【问题标题】:How to fix problem 'Error when checking input: expected flatten_7_input to have shape (28, 28) but got array with shape (28, 3)'如何解决问题“检查输入时出错:预期 flatten_7_input 的形状为 (28, 28) 但数组的形状为 (28, 3)”
【发布时间】:2019-01-25 00:00:54
【问题描述】:

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

【问题讨论】:

    标签: python tensorflow jupyter-notebook jupyter


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 2019-09-25
      • 1970-01-01
      • 2019-12-17
      相关资源
      最近更新 更多