Pytorch Lstm 예제 | Pytorch 양방향 Lstm 예제 10 개의 정답

당신은 주제를 찾고 있습니까 “pytorch lstm 예제 – Pytorch 양방향 LSTM 예제“? 다음 카테고리의 웹사이트 https://you.tfvp.org 에서 귀하의 모든 질문에 답변해 드립니다: https://you.tfvp.org/blog. 바로 아래에서 답을 찾을 수 있습니다. 작성자 Aladdin Persson 이(가) 작성한 기사에는 조회수 25,548회 및 좋아요 341개 개의 좋아요가 있습니다.

pytorch lstm 예제 주제에 대한 동영상 보기

여기에서 이 주제에 대한 비디오를 시청하십시오. 주의 깊게 살펴보고 읽고 있는 내용에 대한 피드백을 제공하세요!

d여기에서 Pytorch 양방향 LSTM 예제 – pytorch lstm 예제 주제에 대한 세부정보를 참조하세요

In this video we go through how to code a simple bidirectional LSTM on the very simple dataset MNIST. The focus is just on creating the class for the bidirectional rnn rather than the entire training part which I have done in several previous videos.
Previous video where we create the general training structure:
https://youtu.be/Jy4wM2X21u0
People often ask what courses are great for getting into ML/DL and the two I started with is ML and DL specialization both by Andrew Ng. Below you’ll find both affiliate and non-affiliate links if you want to check it out. The pricing for you is the same but a small commission goes back to the channel if you buy it through the affiliate link.
ML Course (affiliate): https://bit.ly/3qq20Sx
DL Specialization (affiliate): https://bit.ly/30npNrw
ML Course (no affiliate): https://bit.ly/3t8JqA9
DL Specialization (no affiliate): https://bit.ly/3t8JqA9
GitHub Repository:
https://github.com/aladdinpersson/Machine-Learning-Collection
✅ Equipment I use and recommend:
https://www.amazon.com/shop/aladdinpersson
❤️ Become a Channel Member:
https://www.youtube.com/channel/UCkzW5JSFwvKRjXABI-UTAkQ/join
✅ One-Time Donations:
Paypal: https://bit.ly/3buoRYH
Ethereum: 0xc84008f43d2E0bC01d925CC35915CdE92c2e99dc
▶️ You Can Connect with me on:
Twitter – https://twitter.com/aladdinpersson
LinkedIn – https://www.linkedin.com/in/aladdin-persson-a95384153/
GitHub – https://github.com/aladdinpersson
PyTorch Playlist:
https://www.youtube.com/playlist?list=PLhhyoLH6IjfxeoooqP9rhU3HJIAVAJ3Vz

pytorch lstm 예제 주제에 대한 자세한 내용은 여기를 참조하세요.

Pytorch를 활용한 Timeseries 예측 모델(1) – LSTM

이 장에서는 Multiple column을 갖는 Timeseries 형태의 데이터를 예측하는 모델을 만들며 LSTM을 사용한 모델링 과정을 서술한다.

+ 자세한 내용은 여기를 클릭하십시오

Source: eunhye-zz.tistory.com

Date Published: 8/7/2022

View: 5323

[pytoroch 따라하기-9] LSTM을 통한 시계열 데이터 예측모델 구현

[pytorch 따라하기-1] 구글 Colab에 pytorch 세팅하기 https://limitsinx.tistory.com/136 [pytorch 따라하기-2] Tensor생성 및 Backward …

+ 여기에 보기

Source: limitsinx.tistory.com

Date Published: 11/5/2021

View: 2626

[Pytorch] LSTM을 이용한 삼성전자 주가 예측하기 – 코딩도상국

안녕하세요. 오늘은 LSTM을 이용해서 삼성전자 주가를 예측해보겠습니다. 큰 Dataset은 따로 필요하지 않으니 부담 갖지 않고 하시면 될 것 같습니다.

+ 더 읽기

Source: coding-yoon.tistory.com

Date Published: 7/28/2021

View: 4390

Pytorch LSTM – 홍러닝

이번 포스트에서는 시계열 데이터에서 자주 쓰이는 ‘airline-passengers.csv’ 데이터에 대해 Pytorch 프레임워크의 LSTM 모듈을 이용하여 시계열 예측 …

+ 여기에 표시

Source: hongl.tistory.com

Date Published: 10/4/2021

View: 4286

Sequence Models and Long Short-Term Memory Networks

LSTMs in Pytorch. Before getting to the example, note a few things. Pytorch’s LSTM expects all of its inputs to be 3D tensors. The semantics of the axes of …

+ 여기를 클릭

Source: pytorch.org

Date Published: 4/3/2021

View: 3342

Pytorch로 RNN, LSTM 구현하기 – JustKode

Code Example (Natural Language Processing). 해당 코드는 NLP (Natural Language Processing) 을 위한 코드입니다. 앞의 두 단어를 보고, 뒤에 나올 단어를 예측 …

+ 여기에 자세히 보기

Source: justkode.kr

Date Published: 1/27/2021

View: 5184

동서발전 태양광 발전량 예측 AI 경진대회

pytorch기반 간단한 lstm 모델입니다. 중간중간 불필요한 코드는 주석 처리 하였습니다. 많이 부족하니 참고만 해주세요.ㅎ ㅎ 감사합니다.

+ 여기에 표시

Source: dacon.io

Date Published: 12/4/2021

View: 415

PyTorch에서 LSTM 사용: 예제가 포함된 튜토리얼

코드 및 대화형 시각화를 통해 PyTorch에서 LSTM을 사용하는 방법을 설명하는 튜토리얼. Made by Dave Davies using Weights & Biases.

+ 여기를 클릭

Source: wandb.ai

Date Published: 9/19/2021

View: 172

4. LSTM — PseudoLab Tutorial Book

이번 장에서는 LSTM을 사용하여 앞으로의 대한민국 코로나 확진자 수를 예측 … PyTorch에서는 hden_state 를 보존하기 때문에 새로운 시퀀스가 입력될 때마다 …

+ 여기를 클릭

Source: pseudo-lab.github.io

Date Published: 9/11/2021

View: 7610

Pytorch LSTMs for time-series data | by Charlie O’Neill

Even the LSTM example on Pytorch’s official documentation only applies it to a natural language problem, which can be disorienting when trying to get these …

+ 여기에 더 보기

Source: towardsdatascience.com

Date Published: 12/12/2021

View: 1805

주제와 관련된 이미지 pytorch lstm 예제

주제와 관련된 더 많은 사진을 참조하십시오 Pytorch 양방향 LSTM 예제. 댓글에서 더 많은 관련 이미지를 보거나 필요한 경우 더 많은 관련 기사를 볼 수 있습니다.

Pytorch 양방향 LSTM 예제
Pytorch 양방향 LSTM 예제

주제에 대한 기사 평가 pytorch lstm 예제

  • Author: Aladdin Persson
  • Views: 조회수 25,548회
  • Likes: 좋아요 341개
  • Date Published: 2020. 5. 8.
  • Video Url link: https://www.youtube.com/watch?v=jGst43P-TJA

Pytorch를 활용한 Timeseries 예측 모델(1)

728×90

이 장에서는 Multiple column을 갖는 Timeseries 형태의 데이터를 예측하는 모델을 만들며 LSTM을 사용한 모델링 과정을 서술한다. 직전 데이터 N개의 정보를 활용하여 이후 1개 시점을 예측하는 Many to one 방법을 사용하였다.

예시로 사용하는 데이터는 구글 주식 데이터로 1주 전(1~7) 데이터를 가지고 8일째 가격을 예측하는 모델을 만들 것이다.

data-02-stock_daily.csv 0.04MB

Data

주식을 예측하기 위해 사용할 수 있는 데이터는 시가, 종가 등 5개의 컬럼이며 이를 Input dimension이라고 부른다.

이전 7일의 정보를 활용하여 그 다음 종가를 예측하므로 Sequence = 7, Output dimension = 1이다.

LSTM

바닐라 RNN은 비교적 짧은 시퀀스에 대해서만 효과를 보이는 단점이 있어 뒤로 갈수록 맨 처음의 정보량은 손실되고 영향력은 거의 의미가 없을 수도 있게 된다.

RNN으로 만든 언어 모델이 다음 단어를 예측하는 과정을 생각해보자. 예를 들어 “모스크바에 여행을 왔는데 건물도 예브고 먹을 것도 맛있었어. 그런데 글쎄 직장 상사한테 전화가 왔어. 어디냐고 묻더라구 그래서 나는 말했지. 저 여행왔는데요. 여기____” 다음 단어를 예측하기 위해서는 장소 정보가 필요하다. 그런데 장소 정보에 해당되는 단어인 ‘모스크바’는 앞에 위치하고 있고, RNN이 충분한 기억력을 가지고 있지 못한다면 다음 단어를 엉뚱하게 예측한다. 이를 장기 의존성 문제라고 한다.

전통적인 RNN의 이러한 단점을 보완한 RNN의 일종을 장단기 메모리(Long Short-Term Memory)라고 하며, 줄여서 LSTM이라고 한다. LSTM은 은닉 상태(hidden state)를 계산하는 식이 바닐라 RNN보다 조금 더 복잡해졌으며 셀 상태(cell state)라는 값을 추가한다.

728×90

LSTM를 활용한 모델 생성 코드는 아래와 같다.

Time Series Forecasting model

Data Preprocessing

1) 학습/테스트 데이터 분할

import pandas as pd import random import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler # 데이터 불러오기 df = pd.read_csv(‘./data-02-stock_daily.csv’) # 7일간의 데이터가 입력으로 들어가고 batch size는 임의로 지정 seq_length = 7 batch = 100 # 데이터를 역순으로 정렬하여 전체 데이터의 70% 학습, 30% 테스트에 사용 df = df[::-1] train_size = int(len(df)*0.7) train_set = df[0:train_size] test_set = df[train_size-seq_length:]

