Keras密集层形状错误 [英] Keras Dense layer shape error

查看:74
本文介绍了Keras密集层形状错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using keras to create a LSTM model. While training, I am getting this error.

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).

y_train is a one-hot-encoded label with shape (299, 34). X_train is of shape (299, 15).

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

I am not sure why model is looking for shape(1,) as I can see that dense_4 (Dense) has an output shape of `(None, 34).

推荐答案

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

Ok, I found the issue. I am posting this as answer so that it can help others also who is facing the same issue.

这不是层配置,而是错误的丢失功能.

It was not the layer configuration but the wrong loss function.

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

I was using sparse_categorical_crossentropy as loss where labels must have the shape [batch_size] and the dtype int32 or int64. I have changed is to categorical_crossentropy which expect label of [batch_size, num_classes].

keras抛出的错误消息具有误导性.

Error message thrown by keras was misleading.

这篇关于Keras密集层形状错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