Understanding LSTM input

username: Jason_Hinson
cooked: <p>I am trying to implement an LSTM model to predict the stock price of the next day using a sliding window. I have implemented the code in keras previously and keras LSTM looks for a 3d input of (timesteps, (batch_size, features)). I have read through tutorials and watched videos on pytorch LSTM model and I still can’t understand how to implement it. I am going to make up some stock data to use as example so we can be on the same page. I have a tensor filled with data points incremented by hour (time) eg.</p>
<pre><code class="lang-auto">data_from_csv = [[time, open, close, high, low, volume],
                 [1,10,11,15,9,100],
                 [2,11,12,16,9,100],
                 [3,12,13,17,9,100],
                 [4,13,14,18,9,100],
                 [5,14,15,19,9,100],
                 [6,15,16,10,9,100]]
</code></pre>
<p>if my window size is 2 then I would take batches like:</p>
<pre><code class="lang-auto">[[1,10,11,15,9,100],
 [2,11,12,16,9,100]]
</code></pre>
<pre><code class="lang-auto">[[2,11,12,16,9,100],
 [3,12,13,17,9,100]]
</code></pre>
<pre><code class="lang-auto">[[3,12,13,17,9,100],
 [4,13,14,18,9,100]]
</code></pre>
<p>etc.<br>
giving me 5 batches of (2,6). in keras that would be an input of (5,(2,6)) where 5 is the samples or number of timesteps. 2 is the batch/window length and 6 is the number of features. I don’t think I fully understand what pytorch expects for each input/parameter.</p>
<p>in the pytorch docs: <a href="https://pytorch.org/docs/stable/nn.html?highlight=lstm#torch.nn.LSTM" rel="noopener nofollow ugc">nn.LSTM</a> the parameters are:</p>
<blockquote>
<p>input_size: the number of expected features</p>
</blockquote>
<p>In keras that would be [time, open, close, high, low, volume] or an input_size of 6 different data labels per timestep.</p>
<blockquote>
<p>hidden_size: number of features in the hidden state</p>
</blockquote>
<p>I take this as how many lstm cells are in the hidden layer(s) and how many outputs the first layer will have.</p>
<blockquote>
<p>num_layers: number of recurrent layers</p>
</blockquote>
<p>I take this as the number of hidden LSTM layers. so if num_layers = 1 then I will have an input, hidden layer, and output layer</p>
<p>There are more parameters listed but then it describes the input as:</p>
<blockquote>
<p>Inputs: input,(h_0,c_0)<br>
where input is of shape(seq_len, batch, input_size)</p>
</blockquote>
<p>the docs then go on to use the example:</p>
<pre><code class="lang-auto">rnn = nn.LSTM(10, 20, 2)
input = torch.randn(5, 3, 10)
h0 = torch.randn(2, 3, 12)
c0 = torch.randn(2, 3, 12)
output, (hn, cn) = rnn(input, (h0, c0))
</code></pre>
<p>from what I can tell this is what it would look like with the parameter names substituted into the values:</p>
<pre><code class="lang-auto">rnn = nn.LSTM(input_size, hidden_size, num_layers)
</code></pre>
<p>when they instantiate the “input” variable, only one number matches so I assume the “10” represents columns in a data set as features. so If I were to use pytorches example with my example data_from_csv above, with 2 hidden layers that accept double the input features, would it look as follows?</p>
<pre><code class="lang-auto">rnn = nn.LSTM(6, 12, 2)
input = np.ndarray([[[1,10,11,15,9,100],
                     [2,11,12,16,9,100]]])
h0 = torch.randn(2, 1, 12)
c0 = torch.randn(2, 1, 12)
output, (hn, cn) = rnn(input, (h0, c0))
</code></pre>
<p>when pytorch asks for “seq_length” is it asking for how long the window/batch is or how many batches are in the dataset?<br>
when pytorch asks for “batch” is it asking for the whole window of data?<br>
when pytorch asks for “features” is it talking about number of columns of data like time, open, close etc.? is that the same as “input_size”</p>
<p>The more I look at this the less I think I understand it. Let me know if I’m on the right track and please define each term based on my stock example data so I can understand. I almost guarantee I will have some clarifying questions but I cannot find a good tutorial or example that uses multivariate input and any help would be appreciated. Thanks.</p>

