0

I am trying to predict a digit by using a keras example, when i trained my model everything is fine and the accuracy of test data is very good, but when i want to predict a digit i have some problem with the match of dimensions , i tryed to change the dimension of the digit but it still the same error .

here is my code : main.py:

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.optimizers import Adam
from keras.layers.convolutional import MaxPooling2D
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
from keras import backend as K


# Read training and test data files
train = pd.read_csv("C:/Users/GOT/Desktop/Arabic Handwritten Digits Dataset CSV/csvTrainImages 60k x 784.csv").values
test  = pd.read_csv("C:/Users/GOT/Desktop/Arabic Handwritten Digits Dataset CSV/csvTestImages 10k x 784.csv").values
train_label  = pd.read_csv("C:/Users/GOT/Desktop/Arabic Handwritten Digits Dataset CSV/csvTrainLabel 60k x 1.csv").values
test_label  = pd.read_csv("C:/Users/GOT/Desktop/Arabic Handwritten Digits Dataset CSV/csvTestLabel 10k x 1.csv").values
print(train.shape)
#Reshape and normalize training data
trainX = train[:, 0:].reshape(train.shape[0],1,28, 28).astype( 'float32' )
X_train = trainX / 255.0
y_train = train_label[:, 0]
# print(y_train.shape)
#Reshape and normalize test data
testX = test[:,0:].reshape(test.shape[0],1, 28, 28).astype( 'float32' )
X_test = testX / 255.0
y_test = test_label[:,0]
# print(y_test.shape)
#one hot encode
from keras.utils import np_utils
number_of_classes = 10
y_train = np_utils.to_categorical(y_train, number_of_classes)
y_test = np_utils.to_categorical(y_test, number_of_classes)
model = Sequential()
K.set_image_dim_ordering('th')
model.add(Conv2D(30, 5, 5, border_mode= 'valid' , input_shape=(1, 28, 28),activation= 'relu' ))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(15, 3, 3, activation= 'relu' ))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation= 'relu' ))
model.add(Dense(50, activation= 'relu' ))
model.add(Dense(10, activation= 'softmax' ))
#   # Compile model
model.compile(loss= 'categorical_crossentropy' , optimizer= 'adam' , metrics=[ 'accuracy' ])
model.fit(X_train, y_train,
          epochs=20,
          batch_size= 160)
model.summary()
model.save('modelRasool.h5')
score = model.evaluate(X_test, y_test, batch_size=128)
print("The Accuracy and the Loss :")
print(score)

teset_predict.py

from keras.models import load_model
from PIL import Image
import numpy as np
model = load_model('C:/Users/GOT/PycharmProjects/test/modelRasool.h5')
for index in range(2):
    img = Image.open('data/' + str(index) + '.png').convert("L")
    img = img.resize((28,28))

    im2arr = np.array(img)
    im2arr = im2arr.reshape(1,28,28,1)
    # Predicting the Test set results
    y_pred = model.predict(im2arr)
    print(y_pred)

the Error :

ValueError: Error when checking input: expected conv2d_1_input to have shape (1, 28, 28) but got array with shape (28, 28, 1)

please help me

Zainab Hasan
  • 39
  • 3
  • 8

1 Answers1

0

it's easy your shape input need be (1 ,1 28,28)

im2arr = np.array(img)
im2arr = im2arr.reshape(1,1,28,28)
joyzaza
  • 186
  • 1
  • 8