Search

Pytorch

Torch 기본

연산 - cat

torch.tensor([1,2,3]) torch.tensor([[1,2,3],[4,5,6]]) torch.cat(dim=0) ## 0차원 방향 -> 2차원 기준으로 row, data 증가 torch.cat(dim=1) ## 1차원 방향 -> 2차원 기준으로 column, feature가 증가 import torch a_tensor = torch.tensor([[1, 2, 3, 4]]) b_tensor = torch.tensor([[5, 6, 7, 8]]) print(a_tensor.shape) # torch.Size([1, 4]) print(b_tensor.shape) # torch.Size([1, 4]) a_b_tensor = torch.cat([a_tensor, b_tensor], dim=1) print(a_b_tensor) # tensor([[1, 2, 3, 4, 5, 6, 7, 8]]) print(a_b_tensor.shape) # torch.Size([1, 8]) ## 같은 걸로 torch.vstack((x,y)), torch.row_stack((x,y))가 있고 ## 같은 걸로 torch.hstack((x,y)), torch.column_stack((x,y))
Python
복사

연산 - stack

### stack -> 새로운 차원을 추가해서 두 개의 텐서를 합침. ### 어디에 새로운 차원을 추가할 것이냐 x = torch.arange(12).reshape(3, 4) y = torch.arange(12, 24).reshape(3, 4) print(x) # tensor([[ 0, 1, 2, 3], # [ 4, 5, 6, 7], # [ 8, 9, 10, 11]]) print(y) # tensor([[12, 13, 14, 15], # [16, 17, 18, 19], # [20, 21, 22, 23]]) torch.stack((x,y), dim=0) # tensor([[[ 0, 1, 2, 3], # [ 4, 5, 6, 7], # [ 8, 9, 10, 11]], # [[12, 13, 14, 15], # [16, 17, 18, 19], # [20, 21, 22, 23]]]) ## new dimension torch.stack(x,y),dim=0).shape # torch.size([2,3,4]) torch.stack((x,y),dim=1) # tensor([[[ 0, 1, 2, 3], # [12, 13, 14, 15]], # [[ 4, 5, 6, 7], # [16, 17, 18, 19]], # [[ 8, 9, 10, 11], # [20, 21, 22, 23]]]) ## new dimension torch.stack((x, y), dim=1).shape # torch.Size([3, 2, 4])
Python
복사

연산 - softmax

a = torch.tensor([1.0, 2.0, 3.0]) # 입력 텐서 softmax_output = torch.softmax(a, dim=0) # dim=0으로 소프트맥스 계산 print(softmax_output) # 출력: tensor([0.0900, 0.2447, 0.6652])
Python
복사

연산 - 인플레이스

import torch # 인플레이스 연산 예제 a = torch.tensor([1, 2, 3]) b = a a.add_(torch.tensor([1, 1, 1])) print(a) print(b)
Python
복사
add_
sub_
mul_
div_
pow_
sqrt_ 등등 가능

연산 - autograd

### detach(), no_grad(), requires_grad=False 이 세 가지가 있음 detach() -> 흐르는 연산을 막는다. static tensor로 만드는 것임 no_grad -> 블록 안의 gradient가 계산되지 않는다 requires_grad=False -> 파라미터를 상수 취급해서 업데이트되지 않음
Python
복사

연산 - matmul, mul

matmul → 행렬 곱
mul, * ⇒ elementwise 연산 w/broadcasting

연산 - view, squeeze, unsqueeze

# squeeze를 사용하면 알아서 1인 차원이 날라감. ft = torch.FloatTensor([[0],[1],[2]]) print(f) print(ft.shape) ## torch.Size([3,1]) print(ft.squeeze())## tensor([0,1,2]) print(ft.squeeze().shape) ## torch.Size([3]) ## unsqueeze를 사용하면 원하는 dimension에 1을 넣어줌
Python
복사

연산 - scatter

torch.scatter(dim, index, src) matrix.scatter(dim, index, value) matrix에서 dim 방향으로 index 위치에 value를 채워넣는다!
Python
복사

sparse - torch.coo

dense_matrix와 sparse_matrix 간 곱셈도 지원을 함.

torch.coalesce()

중복된 위치의 희소행렬을 합치는 것
# 중복된 인덱스가 있는 희소 텐서 생성 indices = torch.tensor([[0, 0, 1], [1, 1, 2]]) values = torch.tensor([1.0, 2.0, 3.0]) sparse_tensor = torch.sparse_coo_tensor(indices, values, (3, 3)) # coalesce 호출 coalesced_tensor = sparse_tensor.coalesce() print(coalesced_tensor) ### 출력 tensor(indices=tensor([[0, 1], [1, 2]]), values=tensor([3., 3.]), size=(3, 3), nnz=2, layout=torch.sparse_coo)
Python
복사

함수들 - cross_entropy

## Low Level z = torch.rand(3,5, requires_grad=True) hypothesis = F.softmax(z,dim=1) print(hypothesis) y = torch.randint(5,(3,)).long() print(y) y_one_hot = torch.zeros_like(hypothesis) y_one_hot.scatter(1,y.unsqueeze(1),1) cost = (y_one_hot * -torch.log(hypothesis)).sum(dim=1).mean() # cross-entropy loss print(cost) ## Low level (y_one_hot * -torch.log(F.softmax(z,di=1))).sum(dim=1).mean() ## high level -> y를 one_hot으로 만들 필요 없음 F.nll_loss(F.log_softmax(z,dim=1),y) ## high level -> y를 one_hot으로 만들 필요 없음 F.cross_entropy(z,y)
Python
복사