username: Crohn_eng
cooked: <p>Hi Jason,</p>
<p>just wanted to let you know that you are not alone: I am encountering your same difficulties in understanding how to use LSTM networks properly.<br>
Moreover, I could not even find the source code for them: reading the docs at <a href="https://pytorch.org/docs/stable/_modules/torch/nn/modules/rnn.html#LSTM" rel="nofollow noopener">https://pytorch.org/docs/stable/_modules/torch/nn/modules/rnn.html#LSTM</a>, the  ´forward´ method uses the ´torch._C._VariableFunctions.lstm_cell´ implementation, that I could not find anywhere.<br>
I think it might be some C++ integration among those in <a href="https://github.com/pytorch/pytorch/tree/master/torch/csrc" rel="nofollow noopener">https://github.com/pytorch/pytorch/tree/master/torch/csrc</a>, but still, I really don’t know where to look at.<br>
Having at least the source code to inspect could be a starting point.</p>

username: Jason_Hinson
cooked: <p>I think the forward function uses C++ only when it handles tensors. Since the forward function defines the path of the tensors through the nn it handles everything using C++. Besides using C++ for nn computations, everything you need is in python to design the flow through the nn(s) which is in the docs. I got an LSTM network running in pytorch by following the Pytorch tutorial example for sentiment analysis but it took a lot of hacking at it to make it work on anything besides word analysis. It still outputs a prediction for every time step instead of each batch which is different than what I’m used to in keras but now I’m almost certain that it has to do with the forward function but I still can’t find any information for common practices around handling the forward function. One thing that was preventing it from working was making sure the hidden state and cell were grabbed and passed to the lstm correctly.</p>

username: Crohn_eng
cooked: <p>Hi Jason,</p>
<p>I am really sorry for answering you with such a long delay, I have been really busy in this period of Christmas’ holidays.<br>
In these days I managed to make some LSTM networks work: not sure if properly… but still, if you need help, or If you figured out how to use LSTMs and would like to compare your work with mine, I will try to answer the questions you asked in the first post.</p>
<blockquote>
<p>when pytorch asks for “seq_length” is it asking for how long the window/batch is or how many batches are in the dataset?</p>
</blockquote>
<p>For your first question, I would say that <code>seq_length</code> corresponds to the length of each window, not to the number of batches in the dataset.</p>
<p>Looking at this post ( <a href="https://discuss.pytorch.org/t/why-3d-input-tensors-in-lstm/4455" class="inline-onebox">Why 3d input tensors in LSTM?</a> ), what I have understood is that using PyTorch’s <code>DataLoader</code>s you can divide your dataset in batches, and each element of the batch can contain a <code>seq_length</code> window of samples.</p>
<p>Let’s make an example: let’s suppose that your dataset contains 10 samples, and you would like to have 5 batches, with each element corresponding to a sequences of 2 samples each.<br>
Since you would like to have 5 batches, having 10 samples in your dataset, this means that your <code>batch_size</code> will be equal to 2, and with each element of the batch being a window/sequence of two elements, this results in something along the line of:</p>
<pre><code class="lang-auto">tensor([[[  1.,  10.,  11.,  15.,   9., 100.],
         [  2.,  11.,  12.,  16.,   9., 100.]],

        [[  2.,  11.,  12.,  16.,   9., 100.],
         [  3.,  12.,  13.,  17.,   9., 100.]]])
</code></pre>
<p>therefore, with dimensions <code>(2=batch_size, 2=seq_length, 6=input_size)</code>.</p>
<p>In order to do so, you have to customize your <code>Dataset</code> class so that it returns at each <code>__getitem__</code> call a window of elements (whose total number will corresponds to <code>seq_length</code>), while with the <code>DataLoader</code> you can play with the batch dimension in order to have different number of windows for each batch.<br>
I wrote this little demo using the tensor you provided before so that my example may be clearer to you:</p>
<pre><code class="lang-auto">import torch
import torch.utils.data as Data
import torch.nn as nn
import torchvision.transforms as transforms

###   Demo dataset

data_from_csv = [[1, 10, 11, 15, 9, 100],
                 [2, 11, 12, 16, 9, 100],
                 [3, 12, 13, 17, 9, 100],
                 [4, 13, 14, 18, 9, 100],
                 [5, 14, 15, 19, 9, 100],
                 [6, 15, 16, 10, 9, 100],
                 [7, 15, 16, 10, 9, 100],
                 [8, 15, 16, 10, 9, 100],
                 [9, 15, 16, 10, 9, 100],
                 [10, 15, 16, 10, 9, 100]]


###   Demo Dataset class

