The LSTM-based subnetwork that is used in TFN for text
| 43 | |
| 44 | # TFN 中的文本编码,额外需要lstm 操作 [感觉是audio|video] |
| 45 | class LSTMEncoder(nn.Module): |
| 46 | ''' |
| 47 | The LSTM-based subnetwork that is used in TFN for text |
| 48 | ''' |
| 49 | |
| 50 | def __init__(self, in_size, hidden_size, dropout, num_layers=1, bidirectional=False): |
| 51 | |
| 52 | super(LSTMEncoder, self).__init__() |
| 53 | |
| 54 | if num_layers == 1: |
| 55 | rnn_dropout = 0.0 |
| 56 | else: |
| 57 | rnn_dropout = dropout |
| 58 | |
| 59 | self.rnn = nn.LSTM(in_size, hidden_size, num_layers=num_layers, dropout=rnn_dropout, bidirectional=bidirectional, batch_first=True) |
| 60 | self.dropout = nn.Dropout(dropout) |
| 61 | self.linear_1 = nn.Linear(hidden_size, hidden_size) |
| 62 | |
| 63 | def forward(self, x): |
| 64 | ''' |
| 65 | Args: |
| 66 | x: tensor of shape (batch_size, sequence_len, in_size) |
| 67 | 因为用的是 final_states ,所以特征的 padding 是放在前面的 |
| 68 | ''' |
| 69 | _, final_states = self.rnn(x) |
| 70 | h = self.dropout(final_states[0].squeeze(0)) |
| 71 | y_1 = self.linear_1(h) |
| 72 | return y_1 |