꺼내먹는지식 준

Torch Math Operations 본문

AI/PyTorch

Torch Math Operations

알 수 없는 사용자 2022. 1. 25. 21:05

Torch Math Operations

다음의 같은 항목으로 구성되어있다. 

 

1) Pointwise Ops 

2) Reduction Ops 

3) Comparison Ops 

4) Spectral Ops 

5) Other Operations 

6) BLAS and LAPACK Operations Utilities

 

1) Pointwise Ops 

말그대로 Point-wise 연산처리 관련 함수 

간단하게 3개만 살펴보자.

  • sigmoid
  • erf
  • trunc
A = torch.tensor([1,2,3,4,5,99])
torch.sigmoid(A)
#tensor([0.7311, 0.8808, 0.9526, 0.9820, 0.9933, 1.0000])

torch.erf(A)
#tensor([0.8427, 0.9953, 1.0000, 1.0000, 1.0000, 1.0000])

A = torch.tensor([1.111,2.234,3.3123,4.41234,5.123,99.123141])
torch.trunc(A)
#tensor([ 1.,  2.,  3.,  4.,  5., 99.])

sigmoid (0 ~ 1)

erf(): error rate를 계산하는 함수 

trunc: 소수점 이하 버리는 함수 

 

2) Reduction Ops 

조건에 따라 tensor에서 특정 값만을 가져오거나 연산을 통해서 크기를 줄이는 등 주어진 tensor의 크기를 줄인다. 

  • argmax
  • all
  • unique
  • dist
A = torch.tensor([1,2,3,4,5,-1], dtype = float)
B = torch.tensor([3,2,5,1,2,3], dtype = float)
print(torch.argmax(A))
print(torch.all(A))
print(torch.dist(A,B, 2.5))
print(torch.unique(B))

#tensor(4)
#tensor(True)
#tensor(5.6084, dtype=torch.float64)
#tensor([1., 2., 3., 5.], dtype=torch.float64)

argmax: 최대값 

all: tensor 모든 element 가 True 일 때 True else: False 다만, -1 은 True 처리된다. 

dist: A,B의 거리 비교 (int type 불가), p norm 

p norm:

$||x||_{p} = \sqrt[p]{\sum_{i}|x_{i}|^p}$

unique: 1개만 있는 값 return 

 

3) Comparison Ops

작은지 큰지 이런 비교와 관련된 기능을 포함하는 함수

3개만 살펴보자. 

  • ge (greater_equal)
  • argsort
  • isclose
B = torch.tensor([3,2,5,1,2,3], dtype = float)
A = torch.tensor([1,2,3,4,5,-1], dtype = float)

print(torch.ge(A,B))
print(torch.argsort(B))
print(torch.isclose(A,B))

#tensor([False,  True, False,  True,  True, False]) 
#tensor([3, 1, 4, 0, 5, 2]) 
#tensor([False,  True, False, False, False, False])

A,B element누가 더 큰지 비교 

B element 크 오름차순 순서대로 index 나열

A,B 각 element 거리가 가까운지 비교

 

4) Other Operations 

특정한 세부 항목으로 분류하기 힘든 함수

  • einsum
  • broadcast_tensors
  • cartesian_prod
  • diag
A = torch.tensor([1,2,3,4,5,-1], dtype = float)
B = torch.tensor([3,2,5,1,2,3], dtype = float)
C = torch.tensor([[1,2,3],[4,5,6],[7,8,9]])

print(torch.einsum('ii', C))
print(torch.einsum('ii->i', C))
print(torch.einsum('i,j->ij', A,B))


print((B).shape)
print(torch.broadcast_tensors(B))

print(torch.cartesian_prod(A,B))
print(torch.diag(A))

#tensor(15)
#tensor([1, 5, 9])
#tensor([[ 3.,  2.,  5.,  1.,  2.,  3.],
        [ 6.,  4., 10.,  2.,  4.,  6.],
        [ 9.,  6., 15.,  3.,  6.,  9.],
        [12.,  8., 20.,  4.,  8., 12.],
        [15., 10., 25.,  5., 10., 15.],
        [-3., -2., -5., -1., -2., -3.]], dtype=torch.float64)
        
#torch.Size([6])

#(tensor([3., 2., 5., 1., 2., 3.], dtype=torch.float64),)
#tensor([[ 1.,  3.],
        [ 1.,  2.],
        [ 1.,  5.],
        [ 1.,  1.],
        [ 1.,  2.],
        [ 1.,  3.],
        [ 2.,  3.],
        [ 2.,  2.],
        ....
        )

#tensor([[ 1.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  2.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  3.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  4.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  5.,  0.],
        [ 0.,  0.,  0.,  0.,  0., -1.]], dtype=torch.float64)

eisum: 연산을 통해 행렬, 벡터의 내적(Dot products), 외적(Outer products), 전치(Transpose), 행렬곱 등을 일관성있게 표현할 수 있다. 특히 "einsum"은 배치 단위의 텐서 계산에 유용하다. 

equation

1) operand의 각 index에 대응하는 소문자로 구성되는 식입니다. 

 

2)-> 기준 왼쪽

operands 의 차원을 연결하는 부분 

`,` 를 기준으로 구분됨

 

3)-> 기존 오른쪽

output의 차원 인덱스

생략되는 경우는 한번만 언급된 알파벳들을 순서대로 나열한 것으로 내부적으로 정의된다고 함.

 

4)예시

  • ni, ij -> nj
    • i가 index에 해당
    • $\sum_{i} A_{ni}B_{ij}$

#1 (0,0) (1,1) (2,2) 에 해당하는 1 + 5 + 9 = 15

#2 (0,0) (1,1) (2,2) 1, 5, 9 를 윈소 

#3 i,j -> ij $\sum A_{i}B_{j}$

 

broadcast_tensors

..

cartesian_prod: 집합 곱 

diag: 1차 vector 값을 가로로 하는 2차 행렬 생성 

 

5) BLAS and LAPACK Operations Utilities

BLAS : Basic Linear Algebra Subprograms 

LAPACK : Linear Algebra PACKage

선형대수학(Linear Algebra)와 연관 

  • eig
  • addmm
  • dot
A = torch.tensor([1,2,3,4,5,-1], dtype = float)
B = torch.tensor([3,2,5,1,2,3], dtype = float)
C = torch.randn(2,5)
D = torch.randn(5,3)
E = torch.randn(4,4)
F = torch.randn(2,3)

print(torch.eig(E))
print(torch.addmm(F,C,D))
print(torch.dot(A,B))

#torch.return_types.eig(
eigenvalues=tensor([[ 1.6187,  0.0000],
        [-1.1170,  1.9338],
        [-1.1170, -1.9338],
        [-0.5600,  0.0000]]),
eigenvectors=tensor([]))
#tensor([[-3.5913, -0.4459, -1.0044],
        [-0.2770,  3.6740, -1.2116]])
#tensor(33., dtype=torch.float64)

 

eig: square 의 eigen value vector 를 구함 

admm F + C mm D

dot 1D A $\cdot$ 1D B

 

 

'AI > PyTorch' 카테고리의 다른 글

Transfer Learning 듀토리얼 - (1) 모델 저장, checkpoint, 불러오기  (0) 2022.01.26
Pytorch nn.Module 총정리 / 모델 만드는 법  (0) 2022.01.25
Torch Tensors  (0) 2022.01.25
Torch Indexing  (0) 2022.01.25
Pytorch Dataset  (0) 2022.01.25
Comments