Please help: LSTM input/output dimensions

Wesley_Neill: <p>I am hopelessly lost trying to understand the shape of data coming in and out of an LSTM.</p>
<p>Most attempts to explain the data flow involve using randomly generated data with no real meaning, which is incredibly unhelpful.</p>
<p>Those examples that use real data, like this <a href="https://github.com/udacity/deep-learning-v2-pytorch/blob/master/recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb" rel="nofollow noopener">Udacity notebook</a> on the topic do not explain it well and do not generalize the concept to other kinds/shapes of data beyond strings of text.</p>
<p><a href="https://discuss.pytorch.org/t/understanding-lstm-input/31110/10">This post</a> asks the identical question I have. No attempt at an answer was ever made, except that of the OP, who was unsure if his conclusion was correct.</p>
<p>So, what I’m asking is this: Can someone provide a <strong>simple</strong>, concrete example of using an LSTM  with:</p>
<ol>
<li>“real” data one dimension (one variable).</li>
<li>“real” data with more than one dimension (multiple variables).</li>
</ol>
<p>I would greatly appreciate it!</p>

vdw: <p>I’ve created a <a href="https://github.com/chrisvdweth/ml-toolkit/blob/master/pytorch/notebooks/minimal-example-lstm-input.ipynb" rel="nofollow noopener">minimal example to feed two sentences into an LSTM</a>. I hope that helps. Let me know if anything is unclear.</p>

Wesley_Neill: <p><a class="mention" href="/u/vdw">@vdw</a>,</p>
<p>Thank you for putting in the time to create those examples. Unfortunately, the use of the “embedded” layer has made things even more confusing for me. I truly am lost, and each additional example I see, including that one adds even more confusion.</p>
<p>I feel that part of the problem is that my questions are too general to be understood. <strong>This is my fault.</strong> Therefore, I’m making a final attempt: Below is some code from my attempt to work alongside <a href="https://stackabuse.com/time-series-prediction-using-lstm-with-pytorch-in-python/" rel="nofollow noopener">this tutorial</a>.</p>
<p>I have taken a page from your book and added lots of print statements for various layers outputs. Below the outputs I have listed specific questions that I have.</p>
<pre><code class="lang-auto">class flightLSTM(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, output_size):
        super().__init__()
        self.hidden = None
        self.hidden_size = hidden_size
        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
        self.fc   = nn.Linear(hidden_size, output_size)
        
    def forward(self, x):
       
        print(f'input original shape: {x.shape}')
        
        # format input to shape (batch_size, seq_len, input_size)
        x = x.view(1, len(x), 1) 
        
        print(f'input reshaped for LSTM: {x.shape} \n')
        
        out, self.hidden = self.lstm(x, self.hidden)
        
        print(f'output shape from LSTM layer: {out.shape}')
        print(f'output = \n {out}')
        print()
        
        # flatten output to (batch_size, hidden_size)
        out = out.view(-1, self.hidden_size)
       
        print(f'out reshaped for FC layer: {out.shape} \n')
        out = self.fc(out)
        
        print(f'Fully connected output shape: {out.shape}')
        print(f'output = \n {out}')
        
        return out

input_size = 1
hidden_size = 3
num_layers = 1
output_size = 1

model = flightLSTM(input_size, hidden_size, num_layers, output_size)

# loads a Pandas dataframe
data = sns.load_dataset("flights")
data.passengers = data.passengers.astype(np.float32)

# reserve the last 12 months as test data. 
train_data = data.passengers[:-12].to_numpy()
test_data  = data.passengers[-12:].to_numpy()

# scale and convert training data to tensor
scaler = MinMaxScaler(feature_range=(-1, 1))
scaled_train_data = scaler.fit_transform(train_data.reshape(-1, 1))
scaled_train_data = torch.tensor(scaled_train_data, dtype=torch.float32)

