keras.model.predict raise ValueError: 错误检查输入时

我在MNIST数据集上训练了一个基础的神经网络模型。以下是训练代码:(导入部分已省略)

mnist = tf.keras.datasets.mnist(x_train, y_train), (x_test, y_test) = mnist.load_data(path='mnist.npz')x_train, x_test = x_train/255.0, x_test/255.0#1st 定义模型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),                       #Dropout层,避免过拟合    tf.keras.layers.Dense(10, activation=tf.nn.softmax) #输出层 / Softmax是一个分类器激活函数])#2nd 编译模型model.compile(optimizer='adam',              loss='sparse_categorical_crossentropy',              metrics=['accuracy'])#3rd 拟合模型model.fit(x_train, y_train, epochs=5)#4th 保存模型model.save('models/mnistCNN.h5')#5th 评估模型model.evaluate(x_test, y_test)

我想看看这个模型如何处理我自己的输入,因此我在这篇文章的帮助下编写了一个预测脚本。我的预测代码是:(导入部分已省略)

model = load_model('models/mnistCNN.h5')for i in range(3):    img = Image.open(str(i+1) + '.png').convert("L")    img = img.resize((28,28))    im2arr = np.array(img)    im2arr = im2arr/255    im2arr = im2arr.reshape(1, 28, 28, 1)    y_pred = model.predict(im2arr)    print('For Image',i+1,'Prediction = ',y_pred)

首先,我不明白这行的用途:

im2arr = im2arr.reshape(1, 28, 28, 1)

如果有人能解释为什么需要这行代码,那将非常有帮助。

其次,这行代码抛出了以下错误:

ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (1, 28, 28, 1)

我在这里遗漏了什么?


回答:

第一维度用于批量大小。这是由keras.model内部添加的。所以这行代码只是将批量大小添加到图像数组中。

im2arr = im2arr.reshape(1, 28, 28, 1)

你得到的错误是因为你用于训练的mnist数据集中的单个样本形状为(28, 28),所以你的输入层也是如此。要消除这个错误,你需要将这行改为

im2arr = img.reshape((1, 28, 28))

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注