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

keras.layers.Layer 상속하기

~8 min · subclass

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

모델 전체보다 레이어 하나를 상속하는 일이 더 흔해

사용자 정의 레이어는 Sequential, Functional, 다른 Subclass 모델 어디에나 기본 레이어처럼 넣을 수 있어 재사용하기 좋아. 세 메서드의 역할을 기억하면 돼. __init__()은 units와 activation 같은 설정을 보관하고, build()는 가중치를 만들며, call()은 순전파 계산을 정의해.

가중치는 입력 모양을 안 뒤에 만들어

가중치를 __init__()에서 만들면 입력 특징 차원을 미리 정해 코드에 박아야 하므로 다른 입력에 재사용하기 어려워. build(input_shape)는 레이어가 실제 입력을 처음 볼 때 자동으로 호출되고 input_shape[-1]을 이용해 가중치 행렬의 크기를 정해. 이런 지연 생성 덕분에 MyDense(64)라고만 작성해도 입력에 맞춰 가중치가 만들어져. add_weight()로 등록해야 Keras가 그 값을 학습 가능한 변수로 추적해.

get_config()는 생성자 인자를 평범한 딕셔너리로 돌려줘 저장된 파일에서 같은 레이어를 다시 만들 수 있게 해. 이를 빠뜨리면 사용자 정의 레이어가 포함된 모델은 model.save()load_model()을 온전히 왕복하지 못해.

Code

build()와 get_config()를 갖춘 사용자 정의 Dense 레이어·python
class MyDense(keras.layers.Layer):
    def __init__(self, units, **kwargs):
        super().__init__(**kwargs)
        self.units = units

    def build(self, input_shape):
        # Lazy weight creation — called on first use
        self.w = self.add_weight(
            shape=(input_shape[-1], self.units),
            initializer="glorot_uniform",
            trainable=True,
            name="kernel",
        )
        self.b = self.add_weight(
            shape=(self.units,),
            initializer="zeros",
            trainable=True,
            name="bias",
        )

    def call(self, inputs):
        return keras.ops.matmul(inputs, self.w) + self.b

    def get_config(self):
        config = super().get_config()
        config.update({"units": self.units})
        return config

External links

Exercise

keras.layers.Layer를 상속해 Dense 출력에 학습 가능한 스칼라를 곱하는 ScaledDense를 만들어. 첫 호출에서 가중치가 생성되는지 확인해.

Progress

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

댓글 0

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

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