# get target data from known sequence
def get_targets(data, window):
    sequences = []
    L = len(data)
    for i in range(L - window):
        sequence = data[i:i + window]
        label = data[i + window: i + window + 1]
        sequences.append((sequence, label))
        
    return sequences

seq_len  = 12
seq_data = get_targets(scaled_train_data, 12)

</code></pre>
<p>Okay, here are the results of a forward pass through the network:</p>
<pre><code class="lang-auto">
model(seq_data[0][0])

&gt;&gt;&gt;
input original shape: torch.Size([12, 1])
input reshaped for LSTM: torch.Size([1, 12, 1]) 

output shape from LSTM layer: torch.Size([1, 12, 3])
output = 
 tensor([[[ 0.1085,  0.0436, -0.0182],
         [ 0.1245,  0.0547, -0.0299],
         [ 0.1277,  0.0552, -0.0445],
         [ 0.1289,  0.0555, -0.0494],
         [ 0.1298,  0.0570, -0.0462],
         [ 0.1298,  0.0550, -0.0541],
         [ 0.1292,  0.0518, -0.0669],
         [ 0.1295,  0.0504, -0.0733],
         [ 0.1304,  0.0520, -0.0682],
         [ 0.1311,  0.0558, -0.0542],
         [ 0.1313,  0.0602, -0.0369],
         [ 0.1306,  0.0595, -0.0377]]], grad_fn=&lt;TransposeBackward0&gt;)

out reshaped for FC layer: torch.Size([12, 3]) 

Fully connected output shape: torch.Size([12, 1])
output = 
 tensor([[0.2949],
        [0.2927],
        [0.2865],
        [0.2844],
        [0.2862],
        [0.2822],
        [0.2758],
        [0.2726],
        [0.2753],
        [0.2824],
        [0.2911],
        [0.2906]], grad_fn=&lt;AddmmBackward&gt;)
</code></pre>
<p>Okay, so my questions about this specific code:</p>
<ol>
<li>I’m providing one sequence of 12 data points. <strong>That means my batch size is one, correct?</strong>
</li>
<li>If I wanted to provide the network two sequences at a time, I’d need to shape my input to (2, 12, 1). <strong>Does this mean a batch is defined as a set of column vectors, where each sequence is a column?</strong>
</li>
<li>If I wanted to have a batches with two sequences, each one containing two variables per point in time, I’d have to change my shape to (2, 12, 2). <strong>Is that correct?</strong>
</li>
<li>Going back to the data output from the forward pass above. The LSTM layer outputs a tensor of size (1, 12, 3). It’s basically a tensor containing 3 columns. <strong>What does each column represent? What does each element of a given column represent?</strong>
</li>
<li>I need to “flatten” the output tensor before I can feed it to my fully connected layer. <strong>Have I done so correctly?</strong>
</li>
<li>The output of the fully connected layer is essentially a column vector. I specified that my output be of size 1, but I got back 12. I think this means that each element of my 12 point sequence gets run through the layers individually. That makes me think that each element of this output is simply the predicted “next step” for that point in the sequence, but I don’t know. <strong>What does each element of this column vector mean?</strong>
</li>
<li>
<strong>If I am correct about <span class="hashtag">#6</span>, why does the author of this code only have a singleton label for each 12 point sequence?</strong> See the function “get_targets”.</li>
</ol>

