You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

lstm.py 1.0 kB

123456789101112131415161718192021222324252627282930
  1. import torch
  2. import torch.nn as nn
  3. from fastNLP.core.const import Const as C
  4. from fastNLP.modules.encoder.lstm import LSTM
  5. from fastNLP.modules import encoder
  6. from fastNLP.modules.decoder.mlp import MLP
  7. class BiLSTMSentiment(nn.Module):
  8. def __init__(self, init_embed,
  9. num_classes,
  10. hidden_dim=256,
  11. num_layers=1,
  12. nfc=128):
  13. super(BiLSTMSentiment,self).__init__()
  14. self.embed = encoder.Embedding(init_embed)
  15. self.lstm = LSTM(input_size=self.embed.embedding_dim, hidden_size=hidden_dim, num_layers=num_layers, bidirectional=True)
  16. self.mlp = MLP(size_layer=[hidden_dim* 2, nfc, num_classes])
  17. def forward(self, words):
  18. x_emb = self.embed(words)
  19. output, _ = self.lstm(x_emb)
  20. output = self.mlp(output[:,-1,:])
  21. return {C.OUTPUT: output}
  22. def predict(self, words):
  23. output = self(words)
  24. _, predict = output[C.OUTPUT].max(dim=1)
  25. return {C.OUTPUT: predict}