我在MNIST数据集上训练了一个基本的神经网络模型。以下是训练的代码:(导入省略(
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data(path='mnist.npz')
x_train, x_test = x_train/255.0, x_test/255.0
#1st Define the model
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape = (28,28)), #input layer
tf.keras.layers.Dense(512, activation=tf.nn.relu), #main computation layer
tf.keras.layers.Dropout(0.2), #Dropout layer to avoid overfitting
tf.keras.layers.Dense(10, activation=tf.nn.softmax) #output layer / Softmax is a classifier AF
])
#2nd Compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
#3rd Fit the model
model.fit(x_train, y_train, epochs=5)
#4th Save the model
model.save('models/mnistCNN.h5')
#5th Evaluate the model
model.evaluate(x_test, y_test)
我想看看这个模型是如何与我自己的输入一起工作的,所以我在这篇文章的帮助下编写了一个预测脚本。我的预测代码是:(导入省略(
model = load_model('models/mnistCNN.h5')
for i in range(3):
img = Image.open(str(i+1) + '.png').convert("L")
img = img.resize((28,28))
im2arr = np.array(img)
im2arr = im2arr/255
im2arr = im2arr.reshape(1, 28, 28, 1)
y_pred = model.predict(im2arr)
print('For Image',i+1,'Prediction = ',y_pred)
首先,我不明白这行的目的:
im2arr = im2arr.reshape(1, 28, 28, 1)
如果有人能阐明为什么这条线是必要的,那将有很大的帮助。
其次,这一行抛出以下错误:
ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (1, 28, 28, 1)
我在这里错过了什么?
第一个维度用于批大小。它是由内部keras.model
添加的。所以这一行只是将其添加到图像数组中。
im2arr = im2arr.reshape(1, 28, 28, 1)
您得到的错误是因为您用于训练的 mnist dataset
中的单个示例具有形状 (28, 28(,因此作为您的输入层。要消除此错误,您需要将此行更改为
im2arr = img.reshape((1, 28, 28))