vdw: <p>OK, so you’re doing basic time series analysis. In this case, <code>input_size=1</code>, of course.</p>
<p>Before replying to your specific questions, just some general comments:</p>
<ul>
<li>Try not to think too much of row or column vectors. Once you have tensors with more than 2 dimensions (i.e., a matrix), the notions of rows, columns, etc. get quickly confusing. Think about of dimensions and their order.</li>
<li>Network layers only throw an error if the shape of the input is not correct. However, just because the input shape is correct, doesn’t mean that the input itself is correct. Please have a look at a <a href="https://discuss.pytorch.org/t/for-beginners-do-not-use-view-or-reshape-to-swap-dimensions-of-tensors/75524">previous post of mine</a> where I outline some pitfalls of <code>view()</code> and <code>reshape()</code>. For example, the line <code>x = x.view(1, len(x), 1)</code> should be fine since you only have 1 sequence in your batch and <code>input_size=1</code>.</li>
</ul>
<blockquote>
<ol>
<li>I’m providing one sequence of 12 data points. <strong>That means my batch size is one, correct?</strong></li>
</ol>
</blockquote>
<p><strong>Yes!</strong> It’s only a bit unintuitive why the shape of the original <code>x</code> is <code>(12, 1)</code>, since the batch size usually comes first. But I assume that’s just the result of your <code>get_targets()</code> method.</p>
<blockquote>
<ol start="2">
<li>If I wanted to provide the network two sequences at a time, I’d need to shape my input to (2, 12, 1). <strong>Does this mean a batch is defined as a set of column vectors, where each sequence is a column?</strong></li>
</ol>
</blockquote>
<p><strong>Yes!</strong> This needs to be the resulting shape. But again, be careful how you get to this shape without messing up your batch tensor; see link above.</p>
<blockquote>
<ol start="3">
<li>If I wanted to have a batches with two sequences, each one containing two variables per point in time, I’d have to change my shape to (2, 12, 2). <strong>Is that correct?</strong></li>
</ol>
</blockquote>
<p><strong>Yes!</strong> (same comment as above). I would only change the phrasing a bit: the batch contains 2 sequences, each sequence contains 12 data points, and each data point has 2 features (or, is represented by a 2-dim (feature) vector). The term “variable” does fit here.</p>
<blockquote>
<ol start="4">
<li>Going back to the data output from the forward pass above. The LSTM layer outputs a tensor of size (1, 12, 3). It’s basically a tensor containing 3 columns. <strong>What does each column represent? What does each element of a given column represent?</strong></li>
</ol>
</blockquote>
<p>Don’t think for rows or columns. The output of an LSTM gives you the hidden states for each data point in a sequence, for all sequences in a batch. You only have 1 sequence, it comes with 12 data points, each data point has 3 features (since this is the size of the LSTM layer). Maybe this image helps a bit:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/e/e7496a33d835f085d800ee17c0ade05895a89551.png" data-download-href="https://discuss.pytorch.org/uploads/default/e7496a33d835f085d800ee17c0ade05895a89551" title="lstm-output-vs-hidden"><img src="https://discuss.pytorch.org/uploads/default/original/2X/e/e7496a33d835f085d800ee17c0ade05895a89551.png" alt="lstm-output-vs-hidden" data-base62-sha1="x03AlD3QYEjqGqTmkDe4za9w3df" width="583" height="500" data-dominant-color="EDEFF2"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">lstm-output-vs-hidden</span><span class="informations">640×548 20.9 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>In your case, you have h_1 to h_12 since you have 12 data points, and each h_i is a vector with 3 features.</p>
<blockquote>
<ol start="5">
<li>I need to “flatten” the output tensor before I can feed it to my fully connected layer. <strong>Have I done so correctly?</strong></li>
</ol>
</blockquote>
<p><strong>No!</strong> The linear layer expects an input shape of <code>(batch_size, "something")</code>. Since your batch size is 1, <code>out</code> after flattening need to be of shape <code>(1, "something")</code>, but you have <code>(12, "something")</code>. Note that <code>self.fc</code> doesn’t care, it just sees a batch of size 12 and does process it. In your simple case, a quick fix would be <code>out = out.view(1, -1)</code></p>
<blockquote>
<ol start="6">
<li>The output of the fully connected layer is essentially a column vector. I specified that my output be of size 1, but I got back 12. I think this means that each element of my 12 point sequence gets run through the layers individually. That makes me think that each element of this output is simply the predicted “next step” for that point in the sequence, but I don’t know. <strong>What does each element of this column vector mean?</strong></li>
</ol>
</blockquote>
<p>Once you fixed the flattening, <code>self.fc</code> will return an output of size 1. Through the incorrect flattening to created a batch of size 12.</p>
<blockquote>
<ol start="7">
<li><strong>If I am correct about <span class="hashtag-raw">#6</span>, why does the author of this code only have a singleton label for each 12 point sequence?</strong> See the function “get_targets”.</li>
</ol>
</blockquote>
<p>Same issue: you’re flattening is off.</p>

