AI Tech

What is Pytroch (2)?

cpnubplzhelp 2024. 8. 6. 14:44

Tensor Operators

산술 연산

https://pytorch.org/docs/stable/name_inference.html

 

Named Tensors operator coverage — PyTorch 2.4 documentation

Shortcuts

pytorch.org

Tensor.add(), torch.add()

 

torch.add — PyTorch 2.4 documentation

Shortcuts

pytorch.org

Tensor.sub(), torch.sub()

 

torch.sub — PyTorch 2.4 documentation

Shortcuts

pytorch.org

 

 

 

Tensor.mul(), torch.mul()

 

torch.mul — PyTorch 2.4 documentation

Shortcuts

pytorch.org

 

Tensor.div(), torch.div()

 

torch.div — PyTorch 2.4 documentation

Shortcuts

pytorch.org

 

다양한 operator가 존재하며, 서로 다른 크기의 Tensor을 연산하게 되면, 자동으로 Broadcasting이 일어나서 계산을 진행하게 된다.

Tensor.add_(), sub_(), mul_(), div_()등 "_"이 존재하는 함수들은 in-place 연산으로 진행된다.

 

In-Place 연산을 진행하게 될경우 메모리를 효율적으로 사용할 수 있고, 성능을 최적화 할 수 있으나,

단점으로는 계산 그래프가 변동되며, 데이터의 손상에 위험이 있으며, 디버깅이 어려워진다는 점이 있다.

 

비교연산

원소간의 비교연산

eq : equal

ne : not equal

ge : greater than or equal

gt : greater than

le : less than or equal

lt: less than

torch.eq(input, other, *, out=None)
torch.ne(input, other, *, out=None)

매개변수
# input (Tensor): 비교할 첫 번째 Tensor.
# other (Tensor or Number): 비교할 두 번째 Tensor 또는 숫자. input과 other는 같은 크기여야 하며, 또는 input Tensor와 브로드캐스팅이 가능해야 합니다.
# out (Tensor, optional): 결과를 저장할 Tensor (선택적 인자). 기본값은 None입니다.

반환 값
# Tensor: input과 other의 요소가 같은지 비교한 결과를 담고 있는 Boolean Tensor.
a = torch.eq(torch.tensor([[2, 5], [4, 3]]), torch.tensor([[2, 8], [2, 3]]))
b = torch.ne(torch.tensor([[2, 5], [4, 3]]), torch.tensor([[2, 8], [2, 3]]))
print(a)
print(b)

 

논리 연산

torch.logical_and(x,y)

torch.logical_or(x,y)

torch.logical_xor(x,y)

torch.logical_and(input, other, *, out=None)
torch.logical_or(input, other, *, out=None)
torch.logical_xor(input, other, *, out=None)

Parameters
# input (Tensor) – the input tensor.
# other (Tensor) – the tensor to compute AND with

Keyword Arguments
# out (Tensor, optional) – the output tensor.
a = torch.tensor([True, False, True, False])
b = torch.tensor([True, True, False, False])

result = torch.logical_and(a, b)
print(result)

result = torch.logical_or(a, b)
print(result)

result = torch.logical_xor(a, b)
print(result)