Artificial Intelligence/πŸ“–

[정리] Numpy β‘  : shape, ndim, axis

geum 2022. 4. 19. 10:31

 

a = np.array([0, 1, 2, 3, 4, 5])

 

μ‹€μŠ΅μ„ μœ„ν•œ μž„μ˜μ˜ 배열을 μƒμ„±ν•˜κ³  이 λ°°μ—΄λ‘œ 이것저것 해보렀고 ν•œλ‹€.

 

shape/ndim/size

print("shape: ", a.shape) # μ˜ˆμƒ (6, 1)
print("ndim: ", a.ndim)   # μ˜ˆμƒ 2
print("size: ", a.size)   # μ˜ˆμƒ 6

 

β—» shape : (ν–‰, μ—΄)을 뒀집은 ν˜•νƒœλ‘œ λ‚˜νƒ€λƒ„ → (6, 1) = (1ν–‰, 6μ—΄)

β—» ndim : λ°°μ—΄ 차원

β—» size : λ°°μ—΄μ˜ μ›μ†Œ 개수

 

μ‹€ν–‰ κ²°κ³Ό

 

열이 ν•˜λ‚˜μΌ κ²½μš°λŠ” shapeμ—μ„œ 1이 μ°νžˆμ§€ μ•ŠλŠ”λ‹€λŠ” 것이 νŠΉμ§•! 아직도 차원 κ°œλ…μ΄ λ„ˆλ¬΄ μ–΄λ ΅λ‹€ γ… γ…  ν…μ„œ μ°¨μ›μ΄λž‘ κ°™κ²Œ μƒκ°ν•΄μ„œ μŠ€μΉΌλΌκ°€ 1차원, λ°°μ—΄μ΄λ‹ˆκΉŒ 2차원이라고 μƒκ°ν–ˆλŠ”λ° 1μ°¨μ›μ΄μ—ˆμŒ. κ·Έλƒ₯ 파이썬 μƒμ˜ λ°°μ—΄ κ°œλ…μ΄λž‘ λ˜‘κ°™μ•˜λ‹€.

 

shape 인덱싱

# print("shape[1]: ", a.shape[1]) IndexError
print("shape[0]: ", a.shape[0])
print("shape[-1]: ", a.shape[-1])

 

(6, 1)μ΄λ‹ˆκΉŒ shape[-1] ν•˜λ©΄ 1 λ‚˜μ˜€κ² μ§€ ν–ˆλŠ”λ° 또 μ‚¬λžŒμ˜ μ‹œμ„ μœΌλ‘œ 생각해버렸닀!^^ 행이 ν•˜λ‚˜μΌ λ•ŒλŠ” 1이 μ°νžˆμ§€ μ•ŠμœΌλ‹ˆκΉŒ νŠœν”Œ μš”μ†Œκ°€ ν•œ κ°œλΌμ„œ 인덱슀 0번 μ›μ†Œμ™€ 인덱슀 -1번 μ›μ†Œκ°€ λ™μΌν•˜λ‹€. 

 

μ‹€ν–‰ κ²°κ³Ό

 

reshape

a_reshape = a.reshape(3, 2)

print("reshape: ", a_reshape) # μ˜ˆμƒ
                              # [[0, 1, 2], [3, 4, 5]

 

β—» reshape : ν–‰λ ¬μ˜ 차원을 μ›ν•˜λŠ” λͺ¨μ–‘μœΌλ‘œ λ°”κΏ€ 수 있으며 인자 μˆœμ„œλŒ€λ‘œ ν–‰, 열이닀.

β—» reshape 방법 : κΈ°μ‘΄ λ°°μ—΄.reshape(ν–‰, μ—΄) / np.reshape(κΈ°μ‘΄ λ°°μ—΄, (ν–‰, μ—΄))

 

μ‹€ν–‰ κ²°κ³Ό

 

1ν–‰ 6μ—΄μ˜ 배열이 3ν–‰ 2μ—΄λ‘œ λ°”λ€Œμ—ˆλ‹€. μ˜ˆμƒ κ²°κ³ΌλŠ” reshape 검색해보고 적은 건데도 ν‹€λ¦Ό

 

axis

print("axis=0 sum: ", a_reshape.sum(axis=0)) # ν–‰
print("axis=1 sum: ", a_reshape.sum(axis=1)) # μ—΄

 

sum ν•¨μˆ˜ μΈμžκ°€ axis=0이면 ν–‰ λ°©ν–₯으둜 μš”μ†Œλ₯Ό ν•©ν•˜κ³  axis=1이면 μ—΄ λ°©ν–₯으둜 μš”μ†Œλ₯Ό ν•©ν•œλ‹€. 좕은 항상 배열보닀 μž‘μ€ 값을 κ°–λŠ”λ‹€(λ°°μ—΄ 3차원이면 axis μ΅œλŒ“κ°’μ€ 2).

 

μ‹€ν–‰ κ²°κ³Ό

 

expand_dims

expand_arr = np.array([1, 3])

# expand_dims: 차원 증가
expand_zero = np.expand_dims(expand_arr, axis=0) # [[1, 3]]
expand_one = np.expand_dims(expand_arr, axis=1)  # [[1], [3]]

print(f"expand_arr shape: {expand_arr.shape}, expand_arr ndim: {expand_arr.ndim}")
print("axis expand_dims=0: ", expand_zero)
print("axis expand_dims=1: ", expand_one)
print(f"expand_zero shape: {expand_zero.shape}, expand_zero ndim: {expand_zero.ndim}")
print(f"expand_one shape: {expand_one.shape}, expand_one ndim: {expand_one.ndim}")

 

λͺ¨λ₯Ό λ•ŒλŠ” μ—­μ‹œ μ°μ–΄λ³΄λŠ” 것이 κ°€μž₯ 쒋은 방법이라고 μƒκ°ν•œλ‹€. μœ„μ˜ μ½”λ“œλ₯Ό ν•˜λ‚˜μ”© ν’€μ–΄μ„œ 정리해보면!

 

- expand_arr : 1차원 λ°°μ—΄(ndim=1), shape (2, )

 

- expand_zero : axis=0μ΄λ―€λ‘œ 첫 번째 좕에 차원 μΆ”κ°€, 1ν–‰ 2μ—΄μ˜ 2차원 λ°°μ—΄

- expand_one : axis=1μ΄λ―€λ‘œ 두 번째 좕에 차원 μΆ”κ°€, 2ν–‰ 1μ—΄μ˜ 2차원 λ°°μ—΄

 

- expand_zero shape : 첫 번째 좕에 차원을 μΆ”κ°€ν–ˆμœΌλ―€λ‘œ (1, 2)

- expand_one shape : 두 번째 좕에 차원을 μΆ”κ°€ν–ˆμœΌλ―€λ‘œ (2, 1)

 

⭐ expand_dims의 μΆ• 차원 μΆ”κ°€ κ°œλ…μ€ 이 곳을 μ°Έκ³ ν–ˆλ‹€.

 

μ‹€ν–‰ κ²°κ³Ό