2) 데이터 스케일링

사용되는 설명변수들의 크기가 서로 다르므로 각 컬럼을 0-1 사이의 값으로 스케일링 한다.

# Input scale scaler_x = MinMaxScaler() scaler_x.fit(train_set.iloc[:, :-1]) train_set.iloc[:, :-1] = scaler_x.transform(train_set.iloc[:, :-1]) test_set.iloc[:, :-1] = scaler_x.transform(test_set.iloc[:, :-1]) # Output scale scaler_y = MinMaxScaler() scaler_y.fit(train_set.iloc[:, [-1]]) train_set.iloc[:, -1] = scaler_y.transform(train_set.iloc[:, [-1]]) test_set.iloc[:, -1] = scaler_y.transform(test_set.iloc[:, [-1]])

3) 데이터셋 생성 및 tensor 형태로 변환

파이토치에서는 3D 텐서의 입력을 받으므로 torch.FloatTensor를 사용하여 np.arrary 형태에서 tensor 형태로 바꿔준다. 파이토치에서는 데이터를 좀 더 쉽게 다룰 수 있도록 유용한 도구로서 데이터셋(Dataset)과 데이터로더(DataLoader)를 제공하는데 이를 사용하면 미니 배치 학습, 데이터 셔플, 병렬 처리 등 간단히 수행할 수 있다. 기본적인 사용 방법은 Dataset을 정의하고 이를 DataLoader에 전달하는 것이다.

from torch.utils.data import TensorDataset # 텐서데이터셋 from torch.utils.data import DataLoader # 데이터로더 # 데이터셋 생성 함수 def build_dataset(time_series, seq_length): dataX = [] dataY = [] for i in range(0, len(time_series)-seq_length): _x = time_series[i:i+seq_length, :] _y = time_series[i+seq_length, [-1]] # print(_x, “–>”,_y) dataX.append(_x) dataY.append(_y) return np.array(dataX), np.array(dataY) trainX, trainY = build_dataset(np.array(train_set), seq_length) testX, testY = build_dataset(np.array(test_set), seq_length) # 텐서로 변환 trainX_tensor = torch.FloatTensor(trainX) trainY_tensor = torch.FloatTensor(trainY) testX_tensor = torch.FloatTensor(testX) testY_tensor = torch.FloatTensor(testY) # 텐서 형태로 데이터 정의 dataset = TensorDataset(trainX_tensor, trainY_tensor) # 데이터로더는 기본적으로 2개의 인자를 입력받으며 배치크기는 통상적으로 2의 배수를 사용 dataloader = DataLoader(dataset, batch_size=batch, shuffle=True, drop_last=True)

LSTM

입력 컬럼은 5개, output 형태는 1개이며 hidden_state는 10개, 학습률은 0.01 등 임의 지정하였다. LSTM 구조를 정의한 Net 클래스에서는 __init__ 생성자를 통해 layer를 초기화하고 forward 함수를 통해 실행한다. reset_hidden_state 은 학습시 seq별로 hidden state를 초기화 하는 함수로 학습시 이전 seq의 영향을 받지 않게 하기 위함이다.

# 설정값 data_dim = 5 hidden_dim = 10 output_dim = 1 learning_rate = 0.01 nb_epochs = 100 class Net(nn.Module): # # 기본변수, layer를 초기화해주는 생성자 def __init__(self, input_dim, hidden_dim, seq_len, output_dim, layers): super(Net, self).__init__() self.hidden_dim = hidden_dim self.seq_len = seq_len self.output_dim = output_dim self.layers = layers self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers=layers, # dropout = 0.1, batch_first=True) self.fc = nn.Linear(hidden_dim, output_dim, bias = True) # 학습 초기화를 위한 함수 def reset_hidden_state(self): self.hidden = ( torch.zeros(self.layers, self.seq_len, self.hidden_dim), torch.zeros(self.layers, self.seq_len, self.hidden_dim)) # 예측을 위한 함수 def forward(self, x): x, _status = self.lstm(x) x = self.fc(x[:, -1]) return x

Training

데이터셋과 알고리즘의 구조를 정의하였다면 실제로 학습이 수행될 함수를 정의한다. verbose는 epoch를 해당 verbose번째 마다 출력하기 위함이고, patience는 train loss를 patience만큼 이전 손실값과 비교해 줄어들지 않으면 학습을 종료시킬 때 사용한다.

학습 과정을 직관적으로 살펴보기 위해 dataloader에 저장되어 있는 데이터를 한 배치씩 for문으로 학습하고 loss를 계산 후 verbose 마다 loss를 출력한다.

early stopping으로 epoch의 횟수는 늘어나지만 학습의 효과가 보이지 않으면 중단하는 코드를 추가하였다.

마지막으로 출력에서는 model.eval() 을 사용하였는데 evaluation 과정에서 사용되지 말아야할 layer들을 알아서 꺼주는 함수다.

def train_model(model, train_df, num_epochs = None, lr = None, verbose = 10, patience = 10): criterion = nn.MSELoss().to(device) optimizer = optim.Adam(model.parameters(), lr = learning_rate) nb_epochs = num_epochs # epoch마다 loss 저장 train_hist = np.zeros(nb_epochs) for epoch in range(nb_epochs): avg_cost = 0 total_batch = len(train_df) for batch_idx, samples in enumerate(train_df): x_train, y_train = samples # seq별 hidden state reset model.reset_hidden_state() # H(x) 계산 outputs = model(x_train) # cost 계산 loss = criterion(outputs, y_train) # cost로 H(x) 개선 optimizer.zero_grad() loss.backward() optimizer.step() avg_cost += loss/total_batch train_hist[epoch] = avg_cost if epoch % verbose == 0: print(‘Epoch:’, ‘%04d’ % (epoch), ‘train loss :’, ‘{:.4f}’.format(avg_cost)) # patience번째 마다 early stopping 여부 확인 if (epoch % patience == 0) & (epoch != 0): # loss가 커졌다면 early stop if train_hist[epoch-patience] < train_hist[epoch]: print(' Early Stopping') break return model.eval(), train_hist # 모델 학습 net = Net(data_dim, hidden_dim, seq_length, output_dim, 1).to(device) model, train_hist = train_model(net, dataloader, num_epochs = nb_epochs, lr = learning_rate, verbose = 20, patience = 10) # epoch별 손실값 fig = plt.figure(figsize=(10, 4)) plt.plot(train_hist, label="Training loss") plt.legend() plt.show() Model Save & Load pythorch는 .pt 또는 .pth 파일 확장자로 모델을 저장한다. 추론을 위해 모델을 저장할 때는 학습된 모델의 매개변수만 저장하면 되는데 torch 사용하여 모델의 state_dict을 저장하는 것이 나중에 모델을 사용할 때 가장 유연하게 사용할 수 있는 모델 저장시 권장하는 방법이라고 한다. 또한 모델을 불러 온 후에는 반드시 model.eval() 를 호출하여 드롭아웃 및 배치 정규화를 평가모드로 설정하도록 한다. 평가모드를 사용하지 않고 테스트를 하게 되면 추론 결과가 일관성없게 추론된다. # 모델 저장 PATH = "./Timeseries_LSTM_data-02-stock_daily_.pth" torch.save(model.state_dict(), PATH) # 불러오기 model = Net(data_dim, hidden_dim, seq_length, output_dim, 1).to(device) model.load_state_dict(torch.load(PATH), strict=False) model.eval() Evaluation 마지막으로 테스트 데이터셋에 대한 검증을 한다. torch.no_grad() 함수를 사용하면 gradient 계산을 수행하지 않게 되어 메모리 사용량을 아껴준다고 한다. 또한 예측시에도 새로운 seq가 입력될 때마다 hidden_state를 초기화해야 이전 seq의 영향을 받지 않는다고 한다. # 예측 테스트 with torch.no_grad(): pred = [] for pr in range(len(testX_tensor)): model.reset_hidden_state() predicted = model(torch.unsqueeze(testX_tensor[pr], 0)) predicted = torch.flatten(predicted).item() pred.append(predicted) # INVERSE pred_inverse = scaler_y.inverse_transform(np.array(pred).reshape(-1, 1)) testY_inverse = scaler_y.inverse_transform(testY_tensor) def MAE(true, pred): return np.mean(np.abs(true-pred)) print('MAE SCORE : ', MAE(pred_inverse, testY_inverse)) MAE 지표를 사용하여 모델의 성능을 측정한 결과 Inverse한 값 기준으로 10.3값이 나왔고, 아래 그림에서는 예측값을 Inverse해서 실제값과 비교하였다. fig = plt.figure(figsize=(8,3)) plt.plot(np.arange(len(pred_inverse)), pred_inverse, label = 'pred') plt.plot(np.arange(len(testY_inverse)), testY_inverse, label = 'true') plt.title("Loss plot") plt.show() 감사합니다 🙂 참고자료 https://wikidocs.net/60690 https://blog.naver.com/PostView.nhn?blogId=na_young_1124&logNo=222281343807&parentCategoryNo=&categoryNo=33&viewDate=&isShowPopularPosts=true&from=search 728x90

[pytoroch 따라하기-9] LSTM을 통한 시계열 데이터 예측모델 구현

[pytorch 따라하기-1] 구글 Colab에 pytorch 세팅하기 https://limitsinx.tistory.com/136

[pytorch 따라하기-2] Tensor생성 및 Backward https://limitsinx.tistory.com/137

[pytorch 따라하기-3] 경사하강법을 통한 선형회귀 구현 https://limitsinx.tistory.com/138

