unsqueeze( ) : PyTorch에서 차원(dimension)을 하나 늘려주는 함수
shape에 크기 1짜리 축을 추가
=> Deeplearning에서 주로 batch 차원을 만들 때 사용함 !! (broadcasting)
=> broadcasting : 차원 늘려서 연산 맞추기
ex) 3x224x224 (C, H, W) -> 1x3x224x224 (B, C, H, W)
- unsqueeze( ) : 차원을 추가 (size=1)
- squeeze( ) : 차원을 제거 (size=1인 차원만 삭제 가능)
import torch
x = torch.tensor([1, 2, 3, 4]) # shape: (4,)
y = x.unsqueeze(0) # shape: (1, 4)
z = x.unsqueeze(1) # shape: (4, 1)
- unsqueeze(0) : 맨 앞에 차원 추가
- unsqueeze(1) : 두 번째 차원 추가
- unsqueeze(-1) : 맨 뒤에 차원 추가
reshape( ) & view( ) - 원하는 형태로 변경하기
- reshape( ) : 새로운 shape로 변환
- view( ) : memory 연속성이 있을 때만 가능 (더 빠름)
x = torch.arange(12) # shape (12,)
y = x.reshape(3, 4) # shape (3,4)
z = x.view(2, 6) # shape (2,6)
print(y)
print(z)
* memory 연속적(contiguous) / 비연속적(non-contiguous)
- 연속적 : data가 memory에 행렬 순서대로 이어져 있음
- 비연속적 : stride(간격)만 꼬여 있고 memory 순서가 불규칙
import torch
x = torch.arange(6).reshape(2, 3)
print(x)
# tensor([[0, 1, 2],
# [3, 4, 5]])
실제 메모리에는 [0, 1, 2, 3, 4, 5] 순서대로 저장됨
stride = (3, 1) : 행으로 3칸, 열로 1칸 이동
x는 memory 연속적 상태 !!
y = x.t() # 전치
print(y)
# tensor([[0, 3],
# [1, 4],
# [2, 5]])
print(y.is_contiguous()) # False
y는 memory에서 행 단위로 맞지 않게 저장된 상태 = 비연속적 상태
permute( ) & transpose( ) - 차원 위치 바꾸기
- permute(order) : 모든 차원의 순서를 한 번에 지정해서 교환
- transpose(dim1, dim2) : 두 차원만 교환
x = torch.randn(2, 3, 4) # shape (2,3,4)
# permute
y = x.permute(1, 0, 2) # shape (3,2,4)
# transpose
z = x.transpose(1, 2) # shape (2,4,3)
expand( ) & repeat( ) - 차원 늘려서 복사 또는 참조 확장
- expand( ) : 데이터를 복사하지 않고 memory 참조만 늘림 - 실제 값은 복제되지 않음 !!! (읽기 전용..)
x = torch.tensor([1, 2, 3]) # shape (3,)
y = x.unsqueeze(0).expand(4, 3)
print(y)
# [[1,2,3],
# [1,2,3],
# [1,2,3],
# [1,2,3]]
- repeat( ) : 데이터를 실제로 복사해서 확장 (memory 많이 차지 가능)
x = torch.tensor([1, 2, 3])
y = x.repeat(4, 1)
print(y)
# [[1,2,3],
# [1,2,3],
# [1,2,3],
# [1,2,3]]