케라스에서 모델 설계를 할 때 Sequential( )을 주로 사용해왔다. 단순히 이전 layer의 output이 다음 layer의 input으로 들어가는 선형적인 경우에 사용해주면 아주 편리하기 때문이다. 그래서 단점도 존재한다. DenseNet( ) 같이 선형적 흐름이 아닌 모델 설계의 경우엔 사용하질 못 한다.
keras.models.Model( )을 사용하면 Sequential( )의 불편한 점에서 벗어날 수 있다. 이 놈은 Multi Input / Multi Output을 지원한다.

위와 같은 흐름을 갖는 모델을 설계하고 싶다면 Model( )을 사용해주면 된다.
import keras from keras.layers import Input, Embedding, LSTM, Dense from keras.models import Model main_input = Input(shape=(100,), dtype='int32', name='main_input') x = Embedding(output_dim=512, input_dim=10000, input_length=100)(main_input) lstm_out = LSTM(32)(x) auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out) auxiliary_input = Input(shape=(5,), name='aux_input') x = keras.layers.concatenate([lstm_out, auxiliary_input]) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) main_output = Dense(1, activation='sigmoid', name='main_output')(x) model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output]) model.compile(optimizer='rmsprop', loss='binary_crossentropy', loss_weights=[1., 0.2])
Line 15와 Line 22가 가장 큰 차별점이자 장점이다. Sequential( )와 달리 input tensor를 직접 지정해줘야 해서( = 지정해줄 수 있어서) 입력 전에 input을 변경한 다음 넣어줄 수 있다. keras.layers의 Conv2D, Dense, MaxPooling2D, Dropout, BatchNormalization 등과 같은 함수들을 통해 모델의 흐름을 다 잡아줬으면, Model( )의 input tensor와 output tensor에 넣어주기만 하면 모델 설계가 끝난다.
2021.09.28. 추가
생성된 Model( ) 인스턴스에는 Tensor를 직접 넣어줄 수도 있고, predict_on_batch( ) 클래스 함수를 사용해서 numpy data를 넣어줄 수도 있다. 예제를 통해 확인해보자.
import numpy as np import keras import tensorflow as tf np.random.seed(7) tf.set_random_seed(7) def build_sample_network(): inputs = keras.layers.Input(shape = (2,)) outputs = keras.layers.Dense(units = 2, activation = 'relu')(inputs) return keras.models.Model(input = inputs, output = outputs) # build network model1 = build_sample_network() model2 = build_sample_network() # Test 1 print(model1.output) print(model2(model1.output)) # Test 2 input_data = np.random.rand(1,2) print(input_data) print(model2.predict_on_batch(input_data))
[ 실행 결과 ]

< 참고 사이트 >
https://frhyme.github.io/machine-learning/a_model_in_keras/
'Deep Learning > Keras & Tensorflow' 카테고리의 다른 글
Generative Adversarial Network (GAN) 설계 시 고려할 부분 (0) | 2021.10.08 |
---|---|
ImgaeDataGenerator.flow_from_directory을 이용해 이미지 증식하는 방법 (0) | 2021.08.31 |
MNIST 분류 모델, 조금 다르게 실행해보자 / get_tensor_by_name( ) (0) | 2021.08.31 |
RNN과 CNN 동시 사용 모델(RCNN / CRNN)의 개념 및 구현 (0) | 2021.08.31 |
Tensorflow 개념 정리) 텐서, 변수, 오퍼레이션, 계산 그래프 (0) | 2021.08.31 |