[pytorch 따라하기-4] 인공신경망(ANN) 구현 https://limitsinx.tistory.com/139

[pytorch 따라하기-5] 합성곱신경망(CNN) 구현 https://limitsinx.tistory.com/140

[pytorch 따라하기-6] Neural Style Transfer 구현 https://limitsinx.tistory.com/141

[pytorch 따라하기-7] pix2pix 구현 https://limitsinx.tistory.com/142

[pytorch 따라하기-8] DC-GAN(Deep Convolutional GAN) 구현 https://limitsinx.tistory.com/143

※이 전글에서 정리한 코드/문법은 재설명하지 않으므로, 참고부탁드립니다

※해당 글은 PC에서 보기에 최적화 되어있습니다.

“RNN(Recurrent Neural Network)?”

RNN, 출처 : https://towardsdatascience.com/understanding-rnn-and-lstm-f7cdf6dfc14e

한때 CNN과 더불어 시대를 풍미하던 모델인, RNN에 대해 정리해보도록 하겠습니다.

시계열(Time Sequential)데이터를 학습하는 경우, 필요한 모델인데요. 제가 주로 다루는 모델입니다.

이제까지 General한 Neural Network부터 CNN까지, 모든 데이터들은 Time과 연관되어있지 않았습니다.

즉, 이미지 수만장(MNIST) 혹은 데이터들을 학습시켰을뿐이지, 이게 시간적인 연관성을 전혀 가지진 않았다는 말이죠

예를들면..

“H E L L O” 라는 단어를 자동검색어에 뜨도록 학습시키고 싶다고 가정을 해보시죠

그럼 H라는 단어를 쳤을때 E L L O라고 다음 값이 나올 수 있도록 학습이 되어야겠죠

그럼 기존의 학습방법은 input 한 알파벳을 치면, 그 다음 알파벳이 나오도록 학습을 하는것입니다. 아래처럼요

출처 : 홍콩과기대 김성훈 교수님 딥러닝 강의자료

H -> E

E -> L

L -> L

L -> O

이렇게 1개의 input을 주었을때 다음 output으로는 그다음 알파벳이 나오도록만 학습을 해주는것입니다.

그런데 이상한게 보이시죠??

똑같은 Input을 주었는데 다른 output이 나와야하는 경우가 발생하는 것입니다.

즉, “L이 2번연속나왔을때는 O라는 output을 주도록해라~” 라는 새로운 학습조건이 필요하게 된거죠

이게바로 Time Sequential Data(시계열데이터) 입니다. 이전 과거의 값이 현재의 값에 영향을 미치는거죠

이런 데이터들을 학습시키기 위한 것이 바로 RNN 입니다.

현재 state에서의 x_t(input)과 h_y(hypothesis)로 y_t를 만들어내는것이, 이제까지의 Neural Network 였다면,

과거의 x_t-1, h_t-1, y_t-1이 현재의 y_t를 구성하는데까지 모두 영향을 주는것이라는 거죠

출처 : https://medium.com/analytics-vidhya/in-depth-tutorial-of-recurrent-neural-network-rnn-and-long-short-term-memory-lstm-networks-3a782712a09f

손으로 하나씩 공책에 적어가면서 따라 가다보면 이해가 훨씬 쉽습니다.

개념적인 부분에 대해 정리를 하기위해 Notation을 정리해보겠습니다.

[Notation]

x_(t-1) : 과거의 input 데이터

y_(t-1) : 과거의 output 데이터

h_(t-1) : 과거의 hypothesis

W_(t-1) : 과거의 Weighting

b_h : 과거의 Bias

W_hh : 과거의 Hypothesis를 현재로 넘길때 곱해지는 Weighting

x_t : 현재의 input 데이터

y_t : 현재의 output 데이터

h_t : 현재의 hypothesis

W_xh : 현재의 Weighting

W_hy : 현재의 State와 과거의 Hypothesis를 통해 y_t를 얻기위해 곱해지는 Weighting

b_t : 현재의 Bias

tanh : activation function(기존의 ReLU, sigmoid …와 같은 활성함수)

[개념정리]

과거의 데이터부터 정리해보겠습니다.

h_(t-1) = W_(t-1)*x_(t-1) + b_(t-1) 입니다.

y_(t-1)은 해당 State에서의 Weighting과 Bias값들이 더해진것이므로, 이 다음 State필요한것은 y_(t-1)이 아닌, 좀더 본질적인 값인 h_(t-1)입니다.

따라서, h_(t-1)은 W_hh와 곱해져 다음 State로 넘어가게 됩니다.

이부분이 아래 빨간 네모박스 부분의 동작개요 입니다.

출처 : i2 tutorials, 네모박스는 본인이 침

이것으로 과거데이터의 값은 모두 정리되었습니다. (W_hh * h_(t-1) + b_h)

현재 State로 가보겠습니다.

h_t = W_xh * x_t + b_t 입니다.

여기에 과거의 값을 더해줌으로써 최종적인 현재 state에서의 h_t가 완성됩니다.

h_t = W_xh * x_t + W_hh * h_(t-1)

이것을 Activation Function인 tanh에 통과시킨후, W_hy를 곱하고 bias를 더해주면 최종적으로 현재 state에서의 y값인 y_t 가얻어집니다!

y_t=W_hy * tanh(h_t) + b_t

출처 : i2 tutorials, 네모박스는 본인이 침

즉, 빨간 네모박스 친 부분이, 위에서 현재 state를 기준으로 정리한 값들입니다.

이렇게하면 감이 조금 오는것이, 기존에는 x_t와 관계된 y_t만이 나왔는데

x_(t-1)을 토대로 연산한 h_(t-1)이 관여된, y_t를 얻게 되죠!

즉, 과거의 데이터가 현재의 상태에 영향을 미치게 되는것으로, 이것을 “RNN”이라고 부릅니다.

“LSTM(Long Short Term Memory)”

RNN은 과거의 데이터값들을 기억하지만, Layer가 Deep해질수록 점점 과거의 값들이 “희석”되는 문제가 발생합니다.

즉, 일반적인 Neural Network에서 발생했던 “Vanishing Gradient”와 같은 문제가 생기는거죠

출처 : Kaggle, DS & ML

예를들면, t-1의 값들은 t 상태에서 잘 가지고 있지만, t-100의 값은 거의 영향력이 없게 될것입니다.

따라서, 과거의 데이터들이 희석되는 문제점을 고쳐준 것이 바로 “LSTM(Long Short Term Memory”입니다.

출처 : https://ratsgo.github.io/natural%20language%20processing/2017/03/09/rnnlstm/

상기 그림의 첫번째 이미지가 RNN 두번째가 LSTM인데요

RNN은 위에서 설명한바와 같이, h_(t-1) + W_hx*x_t 를 tanh에 통과시킨채로 해당 Layer에서의 연산이 종료됩니다.

하지만, LSTM에서는 과거의 값을 좀 더 잘 보존할 수 있도록 내부적으로 여러가지 연산장치들을 추가해놓았습니다.

(망각/입력/출력 게이트라는 세개의 게이트를 현재의 데이터와 한스텝전 Hidden state를 기반으로 연산하여 현재 Hidden state와 출력값을 도출하는 시스템입니다. 수식은 복잡해보이지만, 손으로 수식을 따라가보면 별것 아닙니다..)

즉, RNN의 Process Sequence를 따르되, Cell은 “LSTM”이라는 독특한 내부구조를 적용시켜주는것입니다.

– 하기 이미지는 LSTM의 “Cell” 내부를 수식화해서 정리해놓은 것입니다.

출처 : https://www.researchgate.net/figure/Structure-of-the-LSTM-cell-and-equations-that-describe-the-gates-of-an-LSTM-cell_fig5_329362532 출처 : https://ratsgo.github.io/natural%20language%20processing/2017/03/09/rnnlstm/

코드

# Created by Hyunjun,JANG

# limitsinx.tistory.com

# Last revision date : 2021.08.03

import numpy as np

import pandas as pd

import pandas_datareader.data as pdr

import matplotlib.pyplot as plt

import datetime

import torch

import torch.nn as nn

from torch.autograd import Variable

import torch.optim as optim

from torch.utils.data import Dataset, DataLoader

from sklearn.preprocessing import StandardScaler, MinMaxScaler

# GPU setting

device = torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”)

#print(torch.cuda.get_device_name(0)) #Google colab = TESLA T4

# Training/Test ratio = 7:3

Train_ratio = 0.7

Test_ratio = 0.3

# Data load

df = pd.read_csv(‘/content/sample_data/california_housing_train.csv’)

x = df.iloc[:,0:-1]

y = df.iloc[:,-1:]

# Data Division

train_x = x.iloc[0:int(len(df)*Train_ratio),:]

train_y = y.iloc[0:int(len(df)*Train_ratio),:]

test_x = x.iloc[int(len(df)*Train_ratio):,:]

test_y = y.iloc[int(len(df)*Train_ratio):,:]

# Normalizing , 둘다 학습하여 성능비교할것

minmax = MinMaxScaler()

standard = StandardScaler()

train_x = minmax.fit_transform(train_x)

train_y = minmax.fit_transform(train_y)

test_x = minmax.fit_transform(test_x)

test_y = minmax.fit_transform(test_y)

# Check Data pre-processing

#print(“Training shape : “, train_x.shape, train_y.shape)

#print(“Test shape : “,test_x.shape, test_y.shape)

# Numpy array상태로는 학습이 불가능하므로, Torch Variable 형태로 변경(data/grad/grad_fn)

train_x_tensor = Variable(torch.Tensor(train_x))

train_y_tensor = Variable(torch.Tensor(train_y))

#print(“After torch variable shape_Train : “,train_x_tensor.shape, train_y.shape)

test_x_tensor = Variable(torch.Tensor(test_x))

