我正在尝试制作一个简单的Keras模型。但是无论我指定哪种输出形状,输出层始终都是(1,)
形状,因此由于输出层和目标数据形状不匹配,我无法训练模型。
import keras
from keras.models import Sequential
from keras.layers import InputLayer, LSTM, Dense
# 63 is the number of unique characters
# 128 is the length of a sequence of characters
X = ... # X is an one-hot ndarray; X.shape == (96092, 128, 63)
Y = ... # Y is an one-hot ndarray; Y.shape == (96092, 63)
model = Sequential()
model.add(InputLayer([128, 63]))
model.add(LSTM(96))
model.add(Dense(63))
model.compile(
optimizer=keras.optimizers.RMSprop(1e-3, decay=1e-5),
loss=keras.losses.sparse_categorical_crossentropy,
)
model.fit(X, Y) # ValueError: Error when checking target: expected dense_4 to have shape (1,) but got array with shape (63,)
如您所见,输出密集层的形状为(1,)
,但必须具有形状(63,)
。我在做什么错了?
我正在使用预装Keras的Google Colab。
答案 0 :(得分:2)
该错误的意思是输出层的形状为63。但是,由于某些原因,它期望 1。
在这种情况下,期望1的原因是因为您正在使用sparse_categorical_crossentropy
,它期望一个代表输出类别索引的整数。而是使用categorical_crossentropy
,它期望对输出类别进行一次热编码。