我正在尝试使用Tensorflow上的示例创建NN,并将其输入自己的手写数字以预测正确的标签,但是数组的形状不允许我这样做。
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
path = 'C:/Users/pewdu/Desktop/third.jpg'
img = cv2.imread(path)
new_img = cv2.resize(img, (28, 28))
new_img = new_img / 255.0
print(new_img.shape) # it equals to (28,28,3)
prediction = model.predict(new_img)
所以错误是:
ValueError: Error when checking input: expected flatten_7_input to have shape (28, 28) but got array with shape (28, 3)
答案 0 :(得分:1)
Error
消息说明了一切。
您初始化的模型期望以N x W x H
格式的数据,
使用cv2.imread()
读取图像时,可以看到图像尺寸以W x H x C
格式给出,
您的模型需要灰度归一化图像。而且,由于仅发送一个图像(单个示例),因此需要通过在前面添加一个轴来重塑图像阵列。
img = cv2.imread(path)
new_img = cv2.resize(img, (28, 28))
new_img = new_img[:,:,0] / 255.0 # Take only first channel and normalize
new_img = np.expand_dims(new_img, axis=0) # Adding the dimension
print(new_img.shape) # it equals to (1, 28, 28)
prediction = model.predict(new_img)