Pytorch_RNN_timeseries_many_to_one

RNN timeseries Many to One 다루기

모두를 위한 딥러닝 - 파이토치 강의 참고

  • 이전 포스트에서는 문장의 window 크기만큼을 입력받아 다음 문자를 예측하는 모델을 살펴보았다.

  • 이번 포스트에서는 날마다의 주식 기록인 연속된 데이터를 입력받아 종가를 예측하는 모델을 만들어본다.

  • 7일간의 데이터를 입력으로받아 종가를 예측하는 모델이므로 Many(7일) to One(마지막 종가) 모델이다.

  • 주식의 시작가, 최고가, 최저가, 거래량, 종가 즉, 5개의 값을 input으로 이용하는데 output으로 원하는건 종가 하나이다.

  • 따라서, hidden_dim을 1로 정한다면 RNN셀이 마지막 종가를 바로 예측한다고 생각할 수 있다.

  • 하지만 5개의 변수를 하나의 hidden state로서 RNN셀이 유통하는것은 어려운 일이기 때문에 hidden_dim을 10으로 설정하고 마지막에 fully connected layer을 사용해 마지막 종가를 예측하는 모델을 만든다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#-parameters---
seq_length = 7
data_dim = 5
hidden_dim = 10
output_dim = 1
learning_rate = 0.01
iterations = 500
#---------------

# 모델 생성
class Net(torch.nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, layers):
super(Net, self).__init__()
self.rnn = torch.nn.LSTM(input_dim, hidden_dim, num_layers=layers, batch_first=True)
self.fc = torch.nn.Linear(hidden_dim, output_dim, bias=True)

def forward(self, x):
x, _status = self.rnn(x)
#print(x.shape) --> rnn셀을 통과한 x의 shape을 직접 확인해보자.
x = self.fc(x[:,-1])
return x

net = Net(data_dim, hidden_dim, output_dim, 1)
  • LSTM셀을 정의할때 우리는 input_dim으로 시작가, 최고가, 최저가, 거래량, 종가인 5차원을 넣고 이를 hidden_dim이 10차원으로 유통한다.

  • 이렇게 정의한 LSTM셀을 input data가 통과한 후 shape을 살펴보면 (batch_size, seq_length, hidden_dim)의 모양인것을 확인할 수 있다.

  • 즉, 여기서는 LSTM의 output은 (batch_size, 7, 10)의 모양이며 우리가 원하는것은 7일의 output중 마지막 output data이다.

  • 따라서 LSTM을 통과한 x의 마지막 output data를 fully connected layer에 넣어준다.

  • 이를 통해 10차원의 hidden_dim으로 유통되던 데이터가 마지막 종가인 하나의 값으로 예측할 수 있게된다.

Full Code

Full Code

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×