简体   繁体   English

Tensorflow:Model 是用形状 (None, 28, 28) 构造的,但它是在形状不兼容的输入上调用的 (None, 28)

[英]Tensorflow:Model was constructed with shape (None, 28, 28) , but it was called on an input with incompatible shape (None, 28)

I am solving the digit recognition task using the MNIST dataset in keras.我正在使用 keras 中的 MNIST 数据集解决数字识别任务。 The task itself runs smoothly but afterwards I have tried to use the same model for some other handwritten digits that I created with 'paint'.任务本身运行顺利,但之后我尝试将相同的 model 用于我用“paint”创建的其他一些手写数字。 Since the original size was (192, 188, 3), I specifically resized to (28, 28).由于原始尺寸是 (192, 188, 3),所以我特意调整为 (28, 28)。 However, once I try the model on this newly created digit (see attachment), this is the Warning message I get:但是,一旦我尝试在这个新创建的数字上使用 model(见附件),我收到的警告消息是:

WARNING:tensorflow:Model was constructed with shape (None, 28, 28) for input KerasTensor(type_spec=TensorSpec(shape=(None, 28, 28), dtype=tf.float32, name='flatten_input'), name='flatten_input', description="created by layer 'flatten_input'"), but it was called on an input with incompatible shape (None, 28) WARNING:tensorflow:Model 是用形状 (None, 28, 28) 构造的,用于输入 KerasTensor(type_spec=TensorSpec(shape=(None, 28, 28), dtype=tf_input'='3) flatten_input', description="created by layer 'flatten_input'"),但它是在形状不兼容的输入上调用的 (None, 28)

In addition to this error message:除了此错误消息:

ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape (None, 28) ValueError:密集层的输入 0 与该层不兼容:输入形状的预期轴 -1 具有值 784,但接收到的输入具有形状(无,28)

Here is my code:这是我的代码:

import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
# %matplotlib inline
import numpy as np
import pandas as pd
import cv2 as cv

(X_train, y_train),(X_test, y_test)=keras.datasets.mnist.load_data()
# Normalize the train dataset
X_train = tf.keras.utils.normalize(X_train, axis=1)
# Normalize the test dataset
X_test = tf.keras.utils.normalize(X_test, axis=1)

#Build the model object
model = tf.keras.models.Sequential()
# Add the Flatten Layer
model.add(tf.keras.layers.Flatten())
# Build the input and the hidden layers
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
# Build the output layer
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

# Compile the model
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", 
metrics=["accuracy"]) 
model.fit(x=X_train, y=y_train, epochs=20) # Start training process

# Evaluate the model performance
test_loss, test_acc = model.evaluate(x=X_test, y=y_test)
# Print out the model accuracy 
print('\nTest accuracy:', test_acc)

predictions = model.predict([X_test]) # Make prediction

# TRY SAME MODEL WITH NEW DIGIT 

img_6 =  cv.imread("6.png")
img_7 =  cv.imread("7.png")
img_2 =  cv.imread("2.png")


from tensorflow.keras.preprocessing import image

img =  img_7 

img=cv.resize(img, X_train[0].shape, 
            interpolation = cv.INTER_AREA) 
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) 

plt.imshow(img)
plt.show()
img=np.invert(np.array([img]))
img=np.reshape(img, ( 784, 1))
print(img.shape,'fghjkljkhjgfgfgcgvhbjnmnbjv')
plt.imshow(img)
plt.show()

img=np.expand_dims(img, axis=0) # will move it to (1,784)
print(img.shape,'fghjkljkhjgfgfgcgvhbjnmnbjv')
plt.imshow(img)
plt.show()
prediction=model.predict(img) # predict
print ('prediction=',np.argmax(prediction))
plt.imshow(img)
plt.show()

6 7 2

The problem with your code is that your model is expecting a 3-dimensional input (batch_size, width, height) , while you're giving it a single 2-dimensional image (width, height) .您的代码的问题在于您的 model 需要一个 3 维输入(batch_size, width, height) ,而您给它的是一个单一的二维图像(width, height)

