【问题标题】:How to understand and debug the error inside keras.model.fit?如何理解和调试 keras.model.fit 中的错误?
【发布时间】:2020-04-18 21:52:41
【问题描述】:

我正在尝试实现一个keras LSTM。我在 keras.model.fit 中遇到错误。我不明白这个错误是什么意思。我的代码如下 -

print(x_train.shape)
print(y_train.shape)

word_input = Input(shape=(mxlen,), dtype="int32", name="word_input")
x1 = Embedding(len(vocab), 100, input_length=mxlen, weights=[embeddings], trainable=False)(word_input)
x1 = LSTM(100)(x1)

y = Dense(6, activation="softmax", name="main_output")(x1)

model = Model(inputs=[word_input], outputs=[y])
adam = optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False)
model.compile(optimizer=adam,loss='categorical_crossentropy',metrics=['categorical_accuracy']) # have to look into it
model.fit(x_train, y_train, epochs=30, batch_size=40, verbose=1)

x_trainy_train 具有以下形状 - (10240, 198)(10240,)

我收到以下错误:

【问题讨论】:

  • 只需将此行从model.compile(optimizer=adam,loss='categorical_crossentropy',metrics=['categorical_accuracy']) # have to look into it 更改为model.compile(optimizer=adam,loss='sparse_categorical_crossentropy',metrics=['accuracy']) # have to look into it。让我知道它是否适合你。

标签: keras lstm keras-layer tf.keras


【解决方案1】:

您的输出层有 6 个输出(可能给出了 6 个类),但 y_train 中的目标标签显然是整数(数组是平的)。 您需要先将 y_train 转换为 one-hot 编码数组,否则无法计算交叉熵损失。输入和输出张量必须始终与模型的输入和输出兼容。

假设 y_train 中有 6 个类,编码为: 0,1,2,3,4,5

您需要转换:

0 -> 1.,0.,0.,0.,0.,0.

1 -> 0.,1.,0.,0.,0.,0.

等等

试试这样:

import tf.keras.backend as K

...

num_classes = 6
y_one_hot = K.one_hot( y_train, num_classes )

....

model.fit(x_train, y_one_hot, epochs=30, batch_size=40, verbose=1)

【讨论】:

    猜你喜欢
    • 2021-08-02
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 2014-11-27
    • 2021-07-05
    • 1970-01-01
    相关资源
    最近更新 更多