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

Tensor 만들기: constant, zeros, ones, random

~12 min · create, init, random, constant

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

매일 쓸 factory 함수들

TF의 생성자 세트는 작지만 완전해. 어떤 걸 언제 꺼낼지 알면 코드도 줄고 버그도 줄어.

tf.constant는 Python 값/list/NumPy array에서 immutable tensor 만들어. tf.zeros, tf.ones, tf.fill은 초기화용 고정값 tensor. tf.eye는 단위행렬, tf.range는 Python range처럼 시퀀스. *_like 변형들 — tf.zeros_like, tf.ones_like — 은 다른 tensor의 shape/dtype을 따라가서 한 카테고리의 버그를 통째로 막아줘.

weight 초기화엔 거의 항상 tf.random.normal보다 tf.random.truncated_normal이 답이야. truncated 버전은 평균에서 2σ 넘어가는 outlier를 잘라내서 초반 gradient 불안정을 막으면서 평균은 안 흔들어.

재현성: 결정론적이어야 하는 스크립트는 맨 위에 tf.random.set_seed(42). graph mode (@tf.function)에서 재현성 필요하면 tf.random.stateless_normal에 명시적 seed=[a, b] — 글로벌 state는 컴파일된 graph 안에선 불안정해.

Code

constant — from various sources·python
import tensorflow as tf
import numpy as np

a = tf.constant(4)                        # int32 scalar
b = tf.constant(4.0)                      # float32 scalar
mat = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)

arr = np.array([1.0, 2.0, 3.0])
t = tf.constant(arr)                      # float64 (matches numpy default)

s = tf.constant("Hello, TensorFlow!")
s_vec = tf.constant(["cat", "dog", "bird"])
zeros / ones / fill / eye / range·python
z = tf.zeros([3, 4])                      # float32 zeros
o = tf.ones([2, 5])
f = tf.fill([3, 3], 7.0)                  # all 7.0
eye = tf.eye(4)                            # 4x4 identity
r = tf.range(1, 10, delta=2)              # [1, 3, 5, 7, 9]

# Match another tensor's shape + dtype
z_like = tf.zeros_like(mat)
o_like = tf.ones_like(mat)
Random — patterns for weight init·python
tf.random.set_seed(42)

# Standard normal — okay but can produce big outliers
n = tf.random.normal(shape=[3, 4], mean=0.0, stddev=1.0)

# Truncated normal — clips beyond 2σ. Preferred for layer weights.
tn = tf.random.truncated_normal([3, 3], mean=0.0, stddev=0.1)

# Uniform — good for biases or scaled init
u = tf.random.uniform(shape=[3, 3], minval=0.0, maxval=1.0)

# Stateless: reproducible inside @tf.function
n2 = tf.random.stateless_normal(shape=[3, 3], seed=[1, 2])

External links

Progress

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

댓글 0

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

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