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

Immutable Tensor vs Mutable Variable

~11 min · variable, constant, trainable, gradient

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

Training 전체를 떠받치는 분리

TF엔 본질적으로 다른 두 컨테이너가 있어 — tf.constant (immutable)와 tf.Variable (mutable). 차이를 아는 게 필수야. training loop 전체가 이 위에 얹혀 있거든.

tf.constant는 read-only tensor. 입력 데이터, 하이퍼파라미터, 고정 lookup table용으로 딱.

tf.Variable은 mutable. assign, assign_add, assign_sub로 in-place 업데이트. 결정적으로 tf.Variabletf.GradientTape가 자동으로 watch해 — 이게 gradient 기반 파라미터 업데이트를 가능하게 만드는 핵심.

Keras의 모든 Dense, Conv2D layer weight가 tf.Variable이야. optimizer step마다 assign_sub가 호출돼. constant/Variable 구분이 곧 trainable/non-trainable 구분이라고 생각하면 돼.

Code

Variable mutation methods·python
import tensorflow as tf

w = tf.Variable([[1.0, 2.0], [3.0, 4.0]], name="weights")
b = tf.Variable([0.0, 0.0], name="bias")

print(w.numpy())     # [[1. 2.] [3. 4.]]
print(w.shape)       # (2, 2)
print(w.dtype)       # float32
print(w.name)        # weights:0

w.assign([[5.0, 6.0], [7.0, 8.0]])      # full replace
b.assign_add([1.0, 1.0])                # b += [1, 1]  → [1., 1.]
b.assign_sub([0.5, 0.5])                # b -= [0.5, 0.5] → [0.5, 0.5]

# Non-trainable variable (e.g., step counter, BN running stats)
step = tf.Variable(0, trainable=False)
Variable vs constant — the gradient difference·python
v = tf.Variable(3.0)
c = tf.constant(3.0)

with tf.GradientTape() as tape:
    yv = v ** 2
    yc = c ** 2

print(tape.gradient(yv, v))   # 6.0  ← Variable auto-watched
print(tape.gradient(yc, c))   # None ← constant not watched

# To compute a gradient w.r.t. a constant, watch it explicitly:
with tf.GradientTape() as tape:
    tape.watch(c)
    y = c ** 2
print(tape.gradient(y, c))    # 6.0

Progress

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

댓글 0

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

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