C.W.K.
Stream
Lesson 03 of 07 · published

keras.layers.Layer subclass

~8 min · subclass

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

진짜 일꾼은 layer

Layer 를 subclass 하는 게 Model 통째로 subclass 하는 것보다 훨씬 흔해 — 권장되는 building block 이거든. custom layer 는 Sequential, Functional, 또는 다른 subclass model 안에 군말 없이 끼워지니까. 알아둘 메서드는 셋: __init__() 은 config 저장 (units 몇 개, activation 뭐), build() 는 weight 생성, call() 은 forward (Code block 참고).

weight 가 왜 __init__() 말고 build() 에 사나

재밌는 건 build(input_shape) 야. weight 를 __init__() 에서 만들 *수도* 있어, 근데 그러면 입력의 feature 차원을 미리 알고 하드코딩해야 해 — layer 를 다른 데서 재사용하는 순간 깨져. build() 가 Keras 의 답이야: layer 가 실제 데이터를 처음 보는 순간 자동 실행되고, 구체적인 input_shape 를 받아서 input_shape[-1] 로 weight 행렬 크기를 정해. 이게 *lazy weight creation* 이고, 그래서 MyDense(64) 라고만 써도 들어오는 입력에 맞춰 적응해. weight 는 add_weight() 로 등록하는데, 이게 Keras 가 그걸 trainable variable 로 추적하게 만드는 지점이야.

get_config() 가 serialization 의 고리를 닫아 — 생성자 인자를 평범한 dict 로 돌려줘서 Keras 가 저장된 파일에서 layer 를 복원할 수 있게 해. 빼먹으면 custom layer 가 model.save() / load_model() 를 왕복 못 해.

Code

build() 와 get_config() 를 갖춘 custom Dense layer·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 subclass 로 'ScaledDense' 만들어 — Dense 후 출력에 학습가능 scalar 곱하기. weight 가 첫 call 에 생성되는지 확인.

Progress

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

댓글 0

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

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