【问题标题】:LSTM with classification带分类的 LSTM
【发布时间】:2020-06-30 14:24:22
【问题描述】:

是否可以将 LSTM 与我分类的单词数组一起使用?

例如我有一个包含 1000 个单词的数组:

'绿色' '蓝色的' '红色的' '黄色'

我将单词分类为 Green = 0、Blue = 1、Red = 2、Yellow = 3。

我想预测第 4 个单词。单词可以按顺序以不同的顺序出现。例如,第一个序列可以输入 = green、blue、red、target = yellow 下一个序列是 input = blue、red、yellow、target = green 等等。

也许我不应该为此使用 LSTM,但我想我应该这样做,因为我想检查 3 个较早的输入并预测第 4 个。

这就是我到目前为止所拥有的,我或多或少地坚持我的单词列表的重塑。而且我真的不明白我应该拥有什么 input_shape 。我猜是 Timesteps = 3,features = 4

# define documents
words = [0,1,2,3,2,3,1,0,0,1,2,3,2,0,3,1,1,2,3,0]

words_cat = to_categorical(words,4)

X_train = ?
y_train = ?

# define the model
model = Sequential()
model.add(LSTM(32, input_shape=(3,4)))
model.add(Dense(4, activation='softmax'))

# compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# summarize the model
print(model.summary())

# fit the model
model.fit(X_train, y_train epochs=50, verbose=0)

Br

【问题讨论】:

  • 我建议将系列重新打包成 4 个项目(3 + 1 个 traget)的集合,并使用 NN(使用 one-hot 编码)或任何其他更简单的工具运行多元逻辑回归。 LSTM 在这里有点过头了。

标签: keras deep-learning lstm recurrent-neural-network


【解决方案1】:

正如第一条评论已经提到的,在这种情况下,LSTM 网络可能有点矫枉过正。但我认为你这样做是出于教学原因。

这是一个工作示例:

# define documents
words = [0,1,2,3,2,3,1,0,0,1,2,3,2,0,3,1,1,2,3,0]
# create labels
labels = np.roll(words[:-3], -3)

X_train = np.array([words[i:(i+3)%len(words)] for i in range(len(words)-3)]).reshape(-1,1,3)
y_train = labels

# define the model
model = Sequential()
model.add(LSTM(32, input_shape=(None,3)))
model.add(Dense(4, activation='softmax'))

# compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# summarize the model
print(model.summary())

# fit the model
model.fit(X_train, y_train, epochs=5, batch_size=1, verbose=1)
preds = model.predict(X_train).argmax(1)
print(preds)
print(y_train)

输出:

Epoch 1/5
17/17 [==============================] - 2s 88ms/step - loss: 1.3771 - accuracy: 0.1765
Epoch 2/5
17/17 [==============================] - 0s 9ms/step - loss: 1.3647 - accuracy: 0.3529
Epoch 3/5
17/17 [==============================] - 0s 6ms/step - loss: 1.3568 - accuracy: 0.2353
Epoch 4/5
17/17 [==============================] - 0s 8ms/step - loss: 1.3496 - accuracy: 0.2353
Epoch 5/5
17/17 [==============================] - 0s 7ms/step - loss: 1.3420 - accuracy: 0.4118
[1 2 1 2 0 0 0 1 1 2 1 0 2 1 1 1 2]
[3 2 3 1 0 0 1 2 3 2 0 3 1 1 0 1 2]

所以我把你提供的文字重新塑造了。前三个条目是要训练的系列,第四个条目是标签。

如果您的序列是随机的,模型将很难预测下一个值。否则,您可能想训练更长时间或提供更多示例(但是在这种情况下组合的数量相当有限)。

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 2021-05-04
    • 2018-01-26
    • 2023-04-05
    • 2021-04-27
    • 2021-09-19
    相关资源
    最近更新 更多