MCPcopy Create free account
hub / github.com/649453932/Chinese-Text-Classification-Pytorch / Model

Class Model

models/TextRNN.py:42–75  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

40
41
42class Model(nn.Module):
43 def __init__(self, config):
44 super(Model, self).__init__()
45 if config.embedding_pretrained is not None:
46 self.embedding = nn.Embedding.from_pretrained(config.embedding_pretrained, freeze=False)
47 else:
48 self.embedding = nn.Embedding(config.n_vocab, config.embed, padding_idx=config.n_vocab - 1)
49 self.lstm = nn.LSTM(config.embed, config.hidden_size, config.num_layers,
50 bidirectional=True, batch_first=True, dropout=config.dropout)
51 self.fc = nn.Linear(config.hidden_size * 2, config.num_classes)
52
53 def forward(self, x):
54 x, _ = x
55 out = self.embedding(x) # [batch_size, seq_len, embeding]=[128, 32, 300]
56 out, _ = self.lstm(out)
57 out = self.fc(out[:, -1, :]) # 句子最后时刻的 hidden state
58 return out
59
60 '''变长RNN,效果差不多,甚至还低了点...'''
61 # def forward(self, x):
62 # x, seq_len = x
63 # out = self.embedding(x)
64 # _, idx_sort = torch.sort(seq_len, dim=0, descending=True) # 长度从长到短排序(index)
65 # _, idx_unsort = torch.sort(idx_sort) # 排序后,原序列的 index
66 # out = torch.index_select(out, 0, idx_sort)
67 # seq_len = list(seq_len[idx_sort])
68 # out = nn.utils.rnn.pack_padded_sequence(out, seq_len, batch_first=True)
69 # # [batche_size, seq_len, num_directions * hidden_size]
70 # out, (hn, _) = self.lstm(out)
71 # out = torch.cat((hn[2], hn[3]), -1)
72 # # out, _ = nn.utils.rnn.pad_packed_sequence(out, batch_first=True)
73 # out = out.index_select(0, idx_unsort)
74 # out = self.fc(out)
75 # return out

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected