developer tip

Keras의 다 대일 및 다 대다 LSTM 예제

optionbox 2020. 9. 17. 07:40
반응형

Keras의 다 대일 및 다 대다 LSTM 예제


LSTM과 Keras를 사용하여 구축하는 방법을 이해하려고합니다. RNN을 실행하는 데 주로 4 가지 모드가 있다는 것을 알아 냈습니다 (사진에서 올바른 4 가지 모드).

여기에 이미지 설명 입력이미지 출처 : Andrej Karpathy

이제 Keras에서 각각에 대한 최소한의 코드 조각이 어떻게 생겼는지 궁금합니다. 그래서 뭔가

model = Sequential()
model.add(LSTM(128, input_shape=(timesteps, data_dim)))
model.add(Dense(1))

4 가지 작업 각각에 대해 약간의 설명이있을 수 있습니다.


그래서:

  1. 일대일 : Dense시퀀스를 처리하지 않으므로 레이어를 사용할 수 있습니다 .
    model.add(Dense(output_size, input_shape=input_shape))

2. 일대 다 :이 옵션은 지원되지 않으며에서 모델을 연결하는 것이 쉽지 Keras않으므로 다음 버전이 가장 쉬운 버전입니다.

    model.add(RepeatVector(number_of_times, input_shape=input_shape))
    model.add(LSTM(output_size, return_sequences=True))
  1. 다 대일 : 실제로 코드 조각은 (거의)이 접근 방식의 예입니다.
    model = Sequential()
    model.add(LSTM(1, input_shape=(timesteps, data_dim)))
  1. Many-to-many: This is the easiest snippet when the length of the input and output matches the number of recurrent steps:
    model = Sequential()
    model.add(LSTM(1, input_shape=(timesteps, data_dim), return_sequences=True))
  1. Many-to-many when number of steps differ from input/output length: this is freaky hard in Keras. There are no easy code snippets to code that.

EDIT: Ad 5

In one of my recent applications, we implemented something which might be similar to many-to-many from the 4th image. In case you want to have a network with the following architecture (when an input is longer than the output):

                                        O O O
                                        | | |
                                  O O O O O O
                                  | | | | | | 
                                  O O O O O O

You could achieve this in the following manner:

    model = Sequential()
    model.add(LSTM(1, input_shape=(timesteps, data_dim), return_sequences=True))
    model.add(Lambda(lambda x: x[:, -N:, :]

Where N is the number of last steps you want to cover (on image N = 3).

From this point getting to:

                                        O O O
                                        | | |
                                  O O O O O O
                                  | | | 
                                  O O O 

적절한 크기로 조정하기 위해 N예를 들어 0벡터 와 함께 사용 하는 길이의 인위적인 패딩 시퀀스만큼 간단 합니다.


@Marcin Możejko의 훌륭한 답변

나는 것 NR.5에 다음을 추가 (길이에서 / 다른에 많은 많은) :

A) 바닐라 LSTM

model = Sequential()
model.add(LSTM(N_BLOCKS, input_shape=(N_INPUTS, N_FEATURES)))
model.add(Dense(N_OUTPUTS))

B) 인코더-디코더 LSTM

model.add(LSTM(N_BLOCKS, input_shape=(N_INPUTS, N_FEATURES))  
model.add(RepeatVector(N_OUTPUTS))
model.add(LSTM(N_BLOCKS, return_sequences=True))  
model.add(TimeDistributed(Dense(1)))
model.add(Activation('linear')) 

참고 URL : https://stackoverflow.com/questions/43034960/many-to-one-and-many-to-many-lstm-examples-in-keras

반응형