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

Indexing, Slicing, Reshaping

~12 min · indexing, slicing, reshape, expand-dims

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

shape 사이를 정신줄 안 놓고 옮겨다니기

TF는 NumPy 스타일 indexing/slicing 그대로 지원해. TF가 갈라지는 건 전용 reshape op들 — tf.reshape, tf.expand_dims, tf.squeeze, tf.transpose — 인데 layer 사이를 데이터 옮기느라 매일 쓰게 돼.

Batch 차원 트릭: 대부분 TF op는 맨 앞에 batch 차원 기대해. 단일 224×224 RGB 이미지가 (224, 224, 3)이라면 model에 넣기 전에 (1, 224, 224, 3)로 만들어야 해. 같은 두 방법: tf.expand_dims(image, axis=0) 아니면 image[tf.newaxis, ...].

-1 트릭: tf.reshape(x, [-1])은 어떤 tensor든 1D로 평탄화. tf.reshape(x, [batch, -1])은 batch 빼고 다 평탄화 — Dense layer 바로 직전에 유용해.

Code

Indexing + slicing·python
import tensorflow as tf

t = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(t[0, 0])      # 1
print(t[1])         # [4 5 6]
print(t[0:2, 1:])   # [[2,3],[5,6]]
print(t[:, -1])     # [3, 6, 9]
print(t[::2, ::2])  # [[1,3],[7,9]]

# Index-based selection
indices = tf.constant([0, 2])
selected = tf.gather(t, indices)   # rows 0 and 2
Reshape / expand_dims / squeeze / transpose·python
x = tf.constant([[1.0, 2.0, 3.0],
                 [4.0, 5.0, 6.0]])     # shape (2, 3)

flat = tf.reshape(x, [6])              # (6,)
auto = tf.reshape(x, [-1])             # (6,) — auto-flatten
auto2 = tf.reshape(x, [3, -1])         # (3, 2)

y = tf.constant([1.0, 2.0, 3.0])       # (3,)
y_batch = y[tf.newaxis, :]             # (1, 3)
y_col = tf.expand_dims(y, axis=1)      # (3, 1)

z = tf.zeros([1, 3, 1])                # (1, 3, 1)
sq = tf.squeeze(z)                     # (3,)

m = tf.ones([2, 3, 4])
mt = tf.transpose(m, perm=[0, 2, 1])   # (2, 4, 3)
mt2 = tf.transpose(m)                  # reverse all → (4, 3, 2)

Progress

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

댓글 0

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

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