【问题标题】:Keras Dense layer shape errorKeras Dense 图层形状错误
【发布时间】:2019-01-08 02:44:39
【问题描述】:

我正在使用 keras 创建 LSTM 模型。在训练时,我收到了这个错误。

ValueError: Error when checking target: expected dense_4 to have shape (1,) but got array with shape (34,)

这是我的模型

model = Sequential()

model.add(Embedding(max_words, embedding_dim, input_length=maxlen))    
model.add(LSTM(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(units = 34 ,activation='softmax'))

model.layers[0].set_weights([embedding_matrix])
model.layers[0].trainable = False

model.compile(optimizer='rmsprop',loss='sparse_categorical_crossentropy',metrics=['acc'])

模型总结:

Layer (type)                 Output Shape              Param #   
=================================================================
embedding_2 (Embedding)      (None, 15, 50)            500000    
_________________________________________________________________
lstm_2 (LSTM)                (None, 128)               91648     
_________________________________________________________________
dense_3 (Dense)              (None, 64)                8256      
_________________________________________________________________
dropout_2 (Dropout)          (None, 64)                0         
_________________________________________________________________
dense_4 (Dense)              (None, 34)                2210      
=================================================================
Total params: 602,114
Trainable params: 102,114
Non-trainable params: 500,000
_________________________________________________________________

我正在使用

history = model.fit(X_train, y_train,epochs=100,batch_size=128)

y_train 是一个单热编码标签,形状为(299, 34)。 X_train 的形状为 (299, 15)。

我不确定 为什么模型正在寻找 shape(1,),因为我可以看到 dense_4 (Dense) 的输出形状为 `(None, 34)。

【问题讨论】:

  • 不过,您要适应多少个班级?
  • 目前我用的是34个类(以后会减少)
  • X_train和y_train的形状是什么?
  • @krishna,更新了包含形状细节的问题。
  • @g_p 错误信息多么愚蠢!

标签: python tensorflow machine-learning keras


【解决方案1】:

好的,我找到了问题。我将其发布为答案,以便它可以帮助其他面临同样问题的人。

不是层配置,而是损失函数错误。

我使用sparse_categorical_crossentropy 作为损失,其中标签必须具有[batch_size] 的形状和dtype int32 或int64。我已更改为 categorical_crossentropy,其中期望标签为 [batch_size, num_classes]。

keras 抛出的错误信息具有误导性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2018-04-22
    相关资源
    最近更新 更多