Keras:输入层和通过输入正确数据(Keras: Input layer and passing

2019-10-29 06:00发布

我正在学习用Keras功能的API和我已成功构建和编译的典范。 但是,当我打电话model.fit传递数据X和标签y ,我得到了一个错误。 看来我还是没有得到它是如何工作的想法。

该任务划分句子为6类,代码变为:

X_ = ... # shape: (2787, 100) each row a sentence and each column a feature
y_= ... # shape: (2787,)

word_matrix_weights= ... # code to initiate a lookup matrix for vocabulary embeddings. shape: (9825,300)

deep_inputs = Input(shape=(100,))
embedding = Embedding(9825, 300, input_length=100,
                      weights=[word_matrix_weights], trainable=False)(deep_inputs)
flat = Flatten()(embedding)
hidden = Dense(6, activation="softmax")(flat)

model = Model(inputs=deep_inputs, outputs=hidden)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(x=X_,y=y_,epochs=100, batch_size=10, verbose=0) #error here

最后一行产生一个错误:

  File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1555, in fit
    batch_size=batch_size)
  File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1413, in _standardize_user_data
    exception_prefix='target')
  File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 154, in _standardize_input_data
    str(array.shape))
ValueError: Error when checking target: expected dense_1 to have shape (None, 6) but got array with shape (2878, 1)

有什么建议吗?

Answer 1:

你有6个单位的致密层和SOFTMAX激活作为最后一层。 因此,它的输出将是形状的(?,6)其中每个这些6个值的表示属于相应类别的可能性。 既然你已经使用categorical_crossentropy作为损失函数,标签(即y_ )应具有相同的形状(即(2787,6)为好。 你可以独热编码y_使用to_categorical方法:

from keras.utils import to_categorical

y_ = to_categorical(y_)

此一热编码标签,即转换3[0,0,0,1,0,0]假设标签号从零开始)。

如果你不想独热编码的标签,你可以改变loss的说法,以'sparse_categorical_crossentropy'



文章来源: Keras: Input layer and passing input data correctly