Wesley_Neill: <p>Thank you for your help. I think I’m starting to get it. Sorry if I’m difficult to get through to!</p>
<p>Yes, the time-series data made more sense to me as a beginner than the text data because I could think in terms of ‘samples’ and ‘variables’ <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"> I’ll try tackling text data next.</p>
<p><strong>Follow up 1:</strong> Is there any reason I couldn’t have <code>input_size &gt; 1</code>? What if my time series data has more than just a <code>passengers</code> variable? For instance each point in time might also have an average weather, or some such thing. Can I not use multiple variables to predict a single time series outcome?</p>
<aside class="quote no-group" data-username="vdw" data-post="4" data-topic="89353">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/vdw/48/10074_2.png" class="avatar"> vdw:</div>
<blockquote>
<p>Don’t think for rows or columns. The output of an LSTM gives you the hidden states for each data point in a sequence, for all sequences in a batch. You only have 1 sequence, it comes with 12 data points, each data point has 3 features (since this is the size of the LSTM layer). Maybe this image helps a bit:</p>
</blockquote>
</aside>
<p><strong>follow up 2:</strong> Okay, so LSTM layer outputs/hidden aren’t worth trying to interpret? All of that data is transient and unit-less, not meant for human consumption? At least I understand the shape of it now!</p>
<aside class="quote no-group" data-username="vdw" data-post="4" data-topic="89353">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/vdw/48/10074_2.png" class="avatar"> vdw:</div>
<blockquote>
<p><strong>No!</strong> The linear layer expects an input shape of <code>(batch_size, "something")</code> . Since your batch size is 1, <code>out</code> after flattening need to be of shape <code>(1, "something")</code> , but you have <code>(12, "something")</code> . Note that <code>self.fc</code> doesn’t care, it just sees a batch of size 12 and does process it. In your simple case, a quick fix would be <code>out = out.view(1, -1)</code></p>
</blockquote>
</aside>
<p><strong>follow up 3:</strong> I’m wondering why <code>.view(-1, self.hidden_size)</code> was used here, in this <a href="https://github.com/udacity/deep-learning-v2-pytorch/blob/master/recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb" rel="noopener nofollow ugc">Udacity notebook</a> in their <code>.forward()</code> method?</p>
<p>I thought that <code>.forward(-1, hidden_size)</code> would give me exactly <code>(batch_size, hidden_size)</code>, and it appears to have worked. Perhaps a lucky accident:</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/9/e/9e53c19c5a2528fe740dd8b60370a97f31a4a6b6.png" data-download-href="https://discuss.pytorch.org/uploads/default/9e53c19c5a2528fe740dd8b60370a97f31a4a6b6" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/9/e/9e53c19c5a2528fe740dd8b60370a97f31a4a6b6_2_690x454.png" alt="image" data-base62-sha1="mACT10tX9euReowR8UdiEFpVy2a" width="690" height="454" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/9/e/9e53c19c5a2528fe740dd8b60370a97f31a4a6b6_2_690x454.png, https://discuss.pytorch.org/uploads/default/original/3X/9/e/9e53c19c5a2528fe740dd8b60370a97f31a4a6b6.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/9/e/9e53c19c5a2528fe740dd8b60370a97f31a4a6b6.png 2x" data-dominant-color="FAF9FA"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">711×468 41.5 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>I didn’t understand the stackabuse way which was to do <code>out.view(len(input), -1)</code></p>

