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

레이어 공유와 모델 중첩

~11 min · functional

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

한 레이어의 가중치를 여러 경로에서 쓴다

공유 레이어는 같은 가중치를 서로 다른 입력에 적용해. 레이어 인스턴스를 한 번 만든 뒤 여러 텐서에 호출하면 모든 경로가 한 벌의 가중치를 사용하고, 각 호출에서 나온 기울기도 그 가중치에 모여. 첫 코드 블록의 Siamese 신경망에서는 shared_embedding 하나가 두 입력을 같은 방식으로 인코딩해 공통 임베딩 공간을 학습해. 입력마다 별도 인코더를 만들면 둘의 거리를 비교할 공통 기준이 사라져.

모델도 다른 모델 안에서 레이어처럼 쓸 수 있어

모든 Keras Model은 다른 모델 안에서 레이어처럼 호출할 수 있어(두 번째 코드 블록). 전이 학습도 이 원리를 사용해. 사전 학습된 백본은 입력에 호출하는 하나의 Model이고 그 위에 새 헤드를 붙이면 돼. 중첩된 모델은 자신의 가중치를 유지하므로 사전 학습 가중치를 불러온 뒤 backbone.trainable = False로 고정할 수 있어. 인코더와 디코더를 합쳐 오토인코더를 만드는 것도 같은 방식이야. 레이어 공유와 서브그래프 재사용은 규모만 다를 뿐 같은 원리야.

Code

공유 임베딩을 사용하는 Siamese 유사도 신경망·python
# Shared embedding for a Siamese network
shared_embedding = layers.Dense(64, activation="relu", name="shared_embed")

input_a = keras.Input(shape=(128,))
input_b = keras.Input(shape=(128,))

# Same weights used for both inputs
encoded_a = shared_embedding(input_a)
encoded_b = shared_embedding(input_b)

# Compute distance
distance = layers.Lambda(
    lambda x: keras.ops.abs(x[0] - x[1])
)([encoded_a, encoded_b])
output = layers.Dense(1, activation="sigmoid")(distance)

model = keras.Model(inputs=[input_a, input_b], outputs=output)
모델 중첩 — 인코더와 디코더를 오토인코더로 결합·python
# Use an existing model as a layer
encoder = keras.Model(encoder_inputs, encoded, name="encoder")
decoder = keras.Model(decoder_inputs, decoded, name="decoder")

# Nest them
inputs = keras.Input(shape=(784,))
z = encoder(inputs)       # Model called like a layer
outputs = decoder(z)
autoencoder = keras.Model(inputs, outputs)

External links

Exercise

영상 유사도를 구하는 Siamese 신경망을 만들어. 공유 CNN 인코더를 두 입력에 적용하고 L2 거리와 sigmoid로 출력해. Functional API로 작성하고 합성 쌍 데이터로 학습해.

Progress

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

댓글 0

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

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