ValueError:层序列的输入0与层(神经网络)不兼容

2024-04-26 06:02:07 发布

您现在位置:Python中文网/ 问答频道 /正文

完全错误:

ValueError: Input 0 of layer sequential is incompatible with the layer: expected 
axis -1 of input shape to have value 20 but received input with shape (None, 1)

问题

我一直在努力建立一个神经网络,因为它不断抱怨收到的形状。x_-trian和y_序列的形状都是(20),但是当我输入它作为输入形状时,它说它期望输入形状的值是20,但是收到了(无,1)

我不知道(None,1)是从哪里来的,因为当我打印x_列和y_列的形状时,它会给我(20,)。它们都是numpy阵列

代码

# (the training_data and testing_data are both just numpy arrays with 0 being the data and 1 being the label)
x_train = training_data[:, 0]  # training feature
y_train = training_data[:, 1]  # training label
x_test = testing_data[:, 0]  # testing feature
y_test = testing_data[:, 1]  # testing label

# Create neural network.
from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(16, input_dim=20, activation='relu', input_shape=(20,)))
model.add(Dense(12, activation='relu'))
model.add(Dense(12, activation='relu'))
model.add(Dense(2, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

我尝试的

然后我将输入形状更改为(无,1),但它说:

ValueError: Shapes (None, 1) and (None, 1, 2) are incompatible

所以,我把它改为(无,1,2),然后它说:

ValueError: Input 0 of layer sequential is incompatible with the layer: expected 
axis -1 of input shape to have value 2 but received input with shape (None, 1)

然后它会将我发回原始错误

然后我发现(20,)只是一个1的维度,所以我将输入_dim改为1,得到:

ValueError: Input 0 of layer sequential is incompatible with the layer: expected 
axis -1 of input shape to have value 20 but received input with shape (None, 1)

结论

我几乎可以肯定这与输入尺寸、输入形状或密度单位有关(第一个model.add上为16)(错误抱怨的那个),但我非常不确定如何更改值以适合我的数据

我知道形状是(20,),我知道维数是1,所以它可能只与稠密单元的值有关(在第一个模型上是16.add,这是编译器抱怨的)。我读了关于单元测量它的内容,但仍然努力理解它


Tags: ofthenoneaddlayerinputdatamodel
1条回答
网友
1楼 · 发布于 2024-04-26 06:02:07

x_train中,由于您有20个数据点,并且每个数据点都是一个数字,因此正确的形状应该是(1,)。Keras希望您输入每个数据点的形状,而不是整个数据集本身的长度。 例如,如果我的数据看起来像

# shape of x_train is (2,3)
# shape of each data point is (3,)    
x_train = np.array([[1,2,1],
                    [1,2,3]])

然后我的输入形状将是(3,)

在您的情况下,可以将模型更改为如下所示:

from keras.layers import Input

model = Sequential()
model.add(Input(shape=(1,)))
model.add(Dense(16, activation='relu'))
model.add(Dense(12, activation='relu'))
model.add(Dense(12, activation='relu'))
model.add(Dense(2, activation='softmax'))

另外,由于您使用的是loss='categorical_crossentropy',因此必须为y_train使用一个热编码,它必须是(20,2)形状。您可以在这里参考如何转换为一种热编码:Convert array of indices to 1-hot encoded numpy array

相关问题 更多 >