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

Functional과 Subclassing 함께 쓰기

~8 min · subclass

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

동적인 레이어와 정적인 뼈대를 결합해

가장 실용적인 패턴은 필요한 레이어만 상속한 뒤 Functional API로 연결하는 거야. 사용자 정의 레이어 안에는 Python 로직을 자유롭게 넣을 수 있지만 바깥에서는 텐서를 받아 텐서를 돌려주는 호출 가능한 객체일 뿐이라 DenseConv2D처럼 그래프에 넣을 수 있어.

모든 레이어가 같은 계약을 지켜

기본 레이어와 사용자 정의 레이어는 모두 layer(tensor) -> tensor라는 인터페이스를 제공해. Functional API는 내부 구현을 몰라도 결과 텐서를 다음 레이어로 연결할 수 있어. 따라서 Python 로직과 건너뛰기 연결을 가진 ResidualBlock을 넣어도 바깥 구조는 model.summary()로 살펴볼 수 있고 사용자 정의 블록 내부만 불투명해져. 구조 분석 비용을 꼭 필요한 곳에만 가두는 셈이야.

반대 조합도 가능해. 상속한 Model__init__()에서 Functional 하위 모델을 만들고 call()에서 호출할 수 있어. 사전 학습된 ResNet이나 Vision Transformer 백본을 Functional 모델로 두고, 사용자 정의 라우팅이나 손실을 처리하는 얇은 Subclass 헤드로 감싸는 구조가 흔한 예야.

Code

Functional 모델 안에서 사용하는 Subclass ResidualBlock·python
# Custom layer
class ResidualBlock(keras.layers.Layer):
    def __init__(self, filters, **kwargs):
        super().__init__(**kwargs)
        self.dense1 = layers.Dense(filters, activation="relu")
        self.dense2 = layers.Dense(filters)
        self.add_layer = layers.Add()
        self.activation = layers.Activation("relu")

    def call(self, inputs):
        x = self.dense1(inputs)
        x = self.dense2(x)
        x = self.add_layer([x, inputs])
        return self.activation(x)

# Use custom layer in Functional API
inputs = keras.Input(shape=(64,))
x = layers.Dense(64, activation="relu")(inputs)
x = ResidualBlock(64)(x)  # Custom layer used like any built-in
x = ResidualBlock(64)(x)
outputs = layers.Dense(10, activation="softmax")(x)
model = keras.Model(inputs, outputs)

External links

Exercise

Functional 모델 안에 사용자 정의 MultiHeadAttention 같은 Subclass 레이어 하나를 넣어. model.summary()에서 바깥 구조와 사용자 정의 레이어가 모두 보이는지 확인해.

Progress

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

댓글 0

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

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