我正在尝试使用 TensorFlow 本身提供的 MNIST 数据集在 Google Colab 上运行一个带有 NN 的简单示例。我想获取原始数据并自己安装具有数据的结构。我能够训练 NN,但是当我尝试从测试集中预测一个示例时,我得到了错误
ValueError: Error when checking input: expected dense_input to have shape (784,) but got array with shape (1,).
有人可以帮我解决这个问题吗?我对 Python 和 Keras/TensorFlow 很陌生。
当我跑
print(inp.shape)
正如错误所说,我得到 (784,) 而不是 (1,) 。
我也尝试使用评估测试集
test_loss, test_accuracy = model.evaluate(test_input.T)
,但我也得到了错误
ValueError: Arguments and signature arguments do not match: 25 27.
源代码如下:
# Importing stuff
import tensorflow as tf
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
import numpy as np
import math
import time
import keras
tf.enable_eager_execution()
# Functions
def normalize(images, labels):
images = tf.cast(images, tf.float32)
images /= 255
return images, labels
# Getting dataset
ds, meta = tfds.load('fashion_mnist', as_supervised=True, with_info=True)
test_ds, train_ds = ds['test'], ds['train']
# Preprocess the data
train_ds = train_ds.map(normalize)
test_ds = test_ds.map(normalize)
num_train_examples = meta.splits['train'].num_examples
num_test_examples = meta.splits['test'].num_examples
# Making the train set
train_input = np.empty(shape=(784, num_train_examples))
train_label = np.empty(shape=(1, num_train_examples))
i = 0
for image, label in train_ds:
image = image.numpy().reshape((784, 1))
train_input[:, i] = image.ravel()
label = label.numpy().reshape(1)
train_label[:, i] = label
i = i + 1;
# Making the test set
test_input = np.empty(shape=(784, num_test_examples))
test_label = np.empty(shape=(1, num_test_examples))
i = 0
for image, label in test_ds:
image = image.numpy().reshape((784, 1))
test_input[:, i] = image.ravel()
label = label.numpy().reshape(1)
test_label[:, i] = label
i = i + 1;
# Network
input_layer = tf.keras.layers.Dense(units=784, input_shape=[784])
h1 = tf.keras.layers.Dense(128, activation=tf.nn.relu)
output_layer = tf.keras.layers.Dense(10, activation=tf.nn.softmax)
model = tf.keras.Sequential([input_layer, h1, output_layer])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(train_input.T, train_label.T, epochs=3, steps_per_epoch=100, batch_size=1)
test_loss, test_accuracy = model.evaluate(test_input.T)
inp = test_input[:, 0].T
res = model.predict(inp)
最佳答案
所有 API 函数都需要一个首先包含批量大小的输入形状。在您的情况下,您尝试仅提供 1 个示例,因此没有给出批量大小。您只需通过 reshape 数据将批量大小指定为 1。
使用 numpy:
res = model.predict(np.reshape(inp, len(inp))
predict
的参数方法现在接收形状为 (1, 784)
的数组在您的情况下,将批量大小指定为 1。当您通过将它们堆叠在一起来为函数提供更多示例以进行评估时,批量大小由数组的形状隐式给出,因此不需要进一步的转换。
关于python-3.x - 如何为模型准备测试集形状。使用 keras 和 tensorflow 进行评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55506377/