Sonu
Sonu

Reputation: 59

Getting size error in opencv while working on MNIST dataset

I am training an MLP using OpenCV and ML modules. I am getting an unknown error that i m not able to fix it:

"error: OpenCV(3.4.3) /io/opencv/modules/ml/src/data.cpp:257: error: (-215:Assertion failed) samples.type() == CV_32F || samples.type() == CV_32S in function 'setData'"

Here are my codes:

    from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train.shape, y_train.shape
import numpy as np
np.unique(y_train)
import matplotlib.pyplot as plt
%matplotlib inline
for i in range(10):
  plt.subplot(2, 5, i+1)
  plt.imshow(X_train[i, :, :], cmap='gray')
  plt.axis('off')
from sklearn.preprocessing import OneHotEncoder
enc=OneHotEncoder(sparse=False, dtype=np.float32)
y_train_pre=enc.fit_transform(y_train.reshape(-1,1))
y_test_pre=enc.fit_transform(y_test.reshape(-1,1))
X_train_pre=X_train.reshape((X_train.shape[0], -1))
X_train_pre=X_train.astype(np.float32) /255.0
X_test_pre=X_test.reshape((X_test.shape[0], -1))
X_test_pre=X_test.astype(np.float32) / 255.0
import cv2
mlp=cv2.ml.ANN_MLP_create()
mlp.setLayerSizes(np.array([784, 512, 512, 10]))
mlp.setActivationFunction(cv2.ml.ANN_MLP_SIGMOID_SYM, 2.5, 1.0)
mlp.setTrainMethod(cv2.ml.ANN_MLP_BACKPROP)
mlp.setBackpropWeightScale(0.00001)
term_mode= (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS)
term_max_iter=10
term_eps=0.01
mlp.setTermCriteria((term_mode, term_max_iter, term_eps))
mlp.train(X_train_pre, cv2.ml.ROW_SAMPLE, y_train_pre)

I got the error after running the last cell. It means while training! I am not able to fix it but is their anything related with the size of layers? or type conversion using numpy? If you guys can guide me, it will help me. Thanks in advance guys.

Upvotes: 0

Views: 149

Answers (1)

A Kruger
A Kruger

Reputation: 2419

The images need to be 1D vectors, but they are being put in with shape [28,28]. For example, this will reshape the images and will work:

mlp.train(X_train_pre.reshape(60000,-1), cv2.ml.ROW_SAMPLE, y_train_pre)

Upvotes: 1

Related Questions