test_y_tensor = Variable(torch.Tensor(test_y))

#print(“After torch Variable shape_Test : “,test_x_tensor.shape, test_y_tensor.shape)

train_x_tensor_final = torch.reshape(train_x_tensor, (train_x_tensor.shape[0], 1, train_x_tensor.shape[1]))

train_y_tensor_final = torch.reshape(train_y_tensor, (train_y_tensor.shape[0], 1, train_y_tensor.shape[1]))

test_x_tensor_final = torch.reshape(test_x_tensor, (test_x_tensor.shape[0], 1, test_x_tensor.shape[1]))

test_y_tensor_final = torch.reshape(test_y_tensor,(test_y_tensor.shape[0], 1, test_y_tensor.shape[1]) )

#print(train_x_tensor_final.shape, test_x_tensor_final.shape)

# LSTM network modeling

class LSTM_Jun(nn.Module):

def __init__(self, num_classes, input_size, hidden_size, num_layers, seq_length) :

super(LSTM_Jun, self).__init__()

self.num_classes = num_classes

self.num_layers = num_layers

self.input_size = input_size

self.hidden_size = hidden_size

self.seq_length = seq_length

self.lstm = nn.LSTM(input_size = input_size, hidden_size = hidden_size, num_layers = num_layers, batch_first = True)

self.layer_1 = nn.Linear(hidden_size, 256)

self.layer_2 = nn.Linear(256,256)

self.layer_3 = nn.Linear(256,128)

self.layer_out = nn.Linear(128, num_classes)

self.relu = nn.ReLU() #Activation Func

def forward(self,x):

h_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)).to(device) #Hidden State

c_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)).to(device) #Internal Process States

output, (hn, cn) = self.lstm(x, (h_0, c_0))

hn = hn.view(-1, self.hidden_size) # Reshaping the data for starting LSTM network

out = self.relu(hn) #pre-processing for first layer

out = self.layer_1(out) # first layer

out = self.relu(out) # activation func relu

out = self.layer_2(out)

out = self.relu(out)

out = self.layer_3(out)

out = self.relu(out)

out = self.layer_out(out) #Output layer

return out

# Code Main

num_epochs = 10000

learning_rate = 0.001

input_size = int(len(x.columns))

hidden_size = 2 # number of features in hidden state

num_layers = 1

num_classes = int(len(y.columns))

LSTM_Jun = LSTM_Jun(num_classes, input_size, hidden_size, num_layers, train_x_tensor_final.shape[1]).to(device)

loss_function = torch.nn.MSELoss()

optimizer = torch.optim.Adam(LSTM_Jun.parameters(), lr = learning_rate)

for epoch in range(num_epochs) :

outputs = LSTM_Jun.forward(train_x_tensor_final.to(device))

optimizer.zero_grad()

loss = loss_function(outputs, train_y_tensor.to(device))

loss.backward()

optimizer.step() # improve from loss = back propagation

if epoch % 200 == 0 :

print(“Epoch : %d, loss : %1.5f” % (epoch, loss.item()))

# Estimated Value

test_predict = LSTM_Jun(train_x_tensor_final.to(device)) #Forward Pass

predict_data = test_predict.data.detach().cpu().numpy() #numpy conversion

predict_data = minmax.inverse_transform(predict_data) #inverse normalization(Min/Max)

# Real Value

real_data = train_y_tensor.data.numpy() # Real value

real_data = minmax.inverse_transform(real_data) #inverse normalization

#Figure

plt.figure(figsize = (10,6)) # Plotting

plt.plot(real_data, label = ‘Real Data’)

plt.plot(predict_data, label = ‘predicted data’)

plt.title(‘Time series prediction’)

plt.legend()

plt.show()

결과물

인터넷에서 돌아다니는 다변량 회귀 데이터 중, 집값 예측 Kaggle데이터를 가져와서 학습시켜보았습니다.

파란색이 실제 집값이고, 주황색이 예측된 값인데요, epoch을 1000번정도 밖에 안했지만 상당히 괜찮은 성능이 나오는것을 확인할 수 있었습니다!

[Pytorch] LSTM을 이용한 삼성전자 주가 예측하기

반응형

안녕하세요.

오늘은 LSTM을 이용해서 삼성전자 주가를 예측해보겠습니다.

큰 Dataset은 따로 필요하지 않으니 부담 갖지 않고 하시면 될 것 같습니다.

아래는 본문 글입니다.

cnvrg.io/pytorch-lstm/?gclid=Cj0KCQiA6t6ABhDMARIsAONIYyxsIXn6G6EcMLhGnPDxnsKiv3zLU49TRMxsyTPXZmOV3E-Hh4xeI2EaAugLEALw_wcB

LSTM이 어떻게 동작을 하는지 자세히 아시고 싶으시면 아래 블로그를 추천드립니다.

dgkim5360.tistory.com/entry/understanding-long-short-term-memory-lstm-kr

1. 라이브러리

import numpy as np import pandas as pd import pandas_datareader.data as pdr import matplotlib.pyplot as plt import datetime import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim from torch.utils.data import Dataset, DataLoader

no module pandas_datareaderno module named ‘pandas_datareader’

pandas가 깔려 있는데, 위 문구가 뜬다면 pip install pandas_datareader로 다운로드합니다.

coding-yoon.tistory.com/56

옛날에는 Pandas를 깔면 자동으로 깔렸었는데, 이번에 아예 분리가 된 것 같습니다.

2. 삼성 전자 주식 불러오기

start = (2000, 1, 1) # 2020년 01년 01월 start = datetime.datetime(*start) end = datetime.date.today() # 현재 # yahoo 에서 삼성 전자 불러오기 df = pdr.DataReader(‘005930.KS’, ‘yahoo’, start, end) df.head(5) df.tail(5) df.Close.plot(grid=True)

head(5) : 맨 앞 5개

tail(5) : 맨 뒤 5 개 삼성 전자 2000 ~ 2020년

삼성 전자 종가를 2000년부터 2020년으로 한 번에 보니 미쳐 날 뛰네요. 지금이라도 이 흐름을 타야 하지 않을까요.

십 만전자 가자!!

혹시 다른 주식도 하고 싶으시면 야후 파이낸시에서 찾아보시는 것도 추천드립니다.

finance.yahoo.com/

그리고 학습된 모델이 성능을 확인하기 위해서 위 데이터(현재 약 5296개)를 Train(학습하고자 하는 데이터)를 0부터 4499까지, Test(성능 테스트하는 데이터)는 4500부터 5295개 까지 데이터로 분류합니다.

오늘자 대략, 노란색 선 정도까지 데이터를 가지고 학습을 하고, 노란색 선 이후부터 예측을 할 것입니다.

과연 내려가고 올라가는 포인트를 잘 예측할 수 있을지 궁금합니다.

3. 데이터셋 준비하기

“”” 저도 주식을 잘 모르기 때문에 참고해주시면 좋을 것 같습니다. open 시가 high 고가 low 저가 close 종가 volume 거래량 Adj Close 주식의 분할, 배당, 배분 등을 고려해 조정한 종가 확실한건 거래량(Volume)은 데이터에서 제하는 것이 중요하고, Y 데이터를 Adj Close로 정합니다. (종가로 해도 된다고 생각합니다.) “”” X = df.drop(columns=’Volume’) y = df.iloc[:, 5:6] print(X) print(y)

X y

“”” 학습이 잘되기 위해 데이터 정규화 StandardScaler 각 특징의 평균을 0, 분산을 1이 되도록 변경 MinMaxScaler 최대/최소값이 각각 1, 0이 되도록 변경 “”” from sklearn.preprocessing import StandardScaler, MinMaxScaler mm = MinMaxScaler() ss = StandardScaler() X_ss = ss.fit_transform(X) y_mm = mm.fit_transform(y) # Train Data X_train = X_ss[:4500, :] X_test = X_ss[4500:, :] # Test Data “”” ( 굳이 없어도 된다. 하지만 얼마나 예측데이터와 실제 데이터의 정확도를 확인하기 위해 from sklearn.metrics import accuracy_score 를 통해 정확한 값으로 확인할 수 있다. ) “”” y_train = y_mm[:4500, :] y_test = y_mm[4500:, :] print(“Training Shape”, X_train.shape, y_train.shape) print(“Testing Shape”, X_test.shape, y_test.shape)

numpy 형태 : 이 상태에서는 학습이 불가능.

“”” torch Variable에는 3개의 형태가 있다. data, grad, grad_fn 한 번 구글에 찾아서 공부해보길 바랍니다. “”” X_train_tensors = Variable(torch.Tensor(X_train)) X_test_tensors = Variable(torch.Tensor(X_test)) y_train_tensors = Variable(torch.Tensor(y_train)) y_test_tensors = Variable(torch.Tensor(y_test)) X_train_tensors_final = torch.reshape(X_train_tensors, (X_train_tensors.shape[0], 1, X_train_tensors.shape[1])) X_test_tensors_final = torch.reshape(X_test_tensors, (X_test_tensors.shape[0], 1, X_test_tensors.shape[1])) print(“Training Shape”, X_train_tensors_final.shape, y_train_tensors.shape) print(“Testing Shape”, X_test_tensors_final.shape, y_test_tensors.shape)

학습할 수 있는 형태로 변환하기 위해 Torch로 변환

4. GPU 준비하기 (없으면 CPU로 돌리면 됩니다.)

device = torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”) # device print(torch.cuda.get_device_name(0))

5. LSTM 네트워크 구성하기

