检查输入时出错:预期conv2d_1_input具有形状 (1, 28, 28),但得到具有形状 (28, 28, 1)



我正在尝试使用 keras 示例预测一个数字,当我训练我的模型时一切都很好,测试数据的准确性非常好,但是当我想预测一个数字时,我在维度匹配方面遇到了一些问题,我试图更改数字的维度,但它仍然是相同的错误。

这是我的代码: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)

错误 :

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

请帮助我

您的

形状输入很容易 (1 ,1 28,28(

im2arr = np.array(img)
im2arr = im2arr.reshape(1,1,28,28)

相关内容

  • 没有找到相关文章

最新更新