class DemoDatasetLSTM(Data.Dataset):

    """
        Support class for the loading and batching of sequences of samples

        Args:
            dataset (Tensor): Tensor containing all the samples
            sequence_length (int): length of the analyzed sequence by the LSTM
            transforms (object torchvision.transform): Pytorch's transforms used to process the data
    """

    ##  Constructor
    def __init__(self, dataset, sequence_length=1, transforms=None):
        self.dataset = dataset
        self.seq_length = sequence_length
        self.transforms = transforms

    ##  Override total dataset's length getter
    def __len__(self):
        return self.dataset.__len__()

    ##  Override single items' getter
    def __getitem__(self, idx):
        if idx + self.seq_length &gt; self.__len__():
            if self.transforms is not None:
                item = torch.zeros(self.seq_length, self.dataset[0].__len__())
                item[:self.__len__()-idx] = self.transforms(self.dataset[idx:])
                return item, item
            else:
                item = []
                item[:self.__len__()-idx] = self.dataset[idx:]
                return item, item
        else:
            if self.transforms is not None:
                return self.transforms(self.dataset[idx:idx+self.seq_length]), self.transforms(self.dataset[idx:idx+self.seq_length])
            else:
                return self.dataset[idx:idx+self.seq_length], self.dataset[idx:idx+self.seq_length]


###   Helper for transforming the data from a list to Tensor

def listToTensor(list):
    tensor = torch.empty(list.__len__(), list[0].__len__())
    for i in range(list.__len__()):
        tensor[i, :] = torch.FloatTensor(list[i])
    return tensor

###   Dataloader instantiation

# Parameters
seq_length = 2
batch_size = 2
data_transform = transforms.Lambda(lambda x: listToTensor(x))

dataset = DemoDatasetLSTM(data_from_csv, seq_length, transforms=data_transform)
data_loader = Data.DataLoader(dataset, batch_size, shuffle=False, num_workers=2)

for data in data_loader:
    x, _ = data
    print(x)
</code></pre>
<p>As you can see, <code>batch_size</code> works with the total number of samples in your dataset, allowing you to choose how many windows you would like to have, while the single window’s length (<code>seq_length</code>) can be imposed directly customizing the <code>Dataset</code> class.<br>
You may want batches of 5 windows of length 2 as before for instance (<code>batch_size=2</code>, <code>seq_length=2</code>), or directly 10 windows of length 2 (<code>batch_size=1</code>, <code>seq_length=2</code>): it really depends on the specific nature of your problem and of your dataset.</p>
<p><strong><em>Be careful though</em></strong>: as you can see, it may happen that not all your sequences are of the same length!<br>
In the example I wrote before for instance, the last element of the last batch would be composed by a single element window (since we would have reached the end of the dataset): in this case, you have to provide some rules in order to have sequences all of the same length, since <code>DataLoader</code>s won’t work with batches of elements with different dimensions.<br>
That’s why I wrote those checks on the value of <code>idx + self.seq_length</code>.</p>
<blockquote>
<p>when pytorch asks for “batch” is it asking for the whole window of data?<br>
when pytorch asks for “features” is it talking about number of columns of data like time, open, close etc.? is that the same as “input_size”?</p>
</blockquote>
<p>I hope that the explanation I gave you before answers to your second question.  Each element of the batch can be a window of data, it’s up to you.<br>
For the last one, yes, when PyTorch asks for features it is talking about the number of columns, which corresponds to the “input_size” too.</p>
<p>I hope this comment may be helpful to you (and not too late): let me know what do you think about it, or If I have made any errors, in my example code or in my understanding of the functioning of the LSTMs.<br>
I wish you and your family happy holidays!</p>

username: Chris_Oosthuizen
cooked: <p>This is very helpful. Thank you.</p>
<p>I note that both x and y are returning the same  item. Shouldn’t y be the next item in the series to  train LSTM.<br>
x</p>
<pre><code class="lang-auto">tensor([[[  1.,  10.,  11.,  15.,   9., 100.],
         [  2.,  11.,  12.,  16.,   9., 100.]]])
</code></pre>
<p>y</p>
<pre><code class="lang-auto">tensor([[[  3.,  12.,  13.,  17.,   9., 100.]]])
         
</code></pre>
<p>I’m struggling to get guidance on what the shape of target should be.</p>
<p>I’ve trying to amend this code to return x and y  but getting errors everywhere.</p>

