I have a tensor with my LSTM inputs X (in PyTorch) as well as the matching predictions Y_hat
I want to add the Y_hat as a column to the original X.
The problem is that LSTM a sliding window with seq_length. In case seq. length is 3 and I have 6 variables in X, and 2 variables in Y_hat, I have something like this:
First entry of Tensor:
JavaScript
x
15
15
1
X1:
2
[1 2 3 4 5 6]
3
[5 4 6 7 8 9]
4
[3 6 8 7 4 8]
5
6
Y_hat1
7
[0 1]
8
9
X2:
10
[5 4 6 7 8 9] (repeated from X1)
11
[3 6 8 7 4 8] (repeated from X1)
12
[4 8 7 9 8 4]
13
Y_hat1
14
[1 1]
15
and so on.
Is there an easy pythonesk command to reshape the X with Y so I can quickly get:
JavaScript
1
3
1
[3 6 8 7 4 8 0 1]
2
[4 8 7 9 8 4 1 1]
3
Advertisement
Answer
Having defined X1
, X2
, Y_hat1
, and Y_hat2
:
JavaScript
1
10
10
1
X1 = torch.tensor([[1, 2, 3, 4, 5, 6],
2
[5, 4, 6, 7, 8, 9],
3
[3, 6, 8, 7, 4, 8]])
4
Y_hat1 = torch.tensor([0,1])
5
6
X2 = torch.tensor([[5, 4, 6, 7, 8, 9],
7
[3, 6, 8, 7, 4, 8],
8
[4, 8, 7, 9, 8, 4]])
9
Y_hat2 = torch.tensor([1,1])
10
As well as stacks of inputs (X
) and targets (Y
):
JavaScript
1
3
1
X = torch.stack([X1, X2])
2
Y = torch.stack([Y_hat1, Y_hat2])
3
You can the desired operation using concatenation and stacking operators:
JavaScript
1
4
1
>>> X = torch.stack([X1, X2])
2
>>> Y = torch.stack([Y_hat1, Y_hat2])
3
>>> torch.stack(tuple(torch.cat((x[-1], y)) for x, y in zip(X, Y)))
4
Which expanded corresponds to:
JavaScript
1
4
1
>>> torch.stack((
2
torch.cat((X1[-1], Y_hat1)),
3
torch.cat((X2[-1], Y_hat2))))
4
In a more vectorized fashion you can do:
JavaScript
1
2
1
>>> torch.hstack((X[:,-1], Y))
2