如何解决问题“检查输入时出错:期望flatten_7_input具有形状(28,28)但形状为(28,3)的数组”

时间:2019-01-25 00:00:54

标签: python tensorflow jupyter-notebook jupyter

我正在尝试使用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)

1 个答案:

答案 0 :(得分:1)

Error消息说明了一切。

您初始化的模型期望以N x W x H格式的数据,

  • N =示例数
  • W =图片的宽度
  • H =图片的高度

使用cv2.imread()读取图像时,可以看到图像尺寸以W x H x C格式给出,

  • W =图片的宽度
  • H =图像高度
  • C =图像中的通道数(RGB / BGR为3,灰度为1)

您的模型需要灰度归一化图像。而且,由于仅发送一个图像(单个示例),因此需要通过在前面添加一个轴来重塑图像阵列。

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)