簡體   English   中英

Keras 密集層形狀錯誤

[英]Keras Dense layer shape error

我正在使用 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)。

好的,我發現了問題。 我將此作為答案發布,以便它可以幫助也面臨相同問題的其他人。

這不是層配置,而是錯誤的損失函數。

我使用sparse_categorical_crossentropy作為損失,其中標簽必須具有形狀[batch_size]和 dtype int32 或 int64。 我已更改為categorical_crossentropy ,它期望標簽為 [batch_size, num_classes]。

keras 拋出的錯誤信息具有誤導性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM