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

흔한 shape 에러와 디버깅

~13 min · debugging, shape-error, broadcasting

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

가장 자주 보게 될 에러 메시지

세 가지 TF 에러가 디버깅 시간의 80%를 잡아먹어. 보자마자 알아보면 시간 엄청 줄어.

에러 1: matmul shape 불일치. tf.matmul(a, b)a.shape[-1] == b.shape[-2] 필수. 보통 한쪽에 tf.transpose 걸면 해결. 짧게 tf.matmul(a, b, transpose_b=True)로 중간 tensor 안 만들고 처리.

에러 2: batch 차원 까먹음. (batch, ...)로 훈련된 model은 (...) 단일 샘플에 막혀. tf.expand_dims(x, axis=0) 또는 x[tf.newaxis]로 해결.

에러 3: dtype mismatch. NumPy는 default가 float64, TF는 float32 기대. 경계에서 캐스팅: tf.cast(np_array, tf.float32). PNG/JPEG 불러와서 uint8 0–255를 float32 0–1로 normalize 까먹는 image pipeline에서 가장 흔한 silent 버그가 이거.

Code

Debugging helper·python
import tensorflow as tf

def debug_tensor(t, name="tensor"):
    print(f"{name}: shape={t.shape}, dtype={t.dtype}")
    if t.shape.rank is not None and tf.size(t) <= 20:
        print(f"  values: {t.numpy()}")

x = tf.random.normal([32, 28, 28, 1])
debug_tensor(x, "raw input")

x_flat = tf.reshape(x, [32, -1])
debug_tensor(x_flat, "after flatten")
Cast pattern — uint8 image to float32 0-1·python
import tensorflow as tf
import numpy as np

# Common pipeline bug: NumPy float64 image into TF float32 model
np_data = np.random.randn(100, 10)         # float64 by default
tf_data = tf.cast(tf.constant(np_data), tf.float32)

# uint8 image → float32 0-1
raw = tf.constant([255, 128, 0], dtype=tf.uint8)
norm = tf.cast(raw, tf.float32) / 255.0    # [1.0, 0.502, 0.0]

Exercise

(32, 28, 28, 1) shape의 tensor를 (MNIST batch). 답 보지 말고: (a) uint8 0-255를 float32 0-1로 normalize, (b) Dense 입력용으로 (32, 784)로 flatten, (c) shape (784, 10)인 weight tensor에 matmul. 출력이 (32, 10)인지 확인.

Progress

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

댓글 0

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

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