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

Eager 실행과 NumPy 호환

~10 min · eager, numpy, interop

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

왜 지금의 TF가 NumPy처럼 느껴지는지

TF 2.x는 default로 eagerly 실행해 — 모든 op이 즉시 돌고 concrete tensor 반환, .numpy()로 들여다볼 수 있어. graph 컴파일러가 아니라 그냥 Python처럼 느껴지는 이유.

NumPy 호환은 양방향 매끄러워. TF op는 NumPy array를 암묵적으로 받고, TF tensor는 NumPy __array__ 프로토콜 구현해서 변환 없이 NumPy 함수에 그대로 들어가. 명시적 변환은 tf.convert_to_tensor.numpy().

.numpy() 예외: .numpy() 메서드는 eager mode에서만 작동. @tf.function 안에선 tensor가 symbolic이라 trace 시점에 concrete value 없고 .numpy()는 에러. tf.print() 써.

Code

Eager + NumPy round-trip·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.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

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

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