class LSTM1(nn.Module): def __init__(self, num_classes, input_size, hidden_size, num_layers, seq_length): super(LSTM1, self).__init__() self.num_classes = num_classes #number of classes self.num_layers = num_layers #number of layers self.input_size = input_size #input size self.hidden_size = hidden_size #hidden state self.seq_length = seq_length #sequence length self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True) #lstm self.fc_1 = nn.Linear(hidden_size, 128) #fully connected 1 self.fc = nn.Linear(128, num_classes) #fully connected last layer self.relu = nn.ReLU() def forward(self,x): h_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)).to(device) #hidden state c_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)).to(device) #internal state # Propagate input through LSTM output, (hn, cn) = self.lstm(x, (h_0, c_0)) #lstm with input, hidden, and internal state hn = hn.view(-1, self.hidden_size) #reshaping the data for Dense layer next out = self.relu(hn) out = self.fc_1(out) #first Dense out = self.relu(out) #relu out = self.fc(out) #Final Output return out

위 코드는 복잡해 보이지만, 실상 하나씩 확인해보면 굉장히 연산이 적은 네트워크입니다.

시계열 데이터이지만, 간단한 구성을 위해 Sequence Length도 1이고, LSTM Layer도 1이기 때문에 굉장히 빨리 끝납니다. 아마 본문 작성자가 CPU환경에서도 쉽게 따라 할 수 있게 간단하게 작성한 것 같습니다.

아래는 Pytorch로 RNN을 사용하는 방법을 적었지만, LSTM과 동일합니다.

기본 동작 원리만 이해하시면, 쉽게 따라 하실 수 있습니다.

coding-yoon.tistory.com/55

5. 네트워크 파라미터 구성하기

num_epochs = 30000 #1000 epochs learning_rate = 0.00001 #0.001 lr input_size = 5 #number of features hidden_size = 2 #number of features in hidden state num_layers = 1 #number of stacked lstm layers num_classes = 1 #number of output classes

lstm1 = LSTM1(num_classes, input_size, hidden_size, num_layers, X_train_tensors_final.shape[1]).to(device) loss_function = torch.nn.MSELoss() # mean-squared error for regression optimizer = torch.optim.Adam(lstm1.parameters(), lr=learning_rate) # adam optimizer

6. 학습하기

for epoch in range(num_epochs): outputs = lstm1.forward(X_train_tensors_final.to(device)) #forward pass optimizer.zero_grad() #caluclate the gradient, manually setting to 0 # obtain the loss function loss = loss_function(outputs, y_train_tensors.to(device)) loss.backward() #calculates the loss of the loss function optimizer.step() #improve from loss, i.e backprop if epoch % 100 == 0: print(“Epoch: %d, loss: %1.5f” % (epoch, loss.item()))

7. 예측하기

df_X_ss = ss.transform(df.drop(columns=’Volume’)) df_y_mm = mm.transform(df.iloc[:, 5:6]) df_X_ss = Variable(torch.Tensor(df_X_ss)) #converting to Tensors df_y_mm = Variable(torch.Tensor(df_y_mm)) #reshaping the dataset df_X_ss = torch.reshape(df_X_ss, (df_X_ss.shape[0], 1, df_X_ss.shape[1]))

train_predict = lstm1(df_X_ss.to(device))#forward pass data_predict = train_predict.data.detach().cpu().numpy() #numpy conversion dataY_plot = df_y_mm.data.numpy() data_predict = mm.inverse_transform(data_predict) #reverse transformation dataY_plot = mm.inverse_transform(dataY_plot) plt.figure(figsize=(10,6)) #plotting plt.axvline(x=4500, c=’r’, linestyle=’–‘) #size of the training set plt.plot(dataY_plot, label=’Actuall Data’) #actual plot plt.plot(data_predict, label=’Predicted Data’) #predicted plot plt.title(‘Time-Series Prediction’) plt.legend() plt.show()

빨간색 선 이후부터 모델이 예측을 한 것인데 나름 비슷하게 나온 것 같습니다.

하지만 인공지능이라도 팔만 전자는 예상하지 못했나 봅니다.

728×90

반응형

Pytorch LSTM

반응형

이번 포스트에서는 시계열 데이터에서 자주 쓰이는 ‘airline-passengers.csv’ 데이터에 대해 Pytorch 프레임워크의 LSTM 모듈을 이용하여 시계열 예측을 수행해보도록 하겠습니다.

international-airline-passengers.csv 0.00MB

Import libraries

먼저 필요한 라이브러리를 호출합니다.

import torch import torch.nn as nn import numpy as np import pandas as pd import matplotlib.pyplot as plt from torch.autograd import Variable from sklearn.preprocessing import MinMaxScaler

Load data

판다스의 ‘read_csv’ 함수를 이용해 데이터를 읽습니다. csv 데이터의 첫번째 열은 날짜이므로 두번째 열만 데이터로 설정하고 min-max 스케일링을 수행합니다.

training_set = pd.read_csv(‘/content/drive/MyDrive/Time Series/Data/international-airline-passengers.csv’) training_set = training_set.iloc[:,1:2].values sc = MinMaxScaler() training_data = sc.fit_transform(training_set)

이후에는 시계열 데이터이므로 몇 개의 타임스텝을 현재 시점에 반영할 것인지 정합니다. 즉, 현재 시점의 값은 지정한 시퀀스 길이에 맞게 직전 몇 개의 값과 연관되게끔 데이터를 재구성하는 것이죠.

def sliding_windows(data, seq_length): x = [] y = [] for i in range(len(data)-seq_length-1): _x = data[i:(i+seq_length)] _y = data[i+seq_length] x.append(_x) y.append(_y) return np.array(x),np.array(y) seq_length = 4 x, y = sliding_windows(training_data, seq_length)

이제 훈련 / 테스트 데이터셋을 2:1 비율로 나누어주고 autograd 모듈의 Variable을 이용하여 텐서로 만들어줍니다. 훈련 데이터의 X, y는 각각 [92, 4, 1] / [92, 1] 크기가 됩니다.

Model

이제는 시계열 데이터 모델링을 위한 LSTM 모델을 구현해줄 차례입니다. LSTM (Long Short-Term Memory) 는 입력 시퀀스의 타임 스텝 $t$에 따라 hidden state $h_t$, cell state $c_t$에 따른 출력을 Equation 1과 같이 계산합니다. Equation 1의 $i_t, f_t, g_t, o_t$는 각각 input, forget, cell, output 게이트이며 $\sigma$는 sigmoid 함수를 말합니다.

Equation 1

Pytorch 에서는 torch.nn 모듈에서 LSTM 클래스를 쉽게 호출할 수 있습니다. LSTM 클래스 생성시 필요한 파라미터는 다음과 같습니다. “num_layer” 아규먼트를 통해 Multi-layer LSTM을 쉽게 구성할 수 있으며 “num_layer”가 2 이상일 경우, 타임스텝 $t$, layer $l$에 대한 입력으로는 ($x_t^l, l \geq 2$) $h_t^{l-1}$에 dropout이 적용된 텐서가 적용됩니다.

Parameters Description input_size 입력 $x$의 feature 차원 hidden_size hidden feature 차원 num_layers LSTM 층의 개수로 2 이상일 경우 Multi-layer LSTM이 됩니다. bias 디폴트는 True로 설정되어 있고 bias 항을 추가할지 말지를 결정합니다. batch_first 디폴트는 False로 설정되어 있고 True일 경우 입력, 출력 모두 [배치 사이즈, 입력 길이, feature 차원]

으로 구성되고 False일 경우 입력, 출력 모두 [입력 길이, 배치 사이즈, feature 차원]이 됩니다.

이러한 텐서 차원 순서는 hidden / cell state 에는 적용되지 않습니다. dropout 마지막 layer의 출력을 제외하고 dropout을 적용합니다.

LSTM 모델을 사용할 때 주의할 점은 각 타임스텝 별로 hidden / cell state 가 업데이트되는 구조로 동작하기 때문에 초기 $h_0, c_0$를 목적에 맞게 선언해줄 수 있다는 점입니다 각각 [$D$*num_layers, 배치 사이즈, feature 차원] 크기로 되어있고 $D$는 bi-directional 일 경우 2, one-directional 일 경우 1이고 따로 제공되지 않을 경우 디폴트는 0으로 할당됩니다. 또한, 입력, 출력의 텐서 구조는 “batch_first” 아규먼트가 True / False 여부에 따라 배치 차원이 어디에 위치할지 결정됩니다. 일반적으로 배치 차원은 맨 앞에 있는 것이 편리하므로 “batch_first=True”로 설정하는 것이 낫습니다.

LSTM 모델에 대해서 forward 함수를 진행할 경우 출력은 “output, $(h_n, c_n)$” 이 됩니다. 출력텐서는 (“output”) “batch_first” 아규먼트에 따라 True일 경우 [배치 사이즈, 입력 길이, $D$*feature 차원] 으로 구성되며 각 타임스텝 $t$에 따른 마지막 LSTM layer의 $h_t$를 담습니다. $h_n, c_n$의 크기는 [$D$*num_layers, 배치 사이즈, feature 차원] 으로 구성되며 마지막 타임스텝의 hidden / cell state가 담깁니다. 모델의 구현은 다음과 같습니다.

class LSTM(nn.Module): def __init__(self, num_classes, input_size, hidden_size, num_layers): super(LSTM, self).__init__() self.num_classes = num_classes self.num_layers = num_layers self.input_size = input_size self.hidden_size = hidden_size self.seq_length = seq_length self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True) self.fc = nn.Linear(hidden_size, num_classes) def forward(self, x): h_0 = Variable(torch.zeros( self.num_layers, x.size(0), self.hidden_size)) c_0 = Variable(torch.zeros( self.num_layers, x.size(0), self.hidden_size)) # Propagate input through LSTM ula, (h_out, _) = self.lstm(x, (h_0, c_0)) h_out = h_out.view(-1, self.hidden_size) out = self.fc(h_out) return out

