Pytorch의 기본 연산 구현

import torch, math

# 2 X 3 짜리 랜덤값의 tensor 생성
x = torch.randn(2,3)

# 2를 곱한 후 -1
new_x = x * 2 - 1

# 연산 값 확인
print(new_x)
# 절대값 확인
print(torch.abs(new_x))
# 실수 값에서 올림하여 정수 반환
print(torch.ceil(new_x))
# 실수 값에서 내림하여 정수 반환
print(torch.floor(new_x))
# 특정 범위의 값 안에서만 값이 나올 수 있도록
# 최소값보다 낮으면 최소값으로, 최대값보다 높으면 최대값으로 변환
print(torch.clamp(new_x, -0.5, 0.5))

"""
tensor([[-1.4341,  0.6692, -0.3575],
        [-0.6242, -1.3584,  0.3057]])
tensor([[1.4341, 0.6692, 0.3575],
        [0.6242, 1.3584, 0.3057]])
tensor([[-1.,  1., -0.],
        [-0., -1.,  1.]])
tensor([[-2.,  0., -1.],
        [-1., -2.,  0.]])
tensor([[-0.5000,  0.5000, -0.3575],
        [-0.5000, -0.5000,  0.3057]])
"""


print(new_x)
# torch 최소값
print(torch.min(new_x))
# torch 최대값
print(torch.max(new_x))
"""
tensor([[-1.4341,  0.6692, -0.3575],
        [-0.6242, -1.3584,  0.3057]])
tensor(-1.4341)
tensor(0.6692)
"""

 

+ Recent posts