Keras-한 모델로 두 가지 이상 작업하기
10 Feb 2020 | Keras목차
Keras를 사용하요 모델을 작성하다가 두 개 이상의 모델을 이용해야 할 경우가 생겼다. 예를들어 Segmentation과 Classfication을 동시에 학습시켜 성능을 측정해보는 이번 작업의 경우가 그러하였다. 그럴 경우에 유용할 수 있는 예제 코드를 documentation을 통해서 한 번 간단하게 실습해보았다.

Epoch 1/1
1/1 [==============================] - 2s 2s/step - loss: 0.3095 - A3_loss: 0.1675 - B3_loss: 0.8776
학습이 진행되는 모습을 볼 수 있다. 이렇게 두 가지 작업을, 각각 다른 loss함수로, 그리고 가중치까지 주어서 학습할 수 있다는 것을 보았다.
from keras.layers import Input, Dense
from keras.models import Model
from keras.utils import plot_model
import numpy as np
A1 = Input(shape=(30,),name='A1')
A2 = Dense(8, activation='relu',name='A2')(A1)
A3 = Dense(30, activation='relu',name='A3')(A2) # 여러 개의 값 추정 한다고 가정 ( ex)segmentation)
B2 = Dense(40, activation='relu',name='B2')(A2)
B3 = Dense(1, activation='relu',name='B3')(B2) # binary classfication 한다고 가정
model = Model(inputs=[A1],outputs=[A3,B3])
plot_model(model, to_file='./desktop/sunwoo/demo.png',show_shapes=True)
# Input
a = np.ones(30).reshape(1,-1)
a.shape
# Output
l1 = np.zeros(30).reshape(1,-1)
l2 = np.ones(1).reshape(1,-1)
print(l1.shape)
print(l2.shape)
model.compile(optimizer='sgd',
# loss도 다르게 할 수 있다.
loss={'A3': 'binary_crossentropy', 'B3': 'mean_squared_error'},
loss_weights={'A3': 0.8, 'B3': 0.2}) # Dictionary 형태로 접근
model.fit(a, {'A3': l1, 'B3': l2}) # Dictionary 형태로 접근