Keras中的小错误:ValueError的错误纠正?

问题描述 投票:-2回答:2

我训练了一个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,).

这是没有意义的,因为shape(array([1,2])) = (2,)因此model.predict函数应该接受它作为有效输入。

相反,当我通过一个形状(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
python tensorflow neural-network keras
2个回答
1
投票

第一个维度是批量维度。因此,即使使用(num_samples,) + (the input shape of network)方法,也必须传递predict形状的数组。这就是为什么当你传递一个形状为(1,2)的数组时,它起作用,因为(1,)表示样本数,而(2,)是网络的输入形状。


0
投票

如果model期望(2,)数组,你应该传递(2,)形状数组

x = x.reshape((2,))
model.predict(x)
© www.soinside.com 2019 - 2024. All rights reserved.