2019년 4월 28일 일요일

Keras LSTM 입력 포맷의 이해 Understanding Input shapes in LSTM | Keras



LSTM을 사용해보려고 하는데 입력과 출력에 대해서 자세히 나온 부분이 없어서 정리해 보았습니다.
기본적인 내용은 아래 참조 링크를 사용하였습니다.

참조 링크 : https://medium.com/@shivajbd/understanding-input-and-output-shape-in-lstm-keras-c501ee95c65e

참조 링크 : https://towardsdatascience.com/predicting-stock-price-with-lstm-13af86a74944

위 링크 저자도 처음에 혼란스러웠다고 되어있네요.

LSTM을 하기 위해서는 3차원적 데이터가 필요합니다. (대부분의 예제의 경우 batch(일괄처리)값 설정없이 input_shape을 사용합니다. 만약 batch를 설정하려면 batch_input_shape 값에 batch값을 추가하여 차원을 추가한 입력을 사용해야합니다.)

[data_size, time_steps, features] 3차원 array로 구성됩니다.

Keras input_shape 예제
model = keras.models.Sequential()
model.add(keras.layers.LSTM(unit=3, input_shape=(3, 5)))

위 예에서 (2,10)은 time_steps=3, features=5 가 됩니다. data_size는 따로 넘기지 않습니다. data_size 정보는 없어도 넘어오는 크기로 부터 전체 data size를 알 수 있기 때문입니다.

이것을 그림으로 그려보면 다음과 같습니다.


time_steps는 Network에 사용할 시간 단위입니다. 이 값은 LSTM에서 과거의 몇개 데이터를 볼것인가 가지고 결정합니다. 위 그림에서 녹색 box부분을 보면 3개 데이터를 이용해서 다음 한개를 추론 하기 때문에 time_steps:3 이 됩니다.
data_size는 데이터의 크기 입니다. 위 그림에서는 N으로 표시 하였습니다. 커다란 박스의 개수가 3개 있고, 추가로 2개 더 그릴수 있으므로 데이터는 5개가 될 것입니다.
Features 는 일반적인 경우 X의 차원을 의미합니다. LSTM에서는 input이 time_steps에 의해서 여러개의 입력 나타내지는데 그것의 속성의 수가 됩니다. 여기에서는 Open, High, Low, Close, Volume 이렇게 5개가 들어갑니다.

Batch에 대하여

Batch는 일괄 처리되는 작업의 양이다. 위에서 설명된 data_size를 한번에 처리하는 갯수를 의미하며, batch크기에 의해 weight 변화가 일어나며 batch크기 단위로 data loading 함수도 구현이 가능하다. 주의할점은 data_size/batch_size일때 나머지가 없어야 한다.

batch 되는 양이 있다면 아래와 같이 설정할 수도 있습니다.

Keras batch_input_shape 예제 
model = keras.models.Sequential()
model.add(keras.layers.LSTM(unit=4, batch_input_shape=(3, 4, 6)))
batch_size, time_steps, features 각각은 3,4,6이 됩니다.

실제 데이터의 크기는 [6,4,6]으로 준비가 된 모습입니다. batch_size로 차원을 구성하는것이 아닙니다. batch_size = 3으로 6/3이 되므로 나머지가 없기 때문에 문제가 없습니다. 나머지가 생기게 되면 batch 작업시 문제가 생깁니다.

unit=4 은 해당 layer의 출력 크기가 된다.


댓글 4개:

  1. unit = 4 가 해당 레이어의 출력의 크기가 된다고 하셨는데 output_dimension과는 뭐가 다른건가요? 그리고 일반적으로 unit의 수는 어떻게 결정하는지 궁금합니다

    답글삭제
  2. LSTM (Long Short-Term Memory) is a type of recurrent neural network (RNN) designed to process and learn from sequential data. Unlike traditional RNNs, LSTMs can remember important information for long periods while forgetting irrelevant details through special components called gates. This makes them highly effective for tasks such as speech recognition, language translation, text prediction, handwriting recognition, and time-series forecasting. Their ability to capture long-term dependencies has made LSTMs a fundamental model in deep learning applications.

    답글삭제