【问题标题】:How to restrict the vocabulary size of an LSTM?如何限制 LSTM 的词汇量?
【发布时间】:2018-04-28 13:12:32
【问题描述】:

我想要一个只预测某个句法类别的模型,例如动词,我可以更新 LSTM 的权重,以便如果单词是动词,它们设置为 1,如果它是任何其他类别,它们设置为 0 ?

这是我当前的代码:

model = Sequential()
model.add(Embedding(vocab_size, embedding_size, input_length=5, weights=[pretrained_weights]))
model.add(Bidirectional(LSTM(units=embedding_size)))
model.add(Dense(2000, activation='softmax'))

for e in zip(model.layers[-1].trainable_weights, model.layers[-1].get_weights()):
    print('Param %s:\n%s' % (e[0], e[1]))

weights = [layer.get_weights() for layer in model.layers]
print(weights)

print(model.summary())

# compile network
model.compile(loss='categorical_crossentropy',
          optimizer = RMSprop(lr=0.001),
          metrics=['accuracy'])

# fit network
history = model.fit(X_train_fit, y_train_fit, epochs=100, verbose=2, validation_data=(X_val, y_val))
score = model.evaluate(x=X_test, y=y_test, batch_size=32)

这些是我要返回的重量:

Param <tf.Variable 'dense_1/kernel:0' shape=(600, 2000) dtype=float32_ref>:
[[-0.00803087  0.0332068  -0.02052244 ...  0.03497869  0.04023124
  -0.02789269]
 [-0.02439511  0.02649114  0.00163587 ... -0.01433908  0.00598045
   0.00556619]
 [-0.01622458 -0.02026448  0.02620039 ...  0.03154427  0.00676246
   0.00236203]
 ...
 [-0.00233192  0.02012364 -0.01562861 ... -0.01857186 -0.02323328
   0.01365903]
 [-0.02556716  0.02962652  0.02400535 ... -0.01870854 -0.04620285
  -0.02111554]
 [ 0.01415684 -0.00216265  0.03434955 ...  0.01771339  0.02930249
   0.002172  ]]
Param <tf.Variable 'dense_1/bias:0' shape=(2000,) dtype=float32_ref>:
[0. 0. 0. ... 0. 0. 0.]
[[array([[-0.023167 , -0.0042483, -0.10572  , ...,  0.089398 , -0.0159   ,
         0.14866  ],
       [-0.11112  , -0.0013859, -0.1778   , ...,  0.063374 , -0.12161  ,
         0.039339 ],
       [-0.065334 , -0.093031 , -0.017571 , ...,  0.16642  , -0.13079  ,
         0.035397 ],

等等。 我可以通过更新权重来做到这一点吗?还是有更有效的方法可以只输出动词? 感谢您的帮助!

【问题讨论】:

  • 我不确定你在问什么。 0. 当前模型的本质是什么? (输入和输出是什么?) 1. 你有标注数据吗:verb/not_verb? 2.在输出层,vocab_size是2000吗?
  • 抱歉,有点混乱!我的问题是:有没有办法只预测动词?因为当我运行模型时,预测的类主要由封闭类单词组成,例如'in'、'all'、'the'等等!我的训练集由句子组成,我的测试集由没有动词的句子组成,我的标签是动词。我将输出层更改为标签类的大小。

标签: python nlp deep-learning keras lstm


【解决方案1】:

在这个模型中,有了这个损失 (categorical_crossentropy),你无法在没有监督的情况下学习动词/非动词标签。因此,您需要标记数据。也许,您可以使用标记语料库,例如Penn Tree Bank 语料库,训练这个模型,该模型接受输入词并预测输出标签(标签的封闭类)。

如果你想在每个单词上都有一个标签和回归,你可以改变模型,让最后一层变成 0 到 1 之间的值:

model.add(Dense(1, activation='sigmoid'))

然后将损失函数改为二进制:

# compile network
model.compile(loss='binary_crossentropy',
          optimizer = RMSprop(lr=0.001),
          metrics=['accuracy'])

那么在y_train_fit 中应该有10 值而不是标签,代表每个单词的动词/非动词。

【讨论】:

    猜你喜欢
    • 2020-07-17
    • 2021-08-02
    • 2021-08-01
    • 1970-01-01
    • 2020-04-18
    • 2020-09-03
    • 2017-06-23
    • 1970-01-01
    • 2017-10-09
    相关资源
    最近更新 更多