본문 바로가기
C.W.K.
Stream
Lesson 02 of 07 · published

Functional 패턴

~8 min · functional

Level 0Keras 도제
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

복잡한 그래프도 세 단계로 만든다

Functional API의 기본 절차는 그래프가 커져도 바뀌지 않아.

  1. 입력 정의keras.Input(shape=...)으로 모양과 자료형만 가진 기호 텐서를 만들어. 아직 실제 데이터는 없어.
  2. 레이어 연결x = Layer()(x)를 호출할 때마다 그래프에 연결 하나가 기록돼.
  3. 모델 생성keras.Model(inputs, outputs)를 호출하면 Keras가 출력에서 입력까지 거슬러 올라가 DAG를 확정해.

두 쌍의 괄호가 하는 일은 달라

layers.Dense(64, activation="relu")는 레이어 객체를 만들고, 이어지는 (inputs)는 그 레이어를 텐서에 적용해. 앞 괄호는 설정과 가중치를 가진 객체를 만들고 뒤 괄호는 그래프에 연결한 뒤 새 기호 텐서를 돌려줘.

생성과 호출이 나뉘어 있으므로 같은 레이어 인스턴스를 여러 번 호출할 수 있어. dense = Dense(64)를 만든 뒤 dense(x1)dense(x2)를 호출하면 두 경로가 같은 가중치를 공유해. 레이어 공유와 weight tying은 이 성질에서 나와. 이때 실제 데이터로 순전파를 실행하는 것이 아니라 계산 그래프를 설명하고 있으므로 결과를 직렬화할 수 있어.

Code

세 단계 Functional 패턴(MNIST 분류기)·python
import keras
from keras import layers

# Step 1: Define input
inputs = keras.Input(shape=(784,))

# Step 2: Chain layers
x = layers.Dense(256, activation="relu")(inputs)
x = layers.Dropout(0.3)(x)
x = layers.Dense(128, activation="relu")(x)
outputs = layers.Dense(10, activation="softmax")(x)

# Step 3: Create model
model = keras.Model(inputs=inputs, outputs=outputs, name="my_classifier")
model.summary()

External links

Exercise

MNIST Sequential 모델을 Functional API로 바꾸고 model.summary()가 같은지 확인해. 그다음 Dense 레이어 하나를 두 입력에 적용하고 len(model.weights)로 가중치가 공유되는지 확인해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.