MCPcopy Create free account
hub / github.com/Tencent/NeuralNLP-NeuralClassifier / RNN

Class RNN

model/rnn.py:30–108  ·  view source on GitHub ↗

One layer rnn.

Source from the content-addressed store, hash-verified

28
29
30class RNN(torch.nn.Module):
31 """
32 One layer rnn.
33 """
34
35 def __init__(self, input_size, hidden_size, num_layers=1,
36 nonlinearity="tanh", bias=True, batch_first=False, dropout=0,
37 bidirectional=False, rnn_type=RNNType.GRU):
38 super(RNN, self).__init__()
39 self.rnn_type = rnn_type
40 self.num_layers = num_layers
41 self.batch_first = batch_first
42 self.bidirectional = bidirectional
43 if rnn_type == RNNType.LSTM:
44 self.rnn = torch.nn.LSTM(
45 input_size, hidden_size, num_layers=num_layers, bias=bias,
46 batch_first=batch_first, dropout=dropout,
47 bidirectional=bidirectional)
48 elif rnn_type == RNNType.GRU:
49 self.rnn = torch.nn.GRU(
50 input_size, hidden_size, num_layers=num_layers, bias=bias,
51 batch_first=batch_first, dropout=dropout,
52 bidirectional=bidirectional)
53 elif rnn_type == RNNType.RNN:
54 self.rnn = torch.nn.RNN(
55 input_size, hidden_size, vnonlinearity=nonlinearity, bias=bias,
56 batch_first=batch_first, dropout=dropout,
57 bidirectional=bidirectional)
58 else:
59 raise TypeError(
60 "Unsupported rnn init type: %s. Supported rnn type is: %s" % (
61 rnn_type, RNNType.str()))
62
63 def forward(self, inputs, seq_lengths=None, init_state=None,
64 ori_state=False):
65 """
66 Args:
67 inputs:
68 seq_lengths:
69 init_state:
70 ori_state: If true, will return ori state generate by rnn. Else will
71 will return formatted state
72 :return:
73 """
74 if seq_lengths is not None:
75 seq_lengths = seq_lengths.int()
76 sorted_seq_lengths, indices = torch.sort(seq_lengths,
77 descending=True)
78 if self.batch_first:
79 sorted_inputs = inputs[indices]
80 else:
81 sorted_inputs = inputs[:, indices]
82 packed_inputs = torch.nn.utils.rnn.pack_padded_sequence(
83 sorted_inputs, sorted_seq_lengths.cpu(), batch_first=self.batch_first)
84 outputs, state = self.rnn(packed_inputs, init_state)
85 else:
86 outputs, state = self.rnn(inputs, init_state)
87

Callers 4

__init__Method · 0.90
__init__Method · 0.90
__init__Method · 0.90
__init__Method · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected