250x250
Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags more
Archives
Today
Total
관리 메뉴

Python 연습장

딥러닝 시계열 알고리즘 정리 본문

코딩

딥러닝 시계열 알고리즘 정리

포숑 2022. 1. 1. 20:33
728x90

머신러닝을 이용한 텍스트 처리, 시계열 Trend 예측 시 사용하는 시계열 알고리즘 종류를 정리해보려고 한다.
머신러닝 및 딥러닝 입문으로 가장 접근하기 좋은게 주가/비트코인 시계열 예측 아니겠어??

 

SimpleRNN (Recurrent Neural Networks)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import SimpleRNN, Dense

model = Sequential()
model.add( SimpleRNN(20, input_shape=(n_timestep,n_features), return_sequences = False)
model.add( Dense(1) )

 

LSTM (Long Short Term Memory)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense

model = Sequential()
model.add( LSTM(20, input_shape=(n_timestep,n_features), return_sequences = False)
model.add( Dense(1) )

 

GRU (Gated Recurrent Unit) 
한국인인 NYU 조경현 박사가 제안한 알고리즘이라고 한다. 괜히 LSTM 보다 슬며시 먼저 써보게 된다ㅎㅎ
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import GRU, Dense

model = Sequential()
model.add( GRU(20, input_shape=(n_timestep,n_features), return_sequences = False)
model.add( Dense(1) )

 

Bidirectional 
양방향 알고리즘 추가, 단독으로 쓰는게 아니고 Bidirectional(LSTM(10, ... 이런식으로 같이 쓰는 것
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Bidirectional, Dense

model = Sequential()
model.add( Bidirectional(LSTM(10, return_squences=False), input_shape=(n_timestep,n_features) )
model.add( Dense(1) )

 

TimeDistributed
각 timestep마다 cost 계산하고 오류 전파. many to many에서 쓰임.

음.. 아래 블로그가 제일 설명 자세히 되어있는듯.
m.blog.naver.com/chunjein/221589624838

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, TimeDistributed, Dense

model = Sequential()
model.add(LSTM(20, input_shape=(n_timestep,n_features), return_sequences=True))
# TimeDistributed를 쓸 땐 return_sequnces = True 로 받음
model.add(TimeDistributed(Dense(1)))
# 출력 shape 은 (n_timestep,1)

 

스태킹 순환층
stack 하려면 모든 중간 층은 return_sequences = True 해야함
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import SimpleRNN,LSTM,GRU,Bidirectional,Dense

tf.random.set_seed(0)
# 이거 안해주면 돌릴 때마다 자꾸 결과 바뀜

model = Sequential()
model.add( Bidirectional(LSTM(10, return_squences=True), input_shape=(72,1) )
# 맨 처음 layer에서는 input_shape 꼭 지정해주기
model.add( Bidirectional(SimpleRNN(10, return_squences=True) )
model.add( Bidirectional(GRU(10, return_squences=True) )
# 예시 때문에 이렇게 쓴거지 실제로 이렇게 섞어 쓰는건 본적 없다....
model.add( Bidirectional(GRU(10, return_squences=False) )
# 마지막 층에선 return_sequences=False
model.add( Dense(1) ) # many to one 가정

model.compile(loss = 'mse', optimizer = 'Adam', metrics = ['mae', 'mape'])
model.summary()

cb = early_stop = EarlyStopping(monitor='val_loss', patience=50, verbose=0)
model.fit(X_train,y_train, epochs=1000, batch_size=64, callbacks = [cb], 
		validation_data = (X_val,y_val) ) # 혹은 validation_data = (X_test, y_test)
y_pred = model.predict(X_test)

compile 에서 회귀가 아닌 경우 loss = 'sparse_categorical_crossentropy' - one hot encoding 필요한 경우
one hot encoding 필요없으면 loss = 'categorical_crossentropy' 
metrics = ['accuracy'] 

728x90
Comments