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

Creating Tensors: 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

The factory functions you'll use every day

TF gives you a small but complete set of constructors. Knowing which to reach for saves both code and bugs.

tf.constant creates an immutable tensor from any Python value, list, or NumPy array. tf.zeros, tf.ones, tf.fill create tensors of fixed values for initialization. tf.eye gives you an identity matrix. tf.range gives you a sequence (like Python's range). The *_like variants — tf.zeros_like, tf.ones_like — match another tensor's shape and dtype, which prevents an entire category of bugs.

For weight initialization, you almost always want tf.random.truncated_normal rather than tf.random.normal — the truncated version clips outliers beyond 2σ, which prevents unstable initial gradients without biasing the mean.

Reproducibility: Use tf.random.set_seed(42) at the top of any script you want to be deterministic. For graph-mode reproducibility (under @tf.function), use tf.random.stateless_normal with an explicit seed=[a, b] argument — global state is unreliable inside compiled graphs.

Code

constant — 다양한 source에서·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 — 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.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.