# Example of Many-to-One LSTM

**URL:** <https://discuss.pytorch.org/t/example-of-many-to-one-lstm/1728>\
**Category:** Uncategorized\
**Created:** [April 7, 2017, 9:30am UTC](https://discuss.pytorch.org/t/example-of-many-to-one-lstm/1728 "2017-04-07T09:30:59Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Tudor\_Berariu](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/tudor_berariu/32/419_2.png) [@Tudor\_Berariu](https://discuss.pytorch.org/u/Tudor_Berariu)\
**Post date:** [April 7, 2017, 11:03am UTC](https://discuss.pytorch.org/t/example-of-many-to-one-lstm/1728/2 "2017-04-07T11:03:20Z")

</div>

[Recurrent modules](http://pytorch.org/docs/nn.html#recurrent-layers) from `torch.nn` will get an input sequence and output a sequence of the same length. Just take the last element from that output sequence.

Here is a small working example with a 2-layer LSTM neural network:

```
import torch
import torch.nn as nn
from torch.autograd import Variable

time_steps = 10
batch_size = 3
in_size = 5
classes_no = 7

model = nn.LSTM(in_size, classes_no, 2)
input_seq = Variable(torch.randn(time_steps, batch_size, in_size))
output_seq, _ = model(input_seq)
last_output = output_seq[-1]

loss = nn.CrossEntropyLoss()
target = Variable(torch.LongTensor(batch_size).random_(0, classes_no-1))
err = loss(last_output, target)
err.backward()
```

---

_[View the full topic](https://discuss.pytorch.org/t/example-of-many-to-one-lstm/1728)._
