检查时出错:预期 dense_1_input 具有形状 (None, 5) 但得到的数组具有形状 (200, 1)

数据挖掘 喀拉斯
2021-10-05 13:29:47

我用 Keras 训练了一个模型,保存了它,当我尝试将它应用于新数据时,我遇到了一个错误:

ValueError: Error when checking : expected dense_1_input to have shape (None, 5) but got array with shape (200, 1)

这是训练和保存训练模型的代码:

# Import necessary modules
import numpy as np  # numpy is just used for reading the data
import keras
from keras.layers import Dense
from keras.models import Sequential
from keras.models import load_model # To save and load model


# fix random seed for reproducibility
seed = 7
np.random.seed(seed)

# load the dataset
dataset = np.loadtxt("modiftrain.csv", delimiter=";")

# split into input (X) and output (Y) variables
X = dataset[:,0:5]
Y = dataset[:,5]

# create model
model = Sequential()

# Add the first layer
# input_dim=   has to be the number of input variables. 
# It represent the number of inputs in the first layer,one per column 
model.add(Dense(12, input_dim=5, activation='relu'))

# Add the second layer
model.add(Dense(8, activation='relu'))

# Add the output layer
model.add(Dense(1, activation='sigmoid'))

# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Fit the model
model.fit(X, Y, epochs=150, batch_size=10)

# Evaluate the model
scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

# Save the model
model.save('model_file.h5')

这是预测的代码:

import numpy as np 
from keras.models import load_model # To save and load model

# Load the model
my_model = load_model('model_file.h5')

# Load the test data file and make predictions on it
predictions = my_model.predict(np.loadtxt("modiftest.csv", delimiter=";"))

print(predictions.shape)

my_predictions=my_model.predict(predictions)

print(my_predictions)

错误来了:

Traceback (most recent call last):
  File "predict01.py", line 14, in <module>
    my_predictions=my_model.predict(X_predictions)
  File "C:\Users\Philippe\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\models.py", line 913, in predict
    return self.model.predict(x, batch_size=batch_size, verbose=verbose)
  File "C:\Users\Philippe\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 1695, in predict
    check_batch_axis=False)
  File "C:\Users\Philippe\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 144, in _standardize_input_data
    str(array.shape))
ValueError: Error when checking : expected dense_1_input to have shape (None, 5) but got array with shape (200, 1)

谢谢您的帮助。

3个回答

在执行 predict/predict_classes 时,我遇到了一个非常相似的问题;

  ...
    classes = model.predict(XpredictInputData) 
  File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 1006, in predict
    return self.model.predict(x, batch_size=batch_size, verbose=verbose)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1772, in predict
    check_batch_axis=False)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 153, in _standardize_input_data
    str(array.shape))
ValueError: Error when checking : expected dense_1_input to have shape (None, 100) but got array with shape (100, 1)

之所以出现问题,是因为 keras predict 的输入数组是一维的(由 a)numpy.genfromtxt 从 1 行数据文件生成一维数组和 b)广播故障的组合引起)。Keras predict 似乎需要一个二维数组,即使只有 1 个预测要进行。

我通过在执行预测之前添加以下检查解决了这个问题;

if (XpredictInputData.ndim == 1):
    XpredictInputData = numpy.array([XpredictInputData])

您定义模型的方式需要输入形状 (None, 5) 并将返回形状 (m, 1) 的输出,其中 m 是示例数,即您加载的数组中的行数。

因此,对于您的数据集,您将获得存储在变量预测中的形状 (200, 1) 的输出。我不知道你为什么要在你的预测上调用 predict 方法,但是当你这样做时,它必须导致错误。

@Jed 让我逐步解释您的代码。

1.

#Load the model

my_model = load_model('model_file.h5')

这部分加载上一节中创建的模型

2.

#Load the test data file and make predictions on it

predictions = my_model.predict(np.loadtxt("modiftest.csv", delimiter=";"))

这部分使用测试数据并对其进行预测。您的测试数据大小为 (,5),这意味着每个测试记录中有 5 个特征。

预测后,预测变量将具有每个测试输入的单个值。

所以预测数组的形状是(,1)。

3.

print(predictions.shape)

这将打印预测变量的形状。

4.

my_predictions=my_model.predict(predictions)

这部分不是必需的,因为您已经在预测变量中拥有来自模型的预测值。

你需要做什么:

所以删除部分

my_predictions=my_model.predict(predictions)