연속적으로 할당된 경우에 사용 가능-1 argument를 사용하면 자동으로 값을 계산해주기 때문에 유용### Example ###
t = torch.arange(12) # tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
v = t.view(4, -1) # tensor([[0, 1, 2],[3, 4, 5],[6, 7, 8],[9, 10, 11]])
슬라이싱으로 2D Tensor의 Sub-Tensor를 생성하면 연속성이 깨짐
### Example ###
t = torch.tensor([[0, 1, 2], [3, 4, 5]])
s = t[:, :2] # tensor([[0, 1], [3, 4]])
# 메모리가 연속적인지 비연속인지 확인
t.is_contiguous() # True
s.is_contiguous() # False
# 연속적이 되도록 변환 (view method 활용 가능)
s.contiguous()
s.is_contiguous() # True
### Example ###
torch.flatten()
t = torch.arange(12) # tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
v = t.view(4, -1) # tensor([[0, 1, 2],[3, 4, 5],[6, 7, 8],[9, 10, 11]])
f = t.flatten()
view()와 차이점
view()와 달리 메모리가 연속적이지 않아도 사용 가능
- 장점 : 안전하고 유연성이 좋음
- 단점 : 성능 저하
✨ 메모리의 연속성이 확실하고 성능이 중요하면view()를 사용하는 것이 좋음
### Example ###
t = torch.arange(12) # tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
v = t.reshape(4, -1) # tensor([[0, 1, 2],[3, 4, 5],[6, 7, 8],[9, 10, 11]])
### Example ###
t = torch.tensor([[0, 1, 2],[3, 4, 5]])
t.transpose(0, 1) # tensor([[0, 3], [1, 4], [2, 5]])
### Example ###
# dim=1이 1개일 때
t = torch.randn(1, 3, 4)
s = torch.squeeze(u)
s.shape # torch.Size([3, 4])
# dim=1이 여러 개일 때
t = torch.randn(1, 1, 4)
s = torch.squeeze(u)
s.shape # torch.Size([4])
# 특정 차원만 squeeze 적용
s1 = torch.squeeze(u, dim=1)
s1.shape # torch.Size([1, 4])
### Example ###
t = torch.randn(2, 3)
# unsqueeze 적용
s0 = torch.unsqueeze(u, dim=0)
s0.shape # torch.Size([1, 2, 3])
s1 = torch.unsqueeze(u, dim=1)
s1.shape # torch.Size([2, 1, 3])
s2 = torch.unsqueeze(u, dim=2)
s2.shape # torch.Size([2, 3, 1])
### Example ###
red = torgh.tensor([[255, 0], [0, 255]]
green = torgh.tensor([[0, 255], [0, 255]]
blue = torgh.tensor([[0, 0], [255, 0]]
# dim=0 생략, 0차원 축(depth 축)을 생성해서 결합
# red가 전면, red-green-blue 순으로 2D Tensor를 쌓음
rgb = torch.stack((red, green, blue))
rgb.shape(rgb.shape) # torch.Size([3, 2, 2])
# 1차원 축(행 축)을 생성해서 3개의 2D Tensor 결합
# red가 윗면, 전면에 rr(1층)-gg(2층)-bb(3층)가 오는 형태
rgb1 = torch.stack((red, green, blue), dim=1)
rgb1.shape(rgb.shape) # torch.Size([2, 3, 2])
# 2차원 축(열 축)을 생성해서 3개의 2D Tensor 결합
# red가 왼쪽 측면, 전면에 rgb(1층) - rgb(2층) 오는 형태
rgb2 = torch.stack((red, green, blue), dim=2)
rgb2.shape(rgb.shape) # torch.Size([2, 2, 3])
stack() 함수와 다르게 기존의 차원을 유지하며 Tensor 연결### Example ###
t1 = torch.tensor([[0, 1], [2, 3]])
t2 = torch.tensor([[4, 5]]) # 같은 차원이어야 함
cat_t = torch.cat((t1, t2))
cat_t.shape # torch.Size([3, 3])
# 다른 차원으로 붙이기
torch.cat((t1, t2), 1) # Error 발생 // 2행-1행으로 차원이 다르기 때문
# reshape
torch.cat((t1, t2.reshape(2, 1)), 1)
1 이어야 함### Example ###
t = torch.tensor([0, 1]) # 1행 2열
t.expand(3, 2) # 3행 2열, [[0, 1], [0, 1], [0, 1]]
expand() 와 다르게 크기가 1인 차원이 있어야 한다는 제약이 없음### Example ###
t = torch.tensor([0, 1], [2, 3]) # 2행 2열
t.repeat(2, 3) # 행 방향으로 2배, 열 방향으로 3배 확장 됨