我正在尝试根据从一些图像中提取的特征来训练模型,模型训练得很好,但是当我尝试 model.predict 时,它给了我这个错误。 “预计dense_input的形状为(7,),但得到的数组的形状为(1,)” 我了解输入的形状,但错误很奇怪。现在对我来说没有任何意义,我试图打印我给 model.predict 的输入的形状,它很好。
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
trainX = np.array(train_set)
trainY = np.array(train_labels)
model = Sequential()
model.add(Dense(8, input_dim=7, activation='relu'))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, nb_epoch=1200, batch_size=2, verbose=2)
model.save('my_model.h5')
for i in np.array(test_set):
print(i.shape)
dataPrediction = model.predict(i)
print (dataPrediction, '<--- Predicted number')
print (test_labels[i],' <-- Correct answer \n')
print(i.shape) 给我 (7,) 但它给了我错误 检查输入时出错:期望dense_input具有形状(7,),但得到形状为(1,)的数组
最佳答案
这是因为您的模型需要一组样本,但您一次只给它一个样本。
因此,它将样本中的每个特征视为形状 (1,)
的单个样本,这对它来说没有意义,因为您大概有 7 个特征,因此它期望样本为形状(7,)
。
您可以执行model.predict(np.array(test_set))
。
关于python - 预期密集输入具有形状 (7,),但得到形状为 (1,) 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55844330/