vdw: <blockquote>
<p>Yes, the time-series data made more sense to me as a beginner than the text data because I could think in terms of ‘samples’ and ‘variables’ <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"> I’ll try tackling text data next.</p>
</blockquote>
<p>A sentence is nothing but a time series of words. The LSTM doesn’t care <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>
<blockquote>
<p><strong>Follow up 1:</strong> Is there any reason I couldn’t have <code>input_size &gt; 1</code> ? What if my time series data has more than just a <code>passengers</code> variable? For instance each point in time might also have an average weather, or some such thing. Can I not use multiple variables to predict a single time series outcome?</p>
</blockquote>
<p>You can of course have multiple features for each data point, i.e., <code>input_size &gt; 1</code>.</p>
<blockquote>
<p><strong>follow up 2:</strong> Okay, so LSTM layer outputs/hidden aren’t worth trying to interpret? All of that data is transient and unit-less, not meant for human consumption? At least I understand the shape of it now!</p>
</blockquote>
<p>Exactly.</p>
<blockquote>
<p><strong>follow up 3:</strong> I’m wondering why <code>.view(-1, self.hidden_size)</code> was used here, in this <a href="https://github.com/udacity/deep-learning-v2-pytorch/blob/master/recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb" rel="noopener nofollow ugc">Udacity notebook</a> in their <code>.forward()</code> method?</p>
</blockquote>
<p>I’ve looked at the notebook, and I would argue the setup is a bit different. If I understand your code correctly, your input are sequence of length 12 and the target is of length 1 (basically your one label). In the notebook, the target is also a sequence and of the same length as the input sequence, only shifted by one time step. That means with one example, say <code>input=[1,2,3,4]</code> and <code>target=[2,3,4,5]</code>, they simulate a batch of 4 examples:</p>
<ul>
<li>[1] =&gt; 2</li>
<li>[1,2] =&gt; 3</li>
<li>[1,2,3] =&gt; 4</li>
<li>[1,2,3,4] =&gt; 5</li>
</ul>
<p>So there <code>.view(-1, self.hidden_size)</code> makes sense.</p>
<p>Can you post the shape of <code>label</code> as well as the code for the training including the part where you calculate the loss?</p>

Wesley_Neill: <p>You are correct, the label shape is a 1-d array/tensor.</p>
<p>Here is the training code:</p>
<pre><code class="lang-auto">def train(model, epochs, train_set, lr=0.001, print_every=10):
    
    criterion = nn.MSELoss()
    opt = optim.Adam(model.parameters(), lr=lr)
    
    for e in range(epochs):
        hidden = None
        for x, y in train_set:
            
            opt.zero_grad()
            
            out, hidden = model(x, hidden)
        
            loss = criterion(out, y.squeeze(0))
            loss.backward()
            opt.step()
            
            hidden = tuple([h.data for h in hidden])
            
        if e % print_every == 0:
            print(f'Epoch {e} Training Loss: {loss}')
</code></pre>
<p>And here is my <a href="https://github.com/wcneill/jn-neural-networks/blob/master/udacity_pytorch/pytorch13b_LSTM.ipynb" rel="nofollow noopener">full notebook</a>.  At this point, I think I’ve piecemeal copied and pasted the whole thing into this thread. Maybe it will be helpful to have it all in one place.</p>
<p>Thank you again for your ongoing help! I hope to finally understand this stuff and stop bugging you <img src="https://discuss.pytorch.org/images/emoji/apple/sweat_smile.png?v=9" title=":sweat_smile:" class="emoji" alt=":sweat_smile:"></p>

vdw: <p>I think I found the reason show it works despite the wrong flattening. You’re last two lines in your <code>forward()</code> method are:</p>
<pre><code>def forward(self, x, hs):
    ...
    out = self.fc(out)
    return out[-1], hs
