본문 바로가기
DNN with Keras/Time Series

Programming LSTM with Keras and TensorFlow

by goatlab 2022. 12. 6.
728x90
반응형
SMALL

Programming LSTM with Keras and TensorFlow

 

전방 연결을 가진 신경망은 항상 첫 번째 숨겨진 계층에 연결된 입력 계층으로 시작한다. 각 숨겨진 계층은 항상 다음 숨겨진 계층에 연결된다. 마지막 숨겨진 계층은 항상 출력 계층에 연결된다. 이러한 연결 방식이 이러한 네트워크를 "feed-forward"라고 부르는 이유이다. 반복 신경망은 역방향 연결도 허용되기 때문에 경직되지 않는다. 반복적인 연결은 층의 뉴런을 이전 층 또는 뉴런 자체에 연결한다. 대부분의 반복 신경망 아키텍처는 반복 연결에서 상태를 유지한다. 피드포워드 신경망은 어떤 상태도 유지하지 않는다.

 

LSTM

 

LSTM (Long Short Term Memory) 레이어는 심층 신경망과 함께 자주 사용하는 반복 단위의 한 유형이다. TensorFlow의 경우 LSTM을 밀도와 같은 다른 레이어 유형과 결합할 수 있는 레이어 유형으로 생각할 수 있다. LSTM은 내부적으로 두 가지 전송 함수 유형을 사용한다. 전달 함수의 첫 번째 유형은 시그모이드이다. 이 전달 기능 유형은 장치 내부의 게이트에서 사용됩니다. 시그모이드 전달 함수는 다음과 같은 방정식으로 주어진다.

 

 

두 번째 유형의 전송 함수는 LSTM의 출력을 스케일링할 수 있는 쌍곡선 탄젠트 (tanh) 함수이다. 이 기능은 본 코스에서 다른 전송 기능을 사용한 방법과 유사하다.

 

%matplotlib inline

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import math

def sigmoid(x):
  a = []
  
  for item in x:
    a.append(1/(1 + math.exp(-item)))

  return a

def f2(x):
  a = []
  
  for item in x:
    a.append (math.tanh(item))

  return a

x = np.arange(-10., 10., 0.2)
y1 = sigmoid(x)
y2 = f2(x)

print("Sigmoid")
plt.plot(x ,y1)
plt.show()

print("Hyperbolic Tangent (tanh)")
plt.plot(x ,y2)
plt.show()

 

이 두 기능 모두 출력을 특정 범위로 압축한다. 시그모이드 함수의 경우 이 범위는 0 ~ 1이다. 쌍곡선 접선 함수의 경우 이 범위는 -1 ~ 1이다. LSTM은 내부 상태를 유지하고 출력을 생성한다. 다음 다이어그램은 아래 그림에서 설명한 바와 같이 현재 타임슬라이스 (t)와 이전 (t-1) 및 다음 (t+1) 슬라이스의 세 번에 걸친 LSTM 장치를 보여준다.

 

 

y 값은 unit의 출력이며, x 값은 unit에 대한 입력이며, c 값은 context 값이다. 출력 및 컨텍스트 값은 항상 다음 시간 슬라이스에 출력을 공급한다. context 값을 사용하면 네트워크가 통화 간 상태를 유지할 수 있다. 그림은 LSTM 계층의 내부를 보여준다.

 

 

Simple Keras LSTM Example

 

from tensorflow.keras.preprocessing import sequence
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense , Embedding
from tensorflow.keras.layers import LSTM
import numpy as np

max_features = 4 # 0, 1 ,2 ,3 (total of 4)

x = [[[0], [1], [1], [0], [0], [0]],
     [[0] ,[0], [0], [2], [2], [0]],
     [[0] ,[0], [0], [0], [3], [3]],
     [[0] ,[2], [2], [0], [0], [0]],
     [[0] ,[0], [3], [3], [0], [0]],
     [[0] ,[0], [0], [0], [1], [1]]]

x = np.array(x, dtype = np.float32)
y = np.array([1, 2, 3, 2, 3, 1], dtype = np.int32)

# Convert y2 to dummy variables
y2 = np.zeros((y.shape[0], max_features), dtype = np.float32)
y2[np.arange(y.shape[0]), y] = 1.0
print(y2)
print('Build model...')

model = Sequential()
model.add(LSTM(128, dropout = 0.2, recurrent_dropout =0.2 , \
input_shape=(None ,1)))
model.add(Dense(4, activation = 'sigmoid'))

# try using different optimizers and different optimizer configs
model.compile(loss = 'binary_crossentropy',
              optimizer = 'adam',
              metrics = ['accuracy'])
print('Train...')

model.fit(x ,y2, epochs = 200)
pred = model.predict(x)
predict_classes = np.argmax(pred, axis = 1)
print("Predicted classes : {}", predict_classes)
print("Expected classes : {}", predict_classes)
Predicted classes : {} [1 2 3 2 3 1]
Expected classes : {} [1 2 3 2 3 1]
def runit(model, inp):
  inp = np.array(inp ,dtype = np.float32)
  pred = model.predict(inp)
  
  return np.argmax(pred[0])

print(runit(model, [[[0], [0], [0], [0], [0], [1]]]))
1
728x90
반응형
LIST

'DNN with Keras > Time Series' 카테고리의 다른 글

Data Encoding  (0) 2022.12.01