简体   繁体   English

Output 层的形状始终为 (1,)

[英]Output layer's shape is always (1,)

I am trying to make a simple Keras model.我正在尝试制作一个简单的 Keras model。 But regardless of what output shape I am specifying the output layer is always of the shape (1,) so I cannot train my model because of the output layer and target data shapes mismatch. But regardless of what output shape I am specifying the output layer is always of the shape (1,) so I cannot train my model because of the output layer and target data shapes mismatch.

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

As you can see, the shape of the output dense layer is (1,) but it has to be of shape (63,) .如您所见,output 密集层的形状是(1,)但它必须是形状(63,) What am I doing wrong?我究竟做错了什么?

I am using Google Colab with preinstalled Keras.我正在使用预装 Keras 的 Google Colab。

What that error is saying is that the shape of the output layer is 63. However, for some reason, it expects 1.该错误的意思是 output 层的形状63。但是,由于某种原因,它期望为 1。

In this case, the reason it expects 1 is because you are using sparse_categorical_crossentropy , which expects an integer representing the index of the output category.在这种情况下,它期望 1 的原因是因为您使用的是sparse_categorical_crossentropy ,它期望 integer 代表 output 类别的索引。 Instead, use categorical_crossentropy , which expects a one-hot encoding of the output category.相反,使用categorical_crossentropy ,它期望 output 类别的单热编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM