1.Tensor의 인덱싱과 슬라이싱
1.1 Tensor의 indexing & slicing
⇒ Numpy와 인덱싱, 슬라이싱 방법 유사
- Indexing : Tensor 특정 위치의 요소에 접근하는 것
- Slicing : 부분집합을 선택하여 새로운 Sub Tensor 생성
2. Tensor의 모양 변경1
2.1 view 메서드를 활용한 Tensor의 모양 변경
- Tensor의 메모리가 연속적으로 할당된 경우에만 사용 가능
-
연속성(contiguous) : Tensor 내 배열된 요소들의 메모리 주소가 연속적인 경우 ⇒하지만 임의의 Tensor를 슬라이싱 한다면, 연속성은 깨짐 ex) Tensor c를 슬라이싱한 Tensor d는 contiguous 속성이 깨짐 : d = c[ : , :2]
-
임의 Tensor의 메모리가 연속적으로 할당되었는지 확인하는 메서드 → c.is_contiguous() (결과: boolean)
-
비연속적인 Tensor를 연속적으로 할당하는 메서드 → c.contiguous()
-
view메서드를 활용한 Tensor 모양 변경- 원본과 동일한 데이터 가리킴 → 모양 등의 Meta 정보만 변경
f = torch.arange(12)- (2-D) → g = f.view(4, 3) or view(4, -1)
- (3-D) → h = f.view(3, 2, 2) or view(3, 2, -1)
2.2 flatten 함수를 활용한 Tensor의 평탄화
flatten메서드- 다차원 데이터 처리에 유용
- 데이터를 신경망 모델에 적합한 형태로 전처리
- 1-D Tensor로 평탄화
i = torch.randn(3, 3)⇒j = torch.flatten(i)⇒j = i.flatten()
- 특정 차원 범위를 평탄화
- k = torch.randn(3, 2, 2)
-
0번째 차원부터 마지막 차원까지 : I = torch.flatten(k, 0) (I.shpae() = (12,) - 1-D)
-
1번째 차원부터 마지막 차원까지 : I = torch.flatten(k, 1) (I.shape() = (3, 4) - 2-D)
-
0번째 차원부터 1번째 차원까지 : I = torch.flatten(k, 0, 1) (I.shape() = (6, 2) - 2-D)
2.3 reshape 메서드를 활용한 Tensor의 모양변경
- view 메서드와 기능은 동일, 메모리가 연속적이지 않아도 사용 가능
- 장점 : 안전하고 유연성 좋음
- 단점 : 성능 저하 (연속적이지 않은 Tensor → 아예 새로운 복사본을 할당)
- n = torch.arange(12)의 1-D Tensor 생성 시,
- 1-D → 2-D
- o = n.reshape(4, 3)
- o = n.reshape(4, -1)
- 1-D → 3-D
- p = n.reshape(3, 2, 2)
- p = n.reshape(3, 2, -1)
- 1-D → 2-D
2.4 transpose() 메서드를 활용한 Tensor의 모양 변경
- transpose() : 특정 두 차원의 축을 서로 바꿔줌
-
2-D Tensor q의 0차원과 1차원의 축 바꾸기 ⇒ r = q.transpose(0, 1)
-
3-D Tensor s의 1차원과 2차원의 축 바꾸기 ⇒ t = s.transpose(1, 2)
-
2.5 squeeze 함수를 활용한 Tensor의 차원 축소
- squeeze() : 1의 값을 갖는(dim = 1) 모든 차원을 축소
-
dim = 1인 차원들을 축소 → v = torch.squeeze(u)
-
Tensor w의 특정 차원을 축소하는 코드 → x = torch.squeeze(w, dim = 0) or torch.squeeze(w, dim = 1)
-
dim = 1인 모든 차원 축소 → t = torch.squeeze(t)
-
2.6 unsqueeze 함수를 활용한 Tensor의 차원 확장
- y = torch.randn(3, 4)의 2-D Tensor 생성
-
y의 0차원에서 dim=1을 갖도록 차원 확장 → z = torch.unsqueeze(y, dim = 0)
-
y의 1차원에서 dim=1을 갖도록 차원 확장 → z = torch.unsqueeze(y, dim = 1) (row 차원(3)은 depth 차원으로 이동 : (3, 1, 4))
-
y의 2차원에서 dim=1을 갖도록 차원 확장 → z = torch.unsqueeze(y, dim = 2) (row(3), column(4)차원은 각각 depth, row 차원으로 이동 : (3, 4, 1))
-
2.7 stack 함수를 활용한 Tensor들 간의 결합
- 3개의 2-D Tensor 결합
- red_channel = torch.tensor([[255, 0], [0, 255]])
- green_channel = torch.tensor([[0, 255], [0, 255]])
- blue_channel = torch.tensor([[0, 0], [255, 0]])
-
dim = 0 축으로 결합 → a = torch.stack((red_channel, green_channel, blue_chaneel), dim = 0) (dim = 0이 디폴트라 생략 가능)

-
dim = 1 축으로 결합 → a = torch.stack((red_channel, green_channel, blue_chaneel), dim = 1)

-
dim = 2 축으로 결합 → a = torch.stack((red_channel, green_channel, blue_chaneel), dim = 2)

-
chat_bubble 댓글남기기
댓글남기기