python - Keras Dense层形状错误

标签 python tensorflow machine-learning keras

我正在使用 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 抛出的错误信息具有误导性。

关于python - Keras Dense层形状错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51617857/

相关文章:

python - 在 tensorflow 中输入图像数据以进行迁移学习

python - 使用 Keras 和 Tensorflow 进行回归的负面结果

python - 如何使Keras网络不输出全1

python - 在对象上 pickle lru_cached 函数

node.js - Tensorflow 服务 grpc 客户端错误 12

python - import 是否调用 __new__ 静态方法?

machine-learning - 如何创建增量NER训练模型(追加到现有模型中)?

machine-learning - 如何配置 word2vec 不使用负采样?

python - 如何将 Opencv 集成到 Tkinter 窗口中

python - Pandas :条件列创建