reshape할 때 값이 -1인 경우

chanykim·2022년 7월 4일
0

목적

딥러닝에서 텐서의 차원을 바꿀 때 -1을 사용하는 경우가 있습니다.
행,열에 -1이 들어갈 때 어떻게 변하는지 나타내보겠습니다.
우선 아래와 같이 예제를 준비합니다.

import numpy as np

x = np.arange(12).reshape(3, 4)
print(x.shape)
print(x)

(3, 4)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

그냥 -1일 경우

(-1) => (12, )

x = np.arange(12).reshape(-1, 1)
print(x.shape)
print(x)

(12,)
[ 0  1  2  3  4  5  6  7  8  9 10 11]

1차원 배열을 반환합니다.

행에 -1일 경우

(-1, 1) => (12, 1)

x = np.arange(12).reshape(-1, 1)
print(x.shape)
print(x)

(12, 1)
[[ 0]
 [ 1]
 [ 2]
 [ 3]
 [ 4]
 [ 5]
 [ 6]
 [ 7]
 [ 8]
 [ 9]
 [10]
 [11]]

(-1, 2) => (6, 2)

x = np.arange(12).reshape(-1, 2)
print(x.shape)
print(x)

(6, 2)
[[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]]

(-1, 3) => (4, 3)

x = np.arange(12).reshape(-1, 3)
print(x.shape)
print(x)

(4, 3)
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

(-1, 4) => (3, 4)

x = np.arange(12).reshape(-1, 4)
print(x.shape)
print(x)

(3, 4)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

전체가 배열이 12기 때문에 가령 -1, 3일 때 ?x3=12가 되려면 어떤 숫자인지 확인하면 4니까 reshape(-1, 3)은 (4,3)과 같아집니다.

열에 -1일 경우

(1, -1) => (1, 12)

x = np.arange(12).reshape(1, -1)
print(x.shape)
print(x)

(1, 12)
[[ 0  1  2  3  4  5  6  7  8  9 10 11]]

(2, -1) => (2, 6)

x = np.arange(12).reshape(2, -1)
print(x.shape)
print(x)

(2, 6)
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]]

(3, -1) => (3, 4)

x = np.arange(12).reshape(3, -1)
print(x.shape)
print(x)

(3, 4)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

(4, -1) => (4, 3)

x = np.arange(12).reshape(4, -1)
print(x.shape)
print(x)

(4, 3)
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

행과 동일하게 작동합니다.

profile
오늘보다 더 나은 내일

0개의 댓글