【问题标题】:Output layer's shape is always (1,)输出层的形状总是 (1,)
【发布时间】:2019-09-23 18:36:59
【问题描述】:

我正在尝试制作一个简单的 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。

【问题讨论】:

  • 你用的是什么损失函数?
  • 查看带有model.compile 参数的更新帖子

标签: python keras jupyter-notebook shapes


【解决方案1】:

这个错误的意思是输出层的形状 63。但是,由于某种原因,它预计 1。

在这种情况下,它需要 1 的原因是因为您使用的是 sparse_categorical_crossentropy,它需要一个表示输出类别索引的整数。相反,请使用 categorical_crossentropy,它期望输出类别的 one-hot 编码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2020-08-31
    • 2020-10-11
    相关资源
    最近更新 更多