层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 784 [英] Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 784

查看:26
本文介绍了层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 784的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 MNIST 上训练过的模型,但是当我放入一个手工制作的图像样本时,它会引发 ValueError:连续层的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 784但是收到了形状为 (None, 1) 的输入

我已经检查了模型的输入,它与 MNIST 的形状相同.x_train[0].shape (784,) 和我的图片 arr.shape (784,) 请帮忙!

...

 from tensorflow.keras.datasets import fashion_mnist从 tensorflow.keras.models 导入顺序从 tensorflow.keras.layers 导入密集,Dropout从 tensorflow.keras 导入工具从 tensorflow.keras.preprocessing 导入图像将 numpy 导入为 np将张量流导入为 tf导入 matplotlib.pyplot 作为 plt%matplotlib 内联打印(x_train[3].shape)x_train = x_train.reshape(60000, 784)x_train = x_train/255模型 = 顺序()model.add(Dense(800, input_dim=784, activation=relu"))model.add(密集(10,激活=softmax"))model.compile(损失=categorical_crossentropy",优化器=SGD",metrics=[accuracy"])历史 = model.fit(x_train, y_train,批量大小=200,时代=100,详细=1)预测 = model.predict(x_train)n = 0plt.imshow(x_train[n].reshape(28, 28), cmap=plt.cm.binary)plt.show()x_train[0].shape #Out[28]: (784,)将 matplotlib.image 导入为 mpimg将 numpy 导入为 np从 PIL 导入图像img = Image.open('yboot.jpg').convert('L')arr = np.asarray(img, dtype=np.float64)arr = arr.reshape(784)形状arr = arr/255打印(arr.shape)#(784,)RealPred = model.predict(arr)

<块引用>

ValueError: 层顺序的输入 0 与层:输入形状的预期轴 -1 具有值 784 但已收到输入形状(无,1)

解决方案

你需要一个额外的维度,arr.reshape(1, 784).这是完整的工作代码

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()# 训练集/数据x_train = x_train.reshape(-1, 28*28)x_train = x_train.astype('float32')/255# 训练集/目标y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)

模型

model = Sequential()model.add(Dense(800, input_dim=784, activation=relu"))model.add(密集(10,激活=softmax"))model.compile(损失=categorical_crossentropy",优化器=SGD",metrics=[accuracy"])历史 = model.fit(x_train, y_train,批量大小=200,时代=20,详细=1)

评估

predictions = model.predict(x_train)n = 0plt.imshow(x_train[n].reshape(28, 28), cmap=plt.cm.binary)plt.title(np.argmax(predictions[n],axis=0))plt.show()

推理

将 numpy 导入为 np导入 cv2def input_prepare(img):img = np.asarray(img) # 转换为数组img = cv2.resize(img, (28, 28 )) # 调整到目标形状img = cv2.bitwise_not(img) # [可选] 我的输入是白色 bg,我把它变成黑色 - {bitwise_not} 把 1 变成 0,0 变成 1img = img/255 # 标准化img = img.reshape(1, 784) # 整形返回图像img = cv2.imread('/content/5.png')orig = img.copy() # 保存以供稍后绘图img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #灰度缩放img = input_prepare(img)打印(img.shape)预测 = 模型.预测(img)plt.imshow(cv2.cvtColor(orig, cv2.COLOR_BGR2RGB))plt.title(np.argmax(pred,axis=1))plt.show()

I have a model which was trained on MNIST, but when I put in a handmade sample of an image it raises ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape (None, 1)

I already checked the input of the model it is in the same shape as MNIST. x_train[0].shape (784,) and my image arr.shape (784,) Please help!

...

    from tensorflow.keras.datasets import fashion_mnist
    from tensorflow.keras.models import Sequential 
    from tensorflow.keras.layers import Dense, Dropout
    from tensorflow.keras import utils
    from tensorflow.keras.preprocessing import image
    import numpy as np
    import tensorflow as tf
    import matplotlib.pyplot as plt
    %matplotlib inline
    print(x_train[3].shape)
    x_train = x_train.reshape(60000, 784)
    x_train = x_train / 255

    model = Sequential()
    model.add(Dense(800, input_dim=784, activation="relu"))
    model.add(Dense(10, activation="softmax"))
    model.compile(loss="categorical_crossentropy", optimizer="SGD", metrics=["accuracy"])
    history = model.fit(x_train, y_train, 
                       batch_size=200, 
                       epochs=100,  
                       verbose=1)

    predictions = model.predict(x_train)
    n = 0
    plt.imshow(x_train[n].reshape(28, 28), cmap=plt.cm.binary)
    plt.show()

    x_train[0].shape     #Out[28]: (784,)


    import matplotlib.image as mpimg

    import numpy as np
    from PIL import Image

    img = Image.open('yboot.jpg').convert('L')
    arr = np.asarray(img, dtype=np.float64)
    arr = arr.reshape(784)
    arr.shape
    arr = arr/255
    print(arr.shape)         # (784,)
    RealPred = model.predict(arr)

ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape (None, 1)

解决方案

You need an extra dimension in here, arr.reshape(1, 784). Here is the full working code

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

# train set / data 
x_train = x_train.reshape(-1, 28*28)
x_train = x_train.astype('float32') / 255

# train set / target 
y_train = tf.keras.utils.to_categorical(y_train , num_classes=10)

Model

model = Sequential()
model.add(Dense(800, input_dim=784, activation="relu"))
model.add(Dense(10, activation="softmax"))

model.compile(loss="categorical_crossentropy", optimizer="SGD", metrics=["accuracy"])
history = model.fit(x_train, y_train, 
                    batch_size=200, 
                    epochs=20,  
                    verbose=1)

Eval

predictions = model.predict(x_train)
n = 0
plt.imshow(x_train[n].reshape(28, 28), cmap=plt.cm.binary)
plt.title(np.argmax(predictions[n], axis=0))
plt.show()

Inference

import numpy as np
import cv2

def input_prepare(img):
    img = np.asarray(img)              # convert to array 
    img = cv2.resize(img, (28, 28 ))   # resize to target shape 
    img = cv2.bitwise_not(img)         # [optional] my input was white bg, I turned it to black - {bitwise_not} turns 1's into 0's and 0's into 1's
    img = img / 255                    # normalize 
    img = img.reshape(1, 784)          # reshaping 
    return img 

img = cv2.imread('/content/5.png')
orig = img.copy() # save for plotting later on 
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scaling 
img = input_prepare(img)
print(img.shape)


pred = model.predict(img)
plt.imshow(cv2.cvtColor(orig, cv2.COLOR_BGR2RGB))
plt.title(np.argmax(pred, axis=1))
plt.show()

这篇关于层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 784的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