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

keras.Model 상속하기

~8 min · subclass

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

두 메서드가 부품과 계산을 나눠 맡아

keras.Model을 상속한 Python 클래스는 일을 두 메서드로 나눠. __init__()에서는 모델이 사용할 레이어를 모두 만들어 self에 저장하고, call()에서는 입력 텐서를 그 레이어에 통과시켜 출력을 만들어. 이 두 부분만 올바르게 정의하면 compile(), fit(), evaluate(), save() 같은 Keras 기능을 기본 모델과 똑같이 사용할 수 있어.

레이어 생성과 텐서 계산을 섞지 마

__init__()의 레이어는 model = MyModel()을 실행할 때 한 번 만들어지고 Keras가 그 가중치를 추적해. 반면 call()은 배치마다 순전파를 할 때마다 실행돼. 레이어를 call() 안에서 만들면 매 단계마다 학습되지 않은 새 가중치가 생기고, 텐서 계산을 __init__()에 넣으면 아직 입력 텐서가 없어 실행할 수 없지. call()training 인자는 Dropout과 BatchNormalization이 학습과 추론 동작을 구분하는 스위치이므로 관련 하위 레이어에 빠짐없이 전달해야 해.

Code

가장 작은 keras.Model 상속 예제·python
import keras
from keras import layers

class MyModel(keras.Model):
    def __init__(self):
        super().__init__()
        self.dense1 = layers.Dense(128, activation="relu")
        self.dropout = layers.Dropout(0.3)
        self.dense2 = layers.Dense(10, activation="softmax")

    def call(self, inputs, training=False):
        x = self.dense1(inputs)
        x = self.dropout(x, training=training)
        return self.dense2(x)

model = MyModel()
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy")
model.fit(x_train, y_train, epochs=5)

External links

Exercise

MNIST 분류기를 keras.Model 상속 방식으로 다시 구현해. 첫 call() 전후의 model.summary()를 비교하고 차이를 적어.

Progress

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

댓글 0

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

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