C.W.K.
Stream
Lesson 06 of 06 · published

Custom layer — 내장이 못 다룰 때

~13 min · custom-layer, build, add-weight

Level 0Level 0
0 XP0/78 lessons0/17 achievements
0/100 XP to next level100 XP to go0% complete

세 메서드, 더 적게는 안 됨

내장 layer로 안 되는 architecture는 keras.layers.Layer 상속. 구현할 세 메서드:

  1. __init__ — config 저장 (units, activation 등). 여기서 weight 만들지 마.
  2. build(input_shape) — weight 여기서 생성. 첫 forward에서 input shape 확정될 때 한 번 호출. self.add_weight(...) 써 — Keras 3에선 raw tf.Variable 절대 금지.
  3. call(inputs) — forward 계산.

저장/불러오기 위해 get_config()도 구현 — from_config()가 layer 재구성에 쓸 dict 반환.

Keras 3 breaking change: self.add_weight() 써, tf.Variable 안 됨. Keras 3의 variable tracking이 raw tf.Variable은 더 이상 자동 추적 안 해. layer 안에서 그거 쓰면 optimizer한테 weight가 안 보여 — model이 아무것도 학습 안 하는데 이유 모르고 헤매게 돼.

Code

CustomDense — the canonical pattern·python
import tensorflow as tf
from keras import layers

class CustomDense(layers.Layer):
    def __init__(self, units=32, activation=None, **kwargs):
        super().__init__(**kwargs)
        self.units = units
        self.activation = tf.keras.activations.get(activation)

    def build(self, input_shape):
        self.kernel = self.add_weight(
            name="kernel",
            shape=(input_shape[-1], self.units),
            initializer="glorot_uniform",
            trainable=True,
        )
        self.bias = self.add_weight(
            name="bias",
            shape=(self.units,),
            initializer="zeros",
            trainable=True,
        )
        super().build(input_shape)

    def call(self, inputs):
        output = tf.matmul(inputs, self.kernel) + self.bias
        if self.activation is not None:
            output = self.activation(output)
        return output

    def get_config(self):
        config = super().get_config()
        config.update({
            "units": self.units,
            "activation": tf.keras.activations.serialize(self.activation),
        })
        return config

# Use in a Sequential model
model = tf.keras.Sequential([
    tf.keras.Input(shape=(784,)),
    CustomDense(256, activation='relu'),
    CustomDense(10),
])

External links

Exercise

ScaleLayer를 직접 구현. 학습 가능한 스칼라 weight scale 하나 (초기값 1.0)를 가지고 inputs * scale 반환하게. y = 3 * x 데이터로 훈련 후 학습된 scale이 3.0 근처로 수렴하는지 확인.

Progress

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

댓글 0

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

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