我训练了一个Keras模型,然而,我很难做出预测 . 我的输入数组的形状为 (400,2)
,输出数组的形状为 (400,1)
. 现在当我将参数 array([1,2])
传递给 model.predict()
函数时,我收到以下错误:
ValueError: Error when checking input: expected dense_1_input to have shape (2,) but got array with shape (1,).
Which is nonsensical since shape(array([1,2])) = (2,) and hence the model.predict function should accept it as a valid input.
相反,当我传递一个形状 (1,2)
的数组时,它是原始的 . 那么Keras实现中是否存在错误?
我的模型如下:
from keras.models import Sequential
from keras.layers import Dense
from keras import optimizers
import numpy as np
data = np.random.rand(400,2)
Y = np.random.rand(400,1)
def base():
model = Sequential()
model.add(Dense(4,activation = 'tanh', input_dim = 2))
model.add(Dense(1, activation = 'sigmoid'))
model.compile(optimizer = optimizers.RMSprop(lr = 0.1), loss = 'binary_crossentropy', metrics= ['accuracy'])
return model
model = base()
model.fit(data,Y, epochs = 10, batch_size =1)
model.predict(np.array([1,2]).reshape(2,1)) #Error
model.predict(np.array([1,2]).reshape(2,)) #Error
model.predict(np.array([1,2]).reshape(1,2)) #Works
2 回答
第一个维度是批量维度 . 因此,即使使用
predict
方法,也必须传递形状为(num_samples,) + (the input shape of network)
的数组 . 这就是为什么当你传递一个形状为(1,2)
的数组时它起作用,因为(1,)
表示样本数,而(2,)
是网络的输入形状 .如果model期望(2,)数组,你应该传递(2,)形状数组