Just Fighting

SimpleRNN 이해하기 본문

ML & DL

SimpleRNN 이해하기

yennle 2022. 7. 24. 16:43
728x90

https://wikidocs.net/106473

 

4) 케라스의 SimpleRNN과 LSTM 이해하기

케라스의 SimpleRNN과 LSTM을 이해해봅니다. #1. 임의의 입력 생성하기 ``` import numpy as np import tensorflow as tf fr ...

wikidocs.net

 

 

먼저 입력값을 임의로 정해준다.

이때, RNN은 3D 텐서를 입력으로 받기 때문에 2차원 입력을 3차원으로 바꾸어주어야 한다.

import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import SimpleRNN, LSTM, Bidirectional
# 임의의 입력. 문장의 길이가 4이고, 차원이 5인 2D 텐서
# RNN은 3D 텐서를 입력받기 때문에 2D 텐서를 3D 텐서로 변경!
train_X = [[0.1, 4.2, 1.5, 1.1, 2.8], [1.0, 3.1, 2.5, 0.7, 1.1], [0.3, 2.1, 1.5, 2.1, 0.1], [2.2, 1.4, 0.5, 0.9, 1.1]]
print(np.shape(train_X))

# 3D 텐서. 밖에 대괄호 하나 더 추가함.
train_X = [[[0.1, 4.2, 1.5, 1.1, 2.8], [1.0, 3.1, 2.5, 0.7, 1.1], [0.3, 2.1, 1.5, 2.1, 0.1], [2.2, 1.4, 0.5, 0.9, 1.1]]]
train_X = np.array(train_X, dtype=np.float32)
print(train_X.shape)

 

 

return_sequences = False, retrun_state = False 인 경우에는

마지막 시점의 은닉상태만 리턴한다.

rnn = SimpleRNN(3)  # 은닉 상태의 크기 3
# rnn = SimpleRNN(3, return_sequences=False, return_state=False)와 동일.
hidden_state = rnn(train_X)

# 마지막 시점의 은닉상태
print('hidden state : {}, shape: {}'.format(hidden_state, hidden_state.shape))

 

 

return_sequences = True, retrun_state = False 인 경우에는

모든 시점의 은닉상태를 리턴한다.

rnn = SimpleRNN(3, return_sequences=True)  # 은닉 상태의 크기 3, return_sequences=True
hidden_state = rnn(train_X)

# 모든 시점의 은닉상태
print('hidden state : {}, shape: {}'.format(hidden_state, hidden_state.shape))

 

 

return_sequences = True, retrun_state = True 인 경우에는

모든 시점의 은닉상태와 마지막 시점의 은닉상태를 리턴한다.

rnn = SimpleRNN(3, return_sequences=True, return_state=True)    # 은닉 상태의 크기 3, return_sequences=True, return_state=True
hidden_states, last_state = rnn(train_X)

# 모든 시점의 은닉상태와 마지막 시점의 은닉상태
print('hidden states : {}, shape: {}'.format(hidden_states, hidden_states.shape))
print('last hidden state : {}, shape: {}'.format(last_state, last_state.shape))

 

 

return_sequences = False, retrun_state = True 인 경우에는

모든시점의 은닉상태는 리턴되지 않는다.

rnn = SimpleRNN(3, return_sequences=False, return_state=True)   # 은닉 상태의 크기 3, return_sequences=False, return_state=True
hidden_state, last_state = rnn(train_X)

# 모든 시점의 은닉상태가 출력되지 않음
print('hidden state : {}, shape: {}'.format(hidden_state, hidden_state.shape))
print('last hidden state : {}, shape: {}'.format(last_state, last_state.shape))

728x90

'ML & DL' 카테고리의 다른 글

GRU 개념정리  (0) 2022.07.24
LSTM 개념 정리 및 실습  (0) 2022.07.24
RNN 개념정리  (0) 2022.07.24
[PySpark] 나이브 베이즈 실습  (0) 2022.06.09
[개념 정리] 나이브 베이즈 (Naive Bayes)  (0) 2022.06.08
Comments