How to convert from nn.linear to nn.rnn?

How can I make the output form of nn.rnn into [torch.Tensor] like nn.linear?

My MLP code is

class sample(nn.Module):
    def __init__(self):
        super(sample, self).__init__()
        self.n = nn.Linear(1, 64)
        self.nn = nn.Linear(64, 3)
    def forward(self, t, is_train = False, y = None):
        # t = torch.Size([128,1]) / t = <class 'torch.Tensor'>
        ot = self.n(t)
        ott = self.nn(ot)
        return ott

and I tried

class sample(nn.Module):
    def __init__(self, input_size, hidden_dim, num_layer):
        super(NNfunc, self).__init__()
        self.input_size = input_size
        self.hidden_dim = hidden_dim
        self.num_layer = num_layer
        self.rnn = nn.rnn(1, 3, 1)
    def forward(self, t, is_train = False, y = None):
        output = self.rnn(t) 
        return output

but I think this is wrong,
I want to make [output] in the form of [torch.tensor], how should I modify the code?

Hi,
Can you please elaborate on your requirement more?
As of now, I could only understand that you want the output of the RNN block to be of type torch.tensor that I would think it already is.

The docs provide an example of how to use an RNN at the bottom of the page:

https://pytorch.org/docs/stable/generated/torch.nn.RNN.html

rnn = nn.RNN(10, 20, 2)
input = torch.randn(5, 3, 10)
h0 = torch.randn(2, 3, 20)
output, hn = rnn(input, h0)

Note, this is a batch size of 3(dim=1). If you want the batch dim to be first, you can set batch_first=True.

Thank you for your kind answer!!!

1 Like