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

Custom layer 의 패턴: class MyLayer(keras.layers.Layer); __init__ (config), build(input_shape) (weight 생성), call(inputs) (forward). build 가 첫 call 시점에 자동 호출 — 그때 input shape 알게 되고, 그 기반으로 self.add_weight() 호출.

add_weight 의 인자: name, shape, initializer, trainable. 보통 trainable parameter 는 W (weight matrix) 와 b (bias). non-trainable 도 가능 — moving average, mask 등.

Code

class <span class="dc">MyDense</span>(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

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

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