【问题标题】:Tensorflow gives error when predicting: expected axis -1 of input shape to have value 784 but received input with shape [None, 28]Tensorflow 在预测时出错:输入形状的预期轴 -1 的值为 784,但接收到的输入形状为 [None, 28]
【发布时间】:2023-03-19 18:38:01
【问题描述】:

当我使用 Python 在 TensorFlow 中使用神经网络进行预测时,我收到以下错误: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]

我正在尝试按照 Tensorflow 网站上的教程来训练神经网络来对服装进行分类。我写了以下代码:

import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
from skimage import color, io

print(tf.__version__)

data = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = data.load_data()

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images = train_images / 255
test_images = test_images / 255


model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation="relu"),
    keras.layers.Dense(10, activation="softmax")
])

model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"]
)

model.fit(train_images, train_labels, epochs=20)

print(type(test_images))
images = [test_images[0]]

predictions = model.predict(images)

print(class_names[np.argmax(predictions[0])])

非常感谢任何帮助,TIA。

【问题讨论】:

  • 使用model.predict(np.expand_dims(test_images[0],0))
  • @MarcoCerliani 解决了我的问题,谢谢

标签: python tensorflow machine-learning keras neural-network


【解决方案1】:

为了社区的利益,来自评论部分。

通过将model.predict(images) 更改为以下行已解决了该问题。

model.predict(np.expand_dims(test_images[0],0))

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 2021-10-08
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多