프로그래밍/Python

배열구조 바꾸기(numpy - reshape, pytorch - view/reshape)

히또아빠 2023. 12. 1. 17:21

 

원소의 수를 유지하면서 배열의 모양을 바꾸는 방법

1.[numpy - reshape]

array.reshape(변환 shape), np.reshape(array, 변환 shape)
재배정이 불가능한 경우 ValueError

arr = np.arange(1, 10)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
reshaped_arr = np.reshape(arr, (3, 3))

print("Original array:")
print(arr)
print("\nReshaped array:")
print(reshaped_arr)

Original array:
[1 2 3 4 5 6 7 8 9]

Reshaped array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

2.[pytorch - view, reshape]

np.reshpae와 동일, pytorch의 view와 reshape은 동일한 결과값.

tensor = torch.arange(1, 10)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
tensor2 = tensor.view(3, 3)

print("Original tensor:")
print(tensor)
print("\nViewed tensor:")
print(tensor2)

print("\nReshaped tensor:")
print(tensor2)

Original tensor:
tensor([1, 2, 3, 4, 5, 6, 7, 8, 9])

Viewed tensor:
tensor([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])

Reshaped tensor:
tensor([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])

3.pytorch view vs reshape 차이

동일한 변환 결과값을 내뱉는걸 위에서 확인했는데 무슨 차이가 있을까?

 

메모리 복사 (Memory Copy):

  • view: view는 가능한 경우 메모리를 복사하지 않고 원래 텐서와 같은 데이터를 참조한다. 따라서 view로 만든 새로운 텐서와 원본 텐서는 동일한 메모리를 공유하게 된다.
  • reshape: reshape는 가능한 경우 메모리를 복사하지 않는다. 그러나 reshape의 경우, 일부 경우에는 메모리 복사가 발생할 수 있습니다.

메모리 연속성 (Memory Contiguity):

  • view: view는 C-contiguous 배열에만 적용할 수 있다. 즉, 메모리에 연속적으로 저장되어 있는 경우에만 view를 사용할 수 있다.
  • reshape: reshape는 메모리 연속성에 크게 신경쓰지 않는다.

호환성:

  • view: view는 뷰의 크기가 원본과 호환
  • reshape: reshape도 마찬가지로 요소 수가 동일
300x250
반응형