You can first reshape your input image to the correct shape, like so:您可以首先将输入图像重塑为正确的形状,如下所示:

np.reshape(img_6, (1, 28, 28))

The first layer on your model is tf.keras.layers.Flatten() ie flatten. model 上的第一层是tf.keras.layers.Flatten()即展平。 means it's like an array.意味着它就像一个数组。 what is that array length is 784(28X28X1 ~ length x width x channel).什么是数组长度为 784(28X28X1 ~ 长度 x 宽度 x 通道)。 so if you put model.summary() the first layer is:所以如果你把model.summary()第一层是:

Layer (type)                 Output Shape              Param #   
=================================================================
flatten (Flatten)            (None, 784)               0   

so it means that predict is expecting input data as (1,784).所以这意味着 predict 期望输入数据为 (1,784)。 you are on right track to resize and gray out the input image, few more steps are needed.你在正确的轨道上调整输入图像的大小和变灰,需要更多的步骤。 please refer to the below code and comment against each line:请参考以下代码并对每一行进行注释:

from tensorflow.keras.preprocessing import image # import image preprocessing
img_6 =  cv.imread("6.png") # shape if (352, 324, 3) for screen snap, this could be different based on read image.
img_6=cv.resize(img_6, X_train[0].shape, 
                interpolation = cv.INTER_AREA) # now its in shape (28, 28, 3) which is~ 2352(28x28x3)
img_6 = cv.cvtColor(img_6, cv.COLOR_BGR2GRAY) # now gray image
img_6=image.img_to_array(img_6) # shape (28, 28, 1) i.e channel 1
img_6= img_6.flatten() # flatten it as model is expecting (None,784) , this will be (784,) i.e 28x28x1 =
img_6=np.expand_dims(img_6, axis=0) # will move it to (1,784)
prediction=model.predict(im1) # predict
print (np.argmax(prediction))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Model 是用形状(无,28)问题构造的 - Model was constructed with shape (None, 28) problem | ValueError:“顺序”层的输入 0 与该层不兼容:预期形状 =(None, 28, 28),找到的形状 =(None, 28, 3) - | ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 28, 28), found shape=(None, 28, 3) tensorflow:Model 是用形状 (None, None, 6) 构造的,但它是在形状不兼容的输入上调用的 - tensorflow:Model was constructed with shape (None, None, 6), but it was called on an input with incompatible shape 将input_data(shape = [None,28,28,1])整形为input_data(shape = [None,28,28]) - Reshape input_data(shape=[None, 28, 28, 1]) to input_data(shape=[None, 28, 28]) ValueError:层“model_23”的输入 0 与层不兼容:预期形状=(无,784),发现形状=(50、28、28) - ValueError: Input 0 of layer "model_23" is incompatible with the layer: expected shape=(None, 784), found shape=(50, 28, 28) 输入形状的预期轴 -1 的值为 28,但收到的输入形状为 (None, 28, 28, 5) - expected axis -1 of input shape to have value 28, but received input with shape (None, 28, 28, 5) 警告:警告:tensorflow:Model 是用形状(无,150)构造的,但它是在形状不兼容的输入上调用的(无,1) - WARNING: WARNING:tensorflow:Model was constructed with shape (None, 150) , but it was called on an input with incompatible shape (None, 1) 预期形状=(无,784),发现形状=(无,28、28) - expected shape=(None, 784), found shape=(None, 28, 28) WARNING:tensorflow:Model 是用形状 (None, 188) 构造的输入,但它是在形状不兼容的输入上调用的 (188,) - WARNING:tensorflow:Model was constructed with shape (None, 188) for input, but it was called on an input with incompatible shape (188,) ValueError: 层序的输入 0 与层不兼容:预期 ndim=4,发现 ndim=3。 收到的完整形状:(无、28、28) - ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: (None, 28, 28)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM