首页 > 解决方案 > 如何限制 LSTM 的词汇量?

问题描述

我想要一个只预测某个句法类别的模型,例如动词,我可以更新 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 ],

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

标签: pythonnlpdeep-learningkeraslstm

解决方案


在这个模型中,有了这个损失(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'])

然后,代替标签,您应该在表示每个单词的动词/非动词时使用10值。y_train_fit


推荐阅读