고급 Reshape - 3 차원 배열 생성
이제 3 차원 배열을 생성하여 더 고급적인 reshaping 으로 넘어가 보겠습니다. 3D 배열은 본질적으로 2D 배열의 배열이며, 볼륨, 이미지의 시계열 또는 기타 복잡한 데이터 구조를 나타내는 데 유용합니다.
numpy_reshape.py 파일에 다음 코드를 추가합니다.
import numpy as np
## Create a simple 1D array
original_array = np.arange(24)
print("Original 1D array:")
print(original_array)
print("Shape of the original array:", original_array.shape)
print("-" * 50) ## Separator line
## Reshape into a 3D array with dimensions 2x3x4
## This creates 2 blocks, each with 3 rows and 4 columns
reshaped_3d = np.reshape(original_array, (2, 3, 4))
print("Reshaped 3D array (2x3x4):")
print(reshaped_3d)
print("Shape of the 3D array:", reshaped_3d.shape)
print("Dimensions of the 3D array:", reshaped_3d.ndim)
print("-" * 50) ## Separator line
## Accessing elements in a 3D array
print("First block of the 3D array:")
print(reshaped_3d[0])
print("\nSecond block of the 3D array:")
print(reshaped_3d[1])
print("\nElement at position [1,2,3] (second block, third row, fourth column):")
print(reshaped_3d[1, 2, 3])
스크립트를 다시 실행합니다.
python3 numpy_reshape.py
출력은 24 개의 요소가 있는 1D 배열이 어떻게 3D 구조로 변환될 수 있는지 보여줍니다. 이 구조는 2 개의 블록으로 시각화할 수 있으며, 각 블록은 3×4 행렬을 포함합니다.
3D 배열 이해:
- 첫 번째 차원 (2) 은 "블록" 또는 "레이어"의 수를 나타냅니다.
- 두 번째 차원 (3) 은 각 블록의 행 수를 나타냅니다.
- 세 번째 차원 (4) 은 각 행의 열 수를 나타냅니다.
이 구조는 이미지 처리 (각 "블록"이 색상 채널일 수 있음), 시계열 데이터 (각 "블록"이 시간 포인트일 수 있음) 또는 여러 행렬이 필요한 기타 시나리오에 특히 유용합니다.