Keras Dense层形状错误

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

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


回答:

好的,我找到了问题所在。我发布这个答案,希望能帮助其他遇到同样问题的人。

问题不在于层的配置,而是选择了错误的损失函数。

我使用了 sparse_categorical_crossentropy 作为损失函数,而标签必须具有形状 [batch_size] 且数据类型为int32或int64。我已将其更改为 categorical_crossentropy,它期望标签的形状为 [batch_size, num_classes]。

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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注