当前位置: 首页 > 知识库问答 >
问题:

层顺序的输入0与层不兼容:输入形状的预期轴-1具有值784

海鸣
2023-03-14

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

我已经检查了模型的输入,它与MNIST的形状相同。x\U列车【0】。形状(784,)和我的图像arr.shape(784,)请帮助!

。。。

    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:layer sequential的输入0与层不兼容:输入形状的轴-1应具有值784,但接收到带形状的输入(无,1)

共有1个答案

诸龙野
2023-03-14

这里需要一个额外的尺寸,arr.restrape(1784)。这是完整的工作代码

(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 = 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)

评估

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()

推论

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()
 类似资料:
  • 完全错误: 问题 我一直在努力建立一个神经网络,因为它不断抱怨收到的形状。x\u trian和y\u train的形状都是(20,)但当我将其输入为input\u形状时,它表示希望输入形状的值为20,但实际上收到了(None,1)。 我不明白(无,1)来自哪里,因为当我打印x_train和y_train的形状时,它给了我(20,)。它们都是数字数组。 代码 我试过的 然后我把input_shape

  • 我正在尝试微调VGG16神经网络,下面是代码: 我得到这个错误: ValueError Traceback(最近一次调用上次)位于 2型号。添加(vgg16\U型号) 3#添加完全连接的层: ---- 5型号。添加(密集(256,激活='relu')) 6型号。添加(辍学(0.5)) /usr/local/anaconda/lib/python3.6/site-packages/keras/eng

  • 问题内容: 我已经检查了所有解决方案,但仍然遇到相同的错误。我的训练图像形状是,我相信它是4维的,但是我不知道为什么错误显示它是5维的。 所以这就是我的定义 问题答案: 问题是。 它实际上应该仅包含3个维度。内部keras将添加批次尺寸使其成为4。 由于您可能使用了4维(包括批处理),因此keras将添加5维。 您应该使用。

  • 问题内容: 在Keras中创建顺序模型时,我知道您在第一层中提供了输入形状。然后,此输入形状会构成 隐式 输入层吗? 例如,下面的模型明确指定了2个密集层,但这实际上是一个3层模型,即由输入形状隐含的一个输入层,一个具有32个神经元的隐藏密集层,然后一个具有10个可能输出的输出层组成的模型吗? 问题答案: 好吧,实际上它实际上 是 一个隐式输入层,即您的模型是一个具有三层“输入,隐藏和输出”的“老

  • 这是我制作的简单的cnn架构。我使用的图像是灰度图。 如果我将通道值指定为粗体分类器中指定的1。添加(卷积2d(32,kernel\u size=3,input\u shape=(50,50,1),激活='relu')) Im获取错误为 检查输入时出错:预期conv2d\u 1\u输入具有形状(50,50,1),但获得具有形状(50,50,3)的数组 但是如果我使用过滤器大小为3,我不会得到任何错

  • 在模型中添加LSTM层之前,我不确定是否需要添加密集输入层。例如,使用以下模型: LSTM层是否为输入层,密集层是否为输出层(即无隐藏层)?或者Keras是否创建了一个输入层,这意味着LSTM层将是一个隐藏层?