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

Eager Execution and NumPy Interop

~10 min · eager, numpy, interop

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

Why TF feels like NumPy now

TF 2.x runs eagerly by default — every op executes immediately, returns a concrete tensor, and you can introspect it with .numpy(). This is what makes it feel like Python instead of a graph compiler.

NumPy interop is seamless in both directions. TF ops accept NumPy arrays implicitly, and TF tensors implement the NumPy __array__ protocol so they slot into NumPy functions without conversion. tf.convert_to_tensor and .numpy() are the explicit conversion functions when you want them.

The .numpy() exception: The .numpy() method works only in eager mode. Inside a @tf.function-decorated function, tensors are symbolic — they have no concrete value at trace time, and .numpy() raises. Use tf.print() instead.

Code

Eager + NumPy 양방향·python
import tensorflow as tf
import numpy as np

a = tf.constant([1, 2, 3])
b = tf.constant([4, 5, 6])
c = a + b
print(c)            # tf.Tensor([5 7 9], shape=(3,), dtype=int32)
print(c.numpy())    # [5 7 9]

# NumPy → TF (implicit)
np_arr = np.array([[1.0, 2.0], [3.0, 4.0]])
tf_sum = tf.reduce_sum(np_arr)

# TF → NumPy (implicit via __array__)
tf_t = tf.constant([1.0, 2.0, 3.0])
print(np.mean(tf_t))    # 2.0

# Explicit conversions when you need them
arr = tf_t.numpy()
back = tf.convert_to_tensor(arr)

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.