</code></pre>
<p>The <code>out[-1]</code> resolves the “artificial” batch of 12 values so you have only 1 output value. If you would have done the flattening correctly the <code>[-1]</code> wouldn’t be needed. The problem is that you sticked too closely to the Udacity tutorial although your setup is different. So you had to make tweaks like the <code>out[-1]</code> to fix it.</p>
<p>It’s a bit like in math exam where you make a mistake at the beginning and an mistake at the end, and both mistakes cancel each other out.</p>

Wesley_Neill: <p>Okay, lesson learned. Shape of input for FC layer is always (batch_size, “something”), which is just like it was for CNNs. Except calculating that “something” was easy back then. It was just the <code>num_channels * height * width</code>.</p>

vdw: <p>Exactly! Here it’s a more tricky since you have the time step dimension.</p>
<p>In fact, with your set up I would not have used the LSTM output but the last hidden state:</p>
<pre><code>def forward(self, x, hs):
    
    # format input to shape (batch_size, seq_len, input_size) 
    x = x.view(1, len(x), 1) 
    
    out, hs = self.lstm(x, hs)
    
    (h, c) = hs # h.shape = (num_layers * num_directions, batch, hidden_size) = (1, 1, 100)

    last_h = h[-1] # Here the [-1] is not because of the sequence but because of the num_layers
    # last_h.shape = (batch, hidden_size) = (1, 100) &lt;== What you want

    # flatten LSTM input for fully connected layer: (batch_size, hidden_size)
    #out = out.view(-1, self.hidden_size) # No longer needed
    
    out = self.fc(last_h) # out.shape = (batch_size, output_size) = (1, 1)
    
    #return out[-1], hs
    return out, hs
</code></pre>
<p>You might want to give this a try.</p>

Wesley_Neill: <aside class="quote no-group" data-username="vdw" data-post="10" data-topic="89353">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/vdw/48/10074_2.png" class="avatar"> vdw:</div>
<blockquote>
<pre><code class="lang-auto">    last_h = h[-1] # Here the [-1] is not because of the sequence but because of the num_layers
</code></pre>
</blockquote>
</aside>
<p>So this solution is a way of getting the “many to one” output, correct?</p>
<p>And this works because the final element of the final hidden state is equal to the final element of the output tensor? That diagram you sent me was helpful.</p>
<p>That would give the correct shape of <code>(batch_size, hidden_size) = (1, 100)</code>. I think I get it!</p>
<h3><a name="okay-but-1" class="anchor" href="#okay-but-1"></a>Okay, but…</h3>
<p>What if I wanted to do a sequence input to sequence output? More like in the NLP Udacity example.</p>
<p>In this case, my LSTM output would have shape <code>(1, 12, 100)</code> if <code>batch_first=True</code>.</p>
<pre><code class="lang-auto">out, hs = self.lstm(x, hs)
out = out.view(1, -1) 

# gives shape (batch_size, "something") = (1, 1200) 
</code></pre>
<p>So that would not work, because the fully connected layer needs input shaped like <code>(batch_size, hidden_size)</code></p>
<p>Instead, if I do this:</p>
<pre><code class="lang-auto">out, hs = self.lstm(x, hs)
out.reshape(-1, self.hidden_size)

# gives shape (12, 100), which works with FC layer.
</code></pre>
<p>But would this be correct, seeing as how we are artificially making a new <code>batch_size = 12</code>, just for the final FC layer?</p>
<p>Or, should I redefine my <code>nn.Linear()</code> layer:</p>
<pre><code class="lang-auto">self.fc = nn.Linear(hidden_size * seq_length, output_size)?
</code></pre>
<p>Where <code>output_size =  12</code> if I want a sequence output.</p>

