1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| class TextRNN(nn.Module): """Text RNN/LSTM for text classification""" def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes, num_layers=2, bidirectional=True, dropout=0.5): super(TextRNN, self).__init__() self.embedding = nn.Embedding(vocab_size, embed_dim) self.lstm = nn.LSTM( embed_dim, hidden_dim, num_layers=num_layers, bidirectional=bidirectional, batch_first=True, dropout=dropout if num_layers > 1 else 0 ) direction_factor = 2 if bidirectional else 1 self.fc = nn.Linear(hidden_dim * direction_factor, num_classes) self.dropout = nn.Dropout(dropout) def forward(self, x): embedded = self.embedding(x) embedded = self.dropout(embedded) lstm_out, (hidden, cell) = self.lstm(embedded) if self.lstm.bidirectional: hidden_cat = torch.cat((hidden[-2], hidden[-1]), dim=1) else: hidden_cat = hidden[-1] output = self.fc(self.dropout(hidden_cat)) return output
class TextBiLSTM_Attention(nn.Module): """BiLSTM with Attention mechanism""" def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes, num_layers=2, dropout=0.5): super(TextBiLSTM_Attention, self).__init__() self.embedding = nn.Embedding(vocab_size, embed_dim) self.bilstm = nn.LSTM( embed_dim, hidden_dim // 2, num_layers=num_layers, bidirectional=True, batch_first=True, dropout=dropout if num_layers > 1 else 0 ) self.attention = nn.Sequential( nn.Linear(hidden_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, 1) ) self.fc = nn.Linear(hidden_dim, num_classes) self.dropout = nn.Dropout(dropout) def forward(self, x): embedded = self.embedding(x) embedded = self.dropout(embedded) lstm_out, _ = self.bilstm(embedded) attn_weights = self.attention(lstm_out) attn_weights = torch.softmax(attn_weights, dim=1) context = torch.sum(attn_weights * lstm_out, dim=1) output = self.fc(self.dropout(context)) return output
|