티스토리 뷰

728x90
반응형

케라스(Keras)에서 딥러닝 모델을 구성하는 방법에는 Sequential APIFunctional API 두 가지가 있습니다.
이전 글에서는 Sequential API를 사용하여 간단한 신경망을 구축했지만, 복잡한 모델을 만들기 위해서는 Functional API가 필요합니다.

이번 글에서는 Functional API와 Sequential API의 차이점을 살펴보고, 다중 입력/출력 및 잔차 연결(Residual Connection) 같은 복잡한 모델을 구축하는 방법을 예제와 함께 알아보겠습니다.


1. Functional API와 Sequential API의 차이점

Sequential API

  • 레이어를 순차적으로 쌓는 방식으로 모델을 구성
  • 간단한 신경망에 적합하지만, 복잡한 네트워크를 구현하기 어려움
  • 예제 코드:
     
     
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

model = Sequential([
    Dense(64, activation='relu', input_shape=(100,)),
    Dense(10, activation='softmax')
])

Functional API

  • 레이어를 자유롭게 연결 가능 (다중 입력/출력, 공유 레이어, 잔차 연결 등 지원)
  • 복잡한 네트워크(ResNet, GAN, Siamese Network 등)를 만들 때 사용됨
  • 유연성과 확장성이 뛰어남
  • 예제 코드:
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model

inputs = Input(shape=(100,))
x = Dense(64, activation='relu')(inputs)
outputs = Dense(10, activation='softmax')(x)

model = Model(inputs=inputs, outputs=outputs)

🛠 Functional API의 주요 특징

기능Sequential APIFunctional API

순차적 모델 구성 ✅ 가능 ✅ 가능
다중 입력/출력 모델 ❌ 불가능 ✅ 가능
레이어 공유 ❌ 불가능 ✅ 가능
잔차 연결(Residual Connection) ❌ 불가능 ✅ 가능
유연한 네트워크 구조 ❌ 제한적 ✅ 가능

2. 복잡한 모델 구현 방법

Functional API를 사용하면 다음과 같은 복잡한 모델을 만들 수 있습니다.

(1) 다중 입력/출력 모델

  • 한 개 이상의 입력 데이터를 받아 서로 다른 출력을 생성하는 모델
  • 예제: 텍스트 데이터와 이미지 데이터를 함께 사용하여 감정을 분석하는 모델
from tensorflow.keras.layers import Input, Dense, concatenate
from tensorflow.keras.models import Model

# 두 개의 입력 정의
input_text = Input(shape=(100,), name="text_input")
input_image = Input(shape=(64, 64, 3), name="image_input")

# 각각의 입력을 처리하는 레이어 구성
x1 = Dense(64, activation='relu')(input_text)
x2 = Dense(64, activation='relu')(input_image)

# 두 개의 레이어를 합치기
merged = concatenate([x1, x2])

# 최종 출력 (이진 분류)
output = Dense(1, activation='sigmoid')(merged)

# 모델 생성
model = Model(inputs=[input_text, input_image], outputs=output)
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

model.summary()

(2) 잔차 연결(Residual Connection)

  • 딥러닝에서 깊은 네트워크의 성능 저하 문제(Gradient Vanishing)를 해결하는 기법
  • ResNet(Residual Network) 같은 모델에서 사용됨
from tensorflow.keras.layers import Input, Dense, Add
from tensorflow.keras.models import Model

# 입력 정의
inputs = Input(shape=(100,))

# 첫 번째 Dense 레이어
x = Dense(64, activation='relu')(inputs)

# 두 번째 Dense 레이어
x1 = Dense(64, activation='relu')(x)

# 잔차 연결 (입력과 출력 더하기)
x2 = Add()([x, x1])

# 출력층
outputs = Dense(10, activation='softmax')(x2)

# 모델 생성
model = Model(inputs=inputs, outputs=outputs)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

model.summary()
 

🔹 잔차 연결의 역할: 입력 데이터를 다음 층과 직접 더해주므로 정보 손실을 줄이고 학습 속도를 높이는 효과가 있습니다.


3. Functional API 실습 예제

예제: 다중 입력/출력 모델 (학습 및 평가)

아래는 두 개의 입력을 받아 두 개의 출력을 생성하는 모델을 만드는 예제입니다.

import numpy as np
from tensorflow.keras.layers import Input, Dense, concatenate
from tensorflow.keras.models import Model

# 더미 데이터 생성
num_samples = 1000
x1_train = np.random.rand(num_samples, 10)  # 첫 번째 입력
x2_train = np.random.rand(num_samples, 5)   # 두 번째 입력
y1_train = np.random.randint(0, 2, size=(num_samples,))  # 첫 번째 출력 (이진 분류)
y2_train = np.random.rand(num_samples, 1)  # 두 번째 출력 (회귀 문제)

# 입력 정의
input1 = Input(shape=(10,))
input2 = Input(shape=(5,))

# 각 입력을 처리하는 네트워크
x1 = Dense(32, activation='relu')(input1)
x2 = Dense(16, activation='relu')(input2)

# 두 개의 입력을 합치기
merged = concatenate([x1, x2])

# 두 개의 출력 생성
output1 = Dense(1, activation='sigmoid', name="output1")(merged)  # 분류 문제
output2 = Dense(1, name="output2")(merged)  # 회귀 문제

# 모델 정의
model = Model(inputs=[input1, input2], outputs=[output1, output2])
model.compile(optimizer='adam', 
              loss={'output1': 'binary_crossentropy', 'output2': 'mse'}, 
              metrics={'output1': 'accuracy', 'output2': 'mae'})

# 모델 학습
model.fit([x1_train, x2_train], [y1_train, y2_train], epochs=10, batch_size=32)

# 모델 평가
loss, loss1, loss2, acc1, mae2 = model.evaluate([x1_train, x2_train], [y1_train, y2_train])
print(f"분류 정확도: {acc1:.4f}, 회귀 MAE: {mae2:.4f}")

결론

이 글에서는 Functional API의 개념과 Sequential API의 차이점을 살펴보고, 다중 입력/출력 및 잔차 연결과 같은 복잡한 모델을 구축하는 방법을 예제와 함께 설명했습니다.

Functional API는 복잡한 신경망을 만들 때 필수적인 도구이며, CNN, RNN, GAN, Transformer 등의 다양한 모델을 구현할 때 매우 유용합니다.

다음 으로는 **케라스의 고급 기능(콜백, 하이퍼파라미터 튜닝 등)**을 활용하여 더욱 강력한 모델을 만드는 방법을 배워보겠습니다! 🚀

728x90
반응형