vdw: <blockquote>
<p>So this solution is a way of getting the “many to one” output, correct?</p>
</blockquote>
<p>Precisely! That is the basic approach that fits your setup where each example is a sequence of 12 data points as input and one 1 target value. Yes, that diagram made things clearer to me as well :).</p>
<blockquote>
<p>What if I wanted to do a sequence input to sequence output?</p>
</blockquote>
<p>Sure, you can also copy the Udacity example basically 1:1, you only need to change your data. For this setup, both inputs and targets are sequences of lengths 12, with the target sequences shifted by one data point. In this case,</p>
<pre><code>reshape(-1, self.hidden_size)
</code></pre>
<p>with a resulting output shape of <code>(12, hidden_size)</code> is the correct way to go, since you need/want 12 output values, one for each of element in your target sequence.</p>
<blockquote>
<p>Or, should I redefine my <code>nn.Linear()</code> layer: <code>self.fc = nn.Linear(hidden_size * seq_length, output_size)?</code> where <code>output_size =  12</code> if I want a sequence output.</p>
</blockquote>
<p>Hm, that’s a good question. Technically you can set up the model like this, I’m just not sure if this “semantically” the right way to do it. Something feels a bit off but I cannot put my finger one it right now :). I would actually be quite curious how the results would be compared to the more established ways.</p>

Wesley_Neill: <aside class="quote no-group" data-username="vdw" data-post="12" data-topic="89353">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/vdw/48/10074_2.png" class="avatar"> vdw:</div>
<blockquote>
<p>. Something feels a bit off but I cannot put my finger one it right now :). I would actually be quite curious how the results would be compared to the more established ways.</p>
</blockquote>
</aside>
<p>Great!</p>
<p>What is the functional difference between “many-to-one” vs a “one-to-one” approaches?</p>
<p>I can see that you would need to “prime” a “many-to-one” model with some past data to get the prediction at the next point. Whereas with a “one-to-one” model, you only need a single past data point. I can’t tell when one or the other would be more beneficial?</p>

vdw: <aside class="quote no-group" data-username="Wesley_Neill" data-post="13" data-topic="89353">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/wesley_neill/48/25709_2.png" class="avatar"> Wesley_Neill:</div>
<blockquote>
<p>What is the functional difference between “many-to-one” vs a “one-to-one” approaches?</p>
</blockquote>
</aside>
<p>What the Udacity tutorial is doing is not a “one-to-one” but more like a “many-to-many” approach. Note that the value of the k-th ouput depends on all the (k-1) inputs. Or in other words, the k-th output depends on the hidden state at time k which in turn depends on the (k-1) hidden states before.</p>
<p>In fact, you can directly map the approach used in the Udacity tutorial to the basic “many-to-one” approach. Instead of having one (input =&gt; target) example such as</p>
<ul>
<li>[1, 2, 3, 4, 5, 6] =&gt; [2, 3, 4, 5, 6, 7]</li>
</ul>
<p>you can convert this into 6 “many-to-one” examples</p>
<ul>
<li>[1] =&gt; [2]</li>
<li>[1, 2] =&gt; [3]</li>
<li>[1, 2, 3] =&gt; [4]</li>
<li>[1, 2, 3, 4] =&gt; [5]</li>
<li>[1, 2, 3, 4, 5] =&gt; [6]</li>
<li>[1, 2, 3, 4, 5, 6] =&gt; [7]</li>
</ul>
<p>From a learning/training perspective, that’s exactly the same. That’s what the <code>reshape(-1, self.hidden_size)</code> in the Udacity tutorial is doing: “internally” creating this artificial batch of, in this case, size 6.</p>

vdw: <aside class="quote no-group" data-username="Wesley_Neill" data-post="11" data-topic="89353">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/wesley_neill/48/25709_2.png" class="avatar"> Wesley_Neill:</div>
<blockquote>
<p><code>self.fc = nn.Linear(hidden_size * seq_length, output_size)</code></p>
</blockquote>
</aside>
<p>I know now why that approach does not seem suitable to me. Here, all output values depend on all input values. That also means that the first output value would depend on the last input value. This means the network can look into the future.</p>
<p>You can still implement it, of course, but it doesn’t seem to fit your prediction task.</p>