$h_0, c_0$는 hidden / cell state의 초기값이기 때문에 requires_grad=False로 설정된 zero 텐서를 넣어줍니다.

현재 시퀀스 길이는 4이고 마지막 시퀀스에 대해 fully-connected layer를 달아주고 싶기 때문에 $h_n$에 대하여 fully-connected layer를 진행시킵니다.

LSTM 모델의 결과로 나오는 “output”의 마지막 타임스텝 값은 $h_n$과 같습니다.

Train

모델 훈련 시에는 회귀를 위한 MSE loss 함수와 Adam 옵티마이저에 대해 훈련시킵니다. 이 경우에는 훈련 데이터셋의 개수가 92개로 매우 적으므로 전체 데이터에 대해 여러 번 훈련시킵니다.

num_epochs = 2000 learning_rate = 0.01 input_size = 1 hidden_size = 2 num_layers = 1 num_classes = 1 lstm = LSTM(num_classes, input_size, hidden_size, num_layers) criterion = torch.nn.MSELoss() # mean-squared error for regression optimizer = torch.optim.Adam(lstm.parameters(), lr=learning_rate) #optimizer = torch.optim.SGD(lstm.parameters(), lr=learning_rate) # Train the model for epoch in range(num_epochs): outputs = lstm(trainX) optimizer.zero_grad() # obtain the loss function loss = criterion(outputs, trainY) loss.backward() optimizer.step() if epoch % 100 == 0: print(“Epoch: %d, loss: %1.5f” % (epoch, loss.item()))

Test

테스트 진행 시에는 전에 선언했던 “MinMaxScaler” 객체의 “inverse_transform” 함수를 이용하여 원래 데이터 값으로 복원시킵니다.

lstm.eval() train_predict = lstm(dataX) data_predict = train_predict.data.numpy() dataY_plot = dataY.data.numpy() data_predict = sc.inverse_transform(data_predict) dataY_plot = sc.inverse_transform(dataY_plot) plt.axvline(x=train_size, c=’r’, linestyle=’–‘) plt.plot(dataY_plot) plt.plot(data_predict) plt.suptitle(‘Time-Series Prediction’) plt.show()

반응형

Sequence Models and Long Short-Term Memory Networks — PyTorch Tutorials 1.12.1+cu102 documentation

Click here to download the full example code

Sequence Models and Long Short-Term Memory Networks¶

At this point, we have seen various feed-forward networks. That is, there is no state maintained by the network at all. This might not be the behavior we want. Sequence models are central to NLP: they are models where there is some sort of dependence through time between your inputs. The classical example of a sequence model is the Hidden Markov Model for part-of-speech tagging. Another example is the conditional random field.

A recurrent neural network is a network that maintains some kind of state. For example, its output could be used as part of the next input, so that information can propagate along as the network passes over the sequence. In the case of an LSTM, for each element in the sequence, there is a corresponding hidden state \(h_t\), which in principle can contain information from arbitrary points earlier in the sequence. We can use the hidden state to predict words in a language model, part-of-speech tags, and a myriad of other things.

LSTMs in Pytorch¶ Before getting to the example, note a few things. Pytorch’s LSTM expects all of its inputs to be 3D tensors. The semantics of the axes of these tensors is important. The first axis is the sequence itself, the second indexes instances in the mini-batch, and the third indexes elements of the input. We haven’t discussed mini-batching, so let’s just ignore that and assume we will always have just 1 dimension on the second axis. If we want to run the sequence model over the sentence “The cow jumped”, our input should look like \[\begin{bmatrix} \overbrace{q_\text{The}}^\text{row vector} \\ q_\text{cow} \\ q_\text{jumped} \end{bmatrix}\] Except remember there is an additional 2nd dimension with size 1. In addition, you could go through the sequence one at a time, in which case the 1st axis will have size 1 also. Let’s see a quick example. # Author: Robert Guthrie import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim torch . manual_seed ( 1 ) lstm = nn . LSTM ( 3 , 3 ) # Input dim is 3, output dim is 3 inputs = [ torch . randn ( 1 , 3 ) for _ in range ( 5 )] # make a sequence of length 5 # initialize the hidden state. hidden = ( torch . randn ( 1 , 1 , 3 ), torch . randn ( 1 , 1 , 3 )) for i in inputs : # Step through the sequence one element at a time. # after each step, hidden contains the hidden state. out , hidden = lstm ( i . view ( 1 , 1 , – 1 ), hidden ) # alternatively, we can do the entire sequence all at once. # the first value returned by LSTM is all of the hidden states throughout # the sequence. the second is just the most recent hidden state # (compare the last slice of “out” with “hidden” below, they are the same) # The reason for this is that: # “out” will give you access to all hidden states in the sequence # “hidden” will allow you to continue the sequence and backpropagate, # by passing it as an argument to the lstm at a later time # Add the extra 2nd dimension inputs = torch . cat ( inputs ) . view ( len ( inputs ), 1 , – 1 ) hidden = ( torch . randn ( 1 , 1 , 3 ), torch . randn ( 1 , 1 , 3 )) # clean out hidden state out , hidden = lstm ( inputs , hidden ) print ( out ) print ( hidden ) Out: tensor([[[-0.0187, 0.1713, -0.2944]], [[-0.3521, 0.1026, -0.2971]], [[-0.3191, 0.0781, -0.1957]], [[-0.1634, 0.0941, -0.1637]], [[-0.3368, 0.0959, -0.0538]]], grad_fn=) (tensor([[[-0.3368, 0.0959, -0.0538]]], grad_fn=), tensor([[[-0.9825, 0.4715, -0.0633]]], grad_fn=))

