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

Tensor Properties: Shape, Dtype, Rank, Device

~10 min · shape, dtype, device, introspection

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

The four checks you'll run a thousand times

Almost every TF debugging session begins with calling .shape and .dtype on whatever's confusing you. These properties don't run any computation — they're metadata, instant to read.

Shapes can contain None for dynamic dimensions. This is common in model input specs where batch size or sequence length isn't fixed at graph build time. Inside model.summary() output, (None, 224, 224, 3) means: any batch size, 224×224 RGB image.

The .device property shows where the tensor lives — CPU vs GPU. Calling .numpy() on a GPU tensor implicitly copies it to CPU first, which is fine for occasional inspection but expensive in tight loops.

Code

Tensor introspection·python
import tensorflow as tf

t = tf.constant([[1.0, 2.0, 3.0],
                 [4.0, 5.0, 6.0]])

print(t.shape)             # TensorShape([2, 3])
print(t.shape[0])          # 2
print(t.shape[-1])         # 3
print(t.shape.as_list())   # [2, 3] — Python list, useful for math

print(t.ndim)              # 2
print(t.dtype)             # <dtype: 'float32'>
print(tf.size(t))          # tf.Tensor(6, ...)
print(t.device)            # /job:localhost/.../device:CPU:0

arr = t.numpy()
print(type(arr), arr.shape)  # <class 'numpy.ndarray'> (2, 3)
Shape에 None이 들어가는 이유·python
# Inside a model summary you'll see (None, 224, 224, 3).
# None = dynamic dimension, decided at runtime.
# Frequently the batch dimension — same architecture, any batch size.

# When in doubt, force a fixed shape so error messages are louder
@tf.function(input_signature=[tf.TensorSpec(shape=[None, 784], dtype=tf.float32)])
def predict(x):
    return model(x)

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.