username: Crohn_eng
cooked: <p>Hey <a class="mention" href="/u/chris_oosthuizen">@Chris_Oosthuizen</a>,</p>
<p>thanks for your feedback! I’m glad my answer helped you!</p>
<blockquote>
<p>I note that both x and y are returning the same item.</p>
</blockquote>
<p>You are right! To be honest, when I wrote this code my goal was just to give an example on how to prepare the input for a LSTM network properly. Moreover, at the time I was working with recurrent autoencoders, so what I wanted was not to predict the “future”, but to better represent the “present” using information from the “past”. For this reason <em>x</em> and <em>y</em> are returning the same item!</p>
<blockquote>
<p>Shouldn’t y be the next item in the series to train LSTM.</p>
</blockquote>
<blockquote>
<p>I’m struggling to get guidance on what the shape of target should be.</p>
</blockquote>
<p>If I have understood what you are trying to implement, I suggest you to look at this <a href="https://github.com/pytorch/examples/tree/master/time_sequence_prediction" rel="noopener nofollow ugc">repository</a>, and at this post (<a href="https://discuss.pytorch.org/t/lstm-time-sequence-generation/1916">LSTM time sequence generation</a>).<br>
I hope it is close to what you are looking for!</p>
<blockquote>
<p>I’ve trying to amend this code to return x and y but getting errors everywhere.</p>
</blockquote>
<p>This is not really my area of expertise. However, if you have still troubles after having read the discussion <a href="https://discuss.pytorch.org/t/lstm-time-sequence-generation/1916">here</a>, try to post your code and your errors on this thread or on a separate topic on the forum, and we can try to fix them!</p>
<p>Cheers <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=12" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>

username: billtubbs
cooked: <p>This code and description is very helpful thanks.  One question.  What’s the logic for having the <code>listToTensor</code> transformer that generates tensors from the data during training?  Just because the source data in this case is a list of lists or a more fundamental reason?  Also, wouldn’t <code>torch.FloatTensor(data_as_a_list)</code> work the same?</p>

username: Crohn_eng
cooked: <p>Hey <a class="mention" href="/u/billtubbs">@billtubbs</a>,</p>
<p>thanks for the feedback, I really appreciate it!</p>
<blockquote>
<p>What’s the logic for having the  <code>listToTensor</code>  transformer that generates tensors from the data during training? Just because the source data in this case is a list of lists or a more fundamental reason?</p>
</blockquote>
<p>Yes, the only reason is to convert the list of lists in Tensor, so</p>
<blockquote>
<p>Also, wouldn’t  <code>torch.FloatTensor(data_as_a_list)</code>  work the same?</p>
</blockquote>
<p>would work exactly in the same way and it is surely a smarter and faster way for doing the conversion.  Thank you for the suggestion <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=12" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>
<p>Cheers!</p>

username: Wesley_Neill
cooked: <p>This is a great question, one that I am struggling with too.</p>
<p>I see maybe you figured some things out for yourself. I wish that someone with some definitive knowledge had answered it for you. How sure are you that your approach is now correct?</p>
<p>I’m afraid that the LSTM model in pytorch has been very hard for me to wrap my head around compared to other CNNs.</p>

username: aatrey
cooked: <p>Thank you, this was very helpful! I was wondering if there is a way to remove the last sequences once we hit the <code>idx + self.seq_length</code> condition instead of appending 0s as it does now.</p>

username: Crohn_eng
cooked: <p>Hey <a class="mention" href="/u/aatrey">@aatrey</a>,</p>
<p>Thanks for the feedback!</p>
<blockquote>
<p>I was wondering if there is a way to remove the last sequences once we hit the  <code>idx + self.seq_length</code>  condition instead of appending 0s as it does now.</p>
</blockquote>
<p>I think there are several ways for solving this. First two that come to my mind:</p>
<ol>
<li>use <a href="https://pytorch.org/docs/stable/generated/torch.nn.utils.rnn.pad_packed_sequence.html#torch.nn.utils.rnn.pad_packed_sequence" rel="noopener nofollow ugc">Torch pad_packed_sequence</a> for generating batches of sequences of the same length starting from sequences of variable length, and <a href="https://pytorch.org/docs/stable/generated/torch.nn.utils.rnn.pack_padded_sequence.html#torch.nn.utils.rnn.pack_padded_sequence" rel="noopener nofollow ugc">Torch pack_padded_sequence</a> for recovering the sequences in their original form (you can think of these operations as the inverse of each other);</li>
<li>since the root problem is that standard DataLoaders do not handle batches of variable size, write your own DataLoader with a custom <em>collate_fn</em> that handles variable size inputs (take a look <a href="https://discuss.pytorch.org/t/how-to-create-a-dataloader-with-variable-size-input/8278">here</a>).</li>
</ol>
<p>Hope these suggestions can be a good start for your troubleshooting, sorry if my answer couldn’t be more detailed but it has been quite a while since the last time I’ve worked with LSTM in PyTorch, and I don’t want to give you any bad advice.</p>
<p>Cheers <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=12" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>

username: hpf
cooked: <p>Hi,Jason_Hinson,Thank you, finally, someone make complaints about the ambiguity of pytorch’s meaning in 【<strong>seq_len,batch_size,input_size</strong>】. I don’t understand why pytorch interprets parameters <strong>seq_len</strong> and <strong>batch_size</strong> so badly that it gives people ambiguity</p>