Example: An LSTM for Part-of-Speech Tagging¶ In this section, we will use an LSTM to get part of speech tags. We will not use Viterbi or Forward-Backward or anything like that, but as a (challenging) exercise to the reader, think about how Viterbi could be used after you have seen what is going on. In this example, we also refer to embeddings. If you are unfamiliar with embeddings, you can read up about them here. The model is as follows: let our input sentence be \(w_1, \dots, w_M\), where \(w_i \in V\), our vocab. Also, let \(T\) be our tag set, and \(y_i\) the tag of word \(w_i\). Denote our prediction of the tag of word \(w_i\) by \(\hat{y}_i\). This is a structure prediction, model, where our output is a sequence \(\hat{y}_1, \dots, \hat{y}_M\), where \(\hat{y}_i \in T\). To do the prediction, pass an LSTM over the sentence. Denote the hidden state at timestep \(i\) as \(h_i\). Also, assign each tag a unique index (like how we had word_to_ix in the word embeddings section). Then our prediction rule for \(\hat{y}_i\) is \[\hat{y}_i = \text{argmax}_j \ (\log \text{Softmax}(Ah_i + b))_j \] That is, take the log softmax of the affine map of the hidden state, and the predicted tag is the tag that has the maximum value in this vector. Note this implies immediately that the dimensionality of the target space of \(A\) is \(|T|\). Prepare data: def prepare_sequence ( seq , to_ix ): idxs = [ to_ix [ w ] for w in seq ] return torch . tensor ( idxs , dtype = torch . long ) training_data = [ # Tags are: DET – determiner; NN – noun; V – verb # For example, the word “The” is a determiner ( “The dog ate the apple” . split (), [ “DET” , “NN” , “V” , “DET” , “NN” ]), ( “Everybody read that book” . split (), [ “NN” , “V” , “DET” , “NN” ]) ] word_to_ix = {} # For each words-list (sentence) and tags-list in each tuple of training_data for sent , tags in training_data : for word in sent : if word not in word_to_ix : # word has not been assigned an index yet word_to_ix [ word ] = len ( word_to_ix ) # Assign each word with a unique index print ( word_to_ix ) tag_to_ix = { “DET” : 0 , “NN” : 1 , “V” : 2 } # Assign each tag with a unique index # These will usually be more like 32 or 64 dimensional. # We will keep them small, so we can see how the weights change as we train. EMBEDDING_DIM = 6 HIDDEN_DIM = 6 Out: {‘The’: 0, ‘dog’: 1, ‘ate’: 2, ‘the’: 3, ‘apple’: 4, ‘Everybody’: 5, ‘read’: 6, ‘that’: 7, ‘book’: 8} Create the model: class LSTMTagger ( nn . Module ): def __init__ ( self , embedding_dim , hidden_dim , vocab_size , tagset_size ): super ( LSTMTagger , self ) . __init__ () self . hidden_dim = hidden_dim self . word_embeddings = nn . Embedding ( vocab_size , embedding_dim ) # The LSTM takes word embeddings as inputs, and outputs hidden states # with dimensionality hidden_dim. self . lstm = nn . LSTM ( embedding_dim , hidden_dim ) # The linear layer that maps from hidden state space to tag space self . hidden2tag = nn . Linear ( hidden_dim , tagset_size ) def forward ( self , sentence ): embeds = self . word_embeddings ( sentence ) lstm_out , _ = self . lstm ( embeds . view ( len ( sentence ), 1 , – 1 )) tag_space = self . hidden2tag ( lstm_out . view ( len ( sentence ), – 1 )) tag_scores = F . log_softmax ( tag_space , dim = 1 ) return tag_scores Train the model: model = LSTMTagger ( EMBEDDING_DIM , HIDDEN_DIM , len ( word_to_ix ), len ( tag_to_ix )) loss_function = nn . NLLLoss () optimizer = optim . SGD ( model . parameters (), lr = 0.1 ) # See what the scores are before training # Note that element i,j of the output is the score for tag j for word i. # Here we don’t need to train, so the code is wrapped in torch.no_grad() with torch . no_grad (): inputs = prepare_sequence ( training_data [ 0 ][ 0 ], word_to_ix ) tag_scores = model ( inputs ) print ( tag_scores ) for epoch in range ( 300 ): # again, normally you would NOT do 300 epochs, it is toy data for sentence , tags in training_data : # Step 1. Remember that Pytorch accumulates gradients. # We need to clear them out before each instance model . zero_grad () # Step 2. Get our inputs ready for the network, that is, turn them into # Tensors of word indices. sentence_in = prepare_sequence ( sentence , word_to_ix ) targets = prepare_sequence ( tags , tag_to_ix ) # Step 3. Run our forward pass. tag_scores = model ( sentence_in ) # Step 4. Compute the loss, gradients, and update the parameters by # calling optimizer.step() loss = loss_function ( tag_scores , targets ) loss . backward () optimizer . step () # See what the scores are after training with torch . no_grad (): inputs = prepare_sequence ( training_data [ 0 ][ 0 ], word_to_ix ) tag_scores = model ( inputs ) # The sentence is “the dog ate the apple”. i,j corresponds to score for tag j # for word i. The predicted tag is the maximum scoring tag. # Here, we can see the predicted sequence below is 0 1 2 0 1 # since 0 is index of the maximum value of row 1, # 1 is the index of maximum value of row 2, etc. # Which is DET NOUN VERB DET NOUN, the correct sequence! print ( tag_scores ) Out: tensor([[-1.1389, -1.2024, -0.9693], [-1.1065, -1.2200, -0.9834], [-1.1286, -1.2093, -0.9726], [-1.1190, -1.1960, -0.9916], [-1.0137, -1.2642, -1.0366]]) tensor([[-0.0462, -4.0106, -3.6096], [-4.8205, -0.0286, -3.9045], [-3.7876, -4.1355, -0.0394], [-0.0185, -4.7874, -4.6013], [-5.7881, -0.0186, -4.1778]])

Pytorch로 RNN, LSTM 구현하기

Pytorch 에서는 CNN 과 마찬가지로, RNN 과 관련 된 API 를 제공합니다. 이를 이용해 손쉽게 RNN 네트워크를 구축 할 수 있습니다.

Recurrent Neural Network

RNN (Recurrent Neural Network) 를 위한 API 는 torch.nn.RNN(*args, **kwargs) 입니다.

일단 Input 시퀀스의 각 요소에 대해, 각 레이어에서는 다음 연산을 수행합니다.

h t = t a n h ( W i h x t + b i h + W h h h ( t − 1 ) + b h h ) h_t = tanh(W_{ihx_t} + b_{ih} + W_{hh}h_{(t-1)} + b_{hh}) ht​=tanh(Wihxt​​+bih​+Whh​h(t−1)​+bhh​)

Parameters

input_size : Input 의 사이즈 에 해당 하는 수를 입력하면 됩니다.

: 의 에 해당 하는 수를 입력하면 됩니다. hidden_size : 은닉층의 사이즈 에 해당 하는 수를 입력하면 됩니다.

: 에 해당 하는 수를 입력하면 됩니다. num_layers : RNN 의 은닉층 레이어 갯수를 나타냅니다. 기본 값은 1입니다.

: 의 은닉층 레이어 갯수를 나타냅니다. 기본 값은 1입니다. nonlinearity : 비선형 활성화 함수 를 선택합니다. tanh , relu 중 하나를 선택 가능하며, 기본 값은 tanh 입니다.

: 를 선택합니다. , 중 하나를 선택 가능하며, 기본 값은 입니다. bias : 바이어스 값 활성화 여부를 선택합니다. 기본 값은 True 입니다.

: 활성화 여부를 선택합니다. 기본 값은 입니다. batch_first : True 일 시, Output 값의 사이즈는 (batch, seq, feature) 가 됩니다. 기본 값은 False 입니다.

: 일 시, 값의 사이즈는 (batch, seq, feature) 가 됩니다. 기본 값은 입니다. dropout : 드롭아웃 비율을 설정 합니다. 기본 값은 0입니다.

: 비율을 설정 합니다. 기본 값은 0입니다. bidirectional : True 일 시, 양방향 RNN이 됩니다. 기본 값은 False 입니다.

num_layers 가 2라면?

다음 그림과 같은 신경망이 만들어 진다고 생각 하면 됩니다.

Inputs: input, h_0 ( tuple 형태)

input : (seqlen, batch, inputsize)

: (seqlen, batch, inputsize) h_0 : (numlayers * numdirections, batch, hiddensize) 여기서 bidirectional 이 True 라면, `numdirections 는 2, False` 라면 1이 됩니다.

Outputs: output, h_n ( tuple 형태)

output : (seqlen, batch, numdirections * hiddensize) 여기서 bidirectional 이 True 라면, `numdirections 는 2, False` 라면 1이 됩니다.

: (seqlen, batch, numdirections * hiddensize) 여기서 이 라면, `numdirections False` 라면 1이 됩니다. h_n : (numlayers * numdirections, batch, hiddensize) 여기서 bidirectional 이 True 라면, `numdirections 는 2, False` 라면 1이 됩니다.

Code Example (Natural Language Processing)

해당 코드는 NLP (Natural Language Processing) 을 위한 코드입니다. 앞의 두 단어를 보고, 뒤에 나올 단어를 예측 합니다.

In

import numpy as np import torch import torch . nn as nn import torch . optim as optim sentences = [ “i like dog” , “i love coffee” , “i hate milk” , “you like cat” , “you love milk” , “you hate coffee” ] dtype = torch . float “”” Word Processing “”” word_list = list ( set ( ” ” . join ( sentences ) . split ( ) ) ) word_dict = { w : i for i , w in enumerate ( word_list ) } number_dict = { i : w for i , w in enumerate ( word_list ) } n_class = len ( word_dict ) “”” TextRNN Parameter “”” batch_size = len ( sentences ) n_step = 2 n_hidden = 5 def make_batch ( sentences ) : input_batch = [ ] target_batch = [ ] for sen in sentences : word = sen . split ( ) input = [ word_dict [ n ] for n in word [ : – 1 ] ] target = word_dict [ word [ – 1 ] ] input_batch . append ( np . eye ( n_class ) [ input ] ) target_batch . append ( target ) return input_batch , target_batch input_batch , target_batch = make_batch ( sentences ) input_batch = torch . tensor ( input_batch , dtype = torch . float32 , requires_grad = True ) target_batch = torch . tensor ( target_batch , dtype = torch . int64 ) “”” TextRNN “”” class TextRNN ( nn . Module ) : def __init__ ( self ) : super ( TextRNN , self ) . __init__ ( ) self . rnn = nn . RNN ( input_size = n_class , hidden_size = n_hidden , dropout = 0.3 ) self . W = nn . Parameter ( torch . randn ( [ n_hidden , n_class ] ) . type ( dtype ) ) self . b = nn . Parameter ( torch . randn ( [ n_class ] ) . type ( dtype ) ) self . Softmax = nn . Softmax ( dim = 1 ) def forward ( self , hidden , X ) : X = X . transpose ( 0 , 1 ) outputs , hidden = self . rnn ( X , hidden ) outputs = outputs [ – 1 ] model = torch . mm ( outputs , self . W ) + self . b return model “”” Training “”” model = TextRNN ( ) criterion = nn . CrossEntropyLoss ( ) optimizer = optim . Adam ( model . parameters ( ) , lr = 0.01 ) for epoch in range ( 500 ) : hidden = torch . zeros ( 1 , batch_size , n_hidden , requires_grad = True ) output = model ( hidden , input_batch ) loss = criterion ( output , target_batch ) if ( epoch + 1 ) % 100 == 0 : print ( ‘Epoch:’ , ‘%04d’ % ( epoch + 1 ) , ‘cost =’ , ‘{:.6f}’ . format ( loss ) ) optimizer . zero_grad ( ) loss . backward ( ) optimizer . step ( ) input = [ sen . split ( ) [ : 2 ] for sen in sentences ] hidden = torch . zeros ( 1 , batch_size , n_hidden , requires_grad = True ) predict = model ( hidden , input_batch ) . data . max ( 1 , keepdim = True ) [ 1 ] print ( [ sen . split ( ) [ : 2 ] for sen in sentences ] , ‘->’ , [ number_dict [ n . item ( ) ] for n in predict . squeeze ( ) ] )

Out

Epoch: 0100 cost = 0.409607 Epoch: 0200 cost = 0.099554 Epoch: 0300 cost = 0.027191 Epoch: 0400 cost = 0.013870 Epoch: 0500 cost = 0.008780 [[‘i’, ‘like’], [‘i’, ‘love’], [‘i’, ‘hate’], [‘you’, ‘like’], [‘you’, ‘love’], [‘you’, ‘hate’]] -> [‘dog’, ‘coffee’, ‘milk’, ‘cat’, ‘milk’, ‘coffee’]

Long Short-Term Memory (LSTM)

LSTM (Long Short-Term Memory) 를 위한 API 는 torch.nn.LSTM(*args, **kwargs) 입니다. LSTM 은 기울기 폭발, 기울기 소실 등의 문제를 해결 하기 위해 기존 RNN 을 개선한 구조로, Input 시퀀스의 각 요소에 대해, 각 레이어에서는 다음 연산을 수행합니다.

i t = σ ( W i i x t + b i i + W h i h ( t − 1 ) + b h i ) i_t = \sigma(W_{ii}x_t + b_{ii} + W_{hi}h_{(t-1)} + b_{hi}) it​=σ(Wii​xt​+bii​+Whi​h(t−1)​+bhi​)

f t = σ ( W i f x t + b i f + W h f h ( t − 1 ) + b h f ) f_t = \sigma(W_{if}x_t + b_{if} + W_{hf}h_{(t-1)} + b_{hf}) ft​=σ(Wif​xt​+bif​+Whf​h(t−1)​+bhf​)

g t = t a n h ( W i g x t + b i g + W h g h ( t − 1 ) + b h g ) g_t = tanh(W_{ig}x_t + b_{ig} + W_{hg}h_{(t-1)} + b_{hg}) gt​=tanh(Wig​xt​+big​+Whg​h(t−1)​+bhg​)

o t = σ ( W i o x t + b i o + W h o h ( t − 1 ) + b h o ) o_t = \sigma(W_{io}x_t + b_{io} + W_{ho}h_{(t-1)} + b_{ho}) ot​=σ(Wio​xt​+bio​+Who​h(t−1)​+bho​)

c t = f t ∗ c ( t − 1 ) + i t ∗ g t c_t = f_t * c_{(t-1)} + i_t * g_t ct​=ft​∗c(t−1)​+it​∗gt​

h t = o t ∗ t a n h ( c t ) h_t = o_t * tanh(c_t) ht​=ot​∗tanh(ct​)

Parameters (RNN과 비슷합니다.)

input_size : Input 의 사이즈 에 해당 하는 수를 입력하면 됩니다.

: 의 에 해당 하는 수를 입력하면 됩니다. hidden_size : 은닉층의 사이즈 에 해당 하는 수를 입력하면 됩니다.

: 에 해당 하는 수를 입력하면 됩니다. num_layers : RNN 의 은닉층 레이어 갯수를 나타냅니다. 기본 값은 1입니다.

: 의 은닉층 레이어 갯수를 나타냅니다. 기본 값은 1입니다. bias : 바이어스 값 활성화 여부를 선택합니다. 기본 값은 True 입니다.

: 활성화 여부를 선택합니다. 기본 값은 입니다. batch_first : True 일 시, Output 값의 사이즈는 (batch, seq, feature) 가 됩니다. 기본 값은 False 입니다.

: 일 시, 값의 사이즈는 (batch, seq, feature) 가 됩니다. 기본 값은 입니다. dropout : 드롭아웃 비율을 설정 합니다. 기본 값은 0입니다.

: 비율을 설정 합니다. 기본 값은 0입니다. bidirectional : True 일 시, 양방향 RNN이 됩니다. 기본 값은 False 입니다.

Inputs: input, (h0, c0) ( tuple 형태)

input : (seqlen, batch, inputsize)

: (seqlen, batch, inputsize) h_0 : (numlayers * numdirections, batch, hiddensize) 여기서 bidirectional 이 True 라면, `numdirections 는 2, False` 라면 1이 됩니다.

: (numlayers * numdirections, batch, hiddensize) 여기서 이 라면, `numdirections False` 라면 1이 됩니다. c_0 : (numlayers * numdirections, batch, hiddensize) 초기 Cell State 입니다. 만약 (h0, c_0)이 없다면, 기본 값은 영벡터 입니다.

Outputs: output, (hn, c0) ( tuple 형태)

output : (seqlen, batch, numdirections * hiddensize) 여기서 bidirectional 이 True 라면, `numdirections 는 2, False` 라면 1이 됩니다.

: (seqlen, batch, numdirections * hiddensize) 여기서 이 라면, `numdirections False` 라면 1이 됩니다. h_n : (numlayers * numdirections, batch, hiddensize) 여기서 bidirectional 이 True 라면, `numdirections 는 2, False` 라면 1이 됩니다.

: (numlayers * numdirections, batch, hiddensize) 여기서 이 라면, `numdirections False` 라면 1이 됩니다. c_n : (numlayers * numdirections, batch, hidden_size) Cell State 입니다.

Code Example

해당 코드는 NLP (Natural Language Processing) 을 위한 코드입니다. 앞의 두 단어를 보고, 뒤에 나올 단어를 예측 합니다. CNN 코드와는 Input 파라미터에 차이가 있습니다.

In

import numpy as np import torch import torch . nn as nn import torch . optim as optim sentences = [ “i like dog” , “i love coffee” , “i hate milk” , “you like cat” , “you love milk” , “you hate coffee” ] dtype = torch . float “”” Word Processing “”” word_list = list ( set ( ” ” . join ( sentences ) . split ( ) ) ) word_dict = { w : i for i , w in enumerate ( word_list ) } number_dict = { i : w for i , w in enumerate ( word_list ) } n_class = len ( word_dict ) “”” TextRNN Parameter “”” batch_size = len ( sentences ) n_step = 2 n_hidden = 5 def make_batch ( sentences ) : input_batch = [ ] target_batch = [ ] for sen in sentences : word = sen . split ( ) input = [ word_dict [ n ] for n in word [ : – 1 ] ] target = word_dict [ word [ – 1 ] ] input_batch . append ( np . eye ( n_class ) [ input ] ) target_batch . append ( target ) return input_batch , target_batch input_batch , target_batch = make_batch ( sentences ) input_batch = torch . tensor ( input_batch , dtype = torch . float32 , requires_grad = True ) target_batch = torch . tensor ( target_batch , dtype = torch . int64 ) “”” TextLSTM “”” class TextLSTM ( nn . Module ) : def __init__ ( self ) : super ( TextLSTM , self ) . __init__ ( ) self . lstm = nn . LSTM ( input_size = n_class , hidden_size = n_hidden , dropout = 0.3 ) self . W = nn . Parameter ( torch . randn ( [ n_hidden , n_class ] ) . type ( dtype ) ) self . b = nn . Parameter ( torch . randn ( [ n_class ] ) . type ( dtype ) ) self . Softmax = nn . Softmax ( dim = 1 ) def forward ( self , hidden_and_cell , X ) : X = X . transpose ( 0 , 1 ) outputs , hidden = self . lstm ( X , hidden_and_cell ) outputs = outputs [ – 1 ] model = torch . mm ( outputs , self . W ) + self . b return model “”” Training “”” model = TextLSTM ( ) criterion = nn . CrossEntropyLoss ( ) optimizer = optim . Adam ( model . parameters ( ) , lr = 0.01 ) for epoch in range ( 500 ) : hidden = torch . zeros ( 1 , batch_size , n_hidden , requires_grad = True ) cell = torch . zeros ( 1 , batch_size , n_hidden , requires_grad = True ) output = model ( ( hidden , cell ) , input_batch ) loss = criterion ( output , target_batch ) if ( epoch + 1 ) % 100 == 0 : print ( ‘Epoch:’ , ‘%04d’ % ( epoch + 1 ) , ‘cost =’ , ‘{:.6f}’ . format ( loss ) ) optimizer . zero_grad ( ) loss . backward ( ) optimizer . step ( ) input = [ sen . split ( ) [ : 2 ] for sen in sentences ] hidden = torch . zeros ( 1 , batch_size , n_hidden , requires_grad = True ) cell = torch . zeros ( 1 , batch_size , n_hidden , requires_grad = True ) predict = model ( ( hidden , cell ) , input_batch ) . data . max ( 1 , keepdim = True ) [ 1 ] print ( [ sen . split ( ) [ : 2 ] for sen in sentences ] , ‘->’ , [ number_dict [ n . item ( ) ] for n in predict . squeeze ( ) ] )

Out

Epoch: 0100 cost = 0.301909 Epoch: 0200 cost = 0.039160 Epoch: 0300 cost = 0.017456 Epoch: 0400 cost = 0.009996 Epoch: 0500 cost = 0.006636 [[‘i’, ‘like’], [‘i’, ‘love’], [‘i’, ‘hate’], [‘you’, ‘like’], [‘you’, ‘love’], [‘you’, ‘hate’]] -> [‘dog’, ‘coffee’, ‘milk’, ‘cat’, ‘milk’, ‘coffee’]

마치며

다음 시간부터는 Pytorch 를 이용해서 실제 동작하는 어플리케이션 을 만들어 보도록 하겠습니다.

References

4. LSTM — PseudoLab Tutorial Book

class CovidPredictor ( nn . Module ): def __init__ ( self , n_features , n_hidden , seq_len , n_layers ): super ( CovidPredictor , self ) . __init__ () self . n_hidden = n_hidden self . seq_len = seq_len self . n_layers = n_layers self . lstm = nn . LSTM ( input_size = n_features , hidden_size = n_hidden , num_layers = n_layers ) self . linear = nn . Linear ( in_features = n_hidden , out_features = 1 ) def reset_hidden_state ( self ): self . hidden = ( torch . zeros ( self . n_layers , self . seq_len , self . n_hidden ), torch . zeros ( self . n_layers , self . seq_len , self . n_hidden ) ) def forward ( self , sequences ): lstm_out , self . hidden = self . lstm ( sequences . view ( len ( sequences ), self . seq_len , – 1 ), self . hidden ) last_time_step = lstm_out . view ( self . seq_len , len ( sequences ), self . n_hidden )[ – 1 ] y_pred = self . linear ( last_time_step ) return y_pred

키워드에 대한 정보 pytorch lstm 예제

다음은 Bing에서 pytorch lstm 예제 주제에 대한 검색 결과입니다. 필요한 경우 더 읽을 수 있습니다.

이 기사는 인터넷의 다양한 출처에서 편집되었습니다. 이 기사가 유용했기를 바랍니다. 이 기사가 유용하다고 생각되면 공유하십시오. 매우 감사합니다!

사람들이 주제에 대해 자주 검색하는 키워드 Pytorch 양방향 LSTM 예제

  • pytorch bidirectional lstm tutorial
  • pytorch bidirectional lstm

Pytorch #양방향 #LSTM #예제


YouTube에서 pytorch lstm 예제 주제의 다른 동영상 보기

주제에 대한 기사를 시청해 주셔서 감사합니다 Pytorch 양방향 LSTM 예제 | pytorch lstm 예제, 이 기사가 유용하다고 생각되면 공유하십시오, 매우 감사합니다.

Leave a Comment