【问题标题】:Trouble with input shape of Embedding layer in KerasKeras 中嵌入层的输入形状出现问题
【发布时间】:2022-12-31 23:15:33
【问题描述】:

我是 Keras Python 建模的新手。我想创建一个模型来生成对我的消息的文本答复,例如聊天机器人。我读到我需要使用 tokenizer 和 to_categorical 方法。有我的代码:

import numpy as np
from keras.layers import Dense, LSTM, Input, Dropout, Embedding
from keras.models import Sequential
from keras.optimizers import Adam
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
from keras.utils import pad_sequences, to_categorical


X = ["Hello!", "Greetings!"]

tokenizer = Tokenizer(1000)

X_seq = pad_sequences(tokenizer.texts_to_sequences(X), 20)

model = Sequential()

model.add(Embedding(1000, 100, input_length=20))
model.add(LSTM(100))
model.add(Dense(1000, "softmax"))

model.summary()

model.compile(loss='categorical_crossentropy', metrics=['accuracy'])

history = model.fit(X_seq, to_categorical(X_seq), epochs=10, batch_size=20)

print(model.predict(pad_sequences(tokenizer.texts_to_sequences(["Greetings!"]), 20)))

价值1000是分词器词汇表中唯一单词的最大数量X是我的消息输入列表。20是文本的最大长度。 我想创建自学模型,但我真的不知道该怎么做。在互联网上,我发现我需要传递相同的输入和输出值,但我的模型应该返回类似 [0.1,0.2,0.3....] 的东西 - 最大值代表模型预测的单词。但是当我尝试适应它时会引发异常:

ValueError: Shapes (None, 20) and (None, 1000) are incompatible

我猜这是输入列表和嵌入层形状的问题。伙计们请帮我处理一下。先感谢您!

【问题讨论】:

    标签: python keras artificial-intelligence lstm


    【解决方案1】:

    在此特定示例中,使用 to_categorical(X_seq) 为您提供具有 [num_of_samples, 20] 形状的目标。这意味着如果您使用此目标变量来拟合模型,它将期望类数等于 20(模型输出形状 = (None, 20))。因此,为了修复您的示例,我建议您将 model.add(Dense(1000, "softmax")) 更改为 model.add(Dense(20, "softmax"))

    此外,在使用tokenizer.texts_to_sequences(X) 之前,我建议您使用tokenizer.fit_on_texts(X) 来安装分词器。

    【讨论】:

    • 那么麻烦是输出模型数据没有输入?
    • 我现在会检查你的建议
    • 不幸的是你的建议没有帮助。程序刚刚引发了新的异常:ValueError: Can not squeeze dim[1], expected a dimension of 1, got 20 for '{{node Squeeze}} = Squeeze[T=DT_FLOAT, squeeze_dims=[-1]](remove_squeezable_dimensions/Squeeze)' with input shapes: [?,20].
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    相关资源
    最近更新 更多