▪︎ 텐서의 연산
▫︎ 산술 연산
x = torch.ones(2,2)
print(x)
# tensor([[1., 1.],
# [1., 1.]])
x *= 2
print(x)
# tensor([[2., 2.],
# [2., 2.]])
x += 3
print(x)
# tensor([[5., 5.],
# [5., 5.]])
x = torch.tensor([[1,2], [3,4]])
y = torch.tensor([[4,3], [2,1]])
# 더하기
add = torch.add(x, y)
print(add)
print(x + y)
# tensor([[5, 5],
# [5, 5]])
# 빼기
sub = torch.sub(x, y)
print(sub)
print(x - y)
# tensor([[-3, -1],
# [ 1, 3]])
# 곱하기
mul = torch.mul(x, y)
print(mul)
print(x * y)
# tensor([[4, 6],
# [6, 4]])
# 나누기
div = torch.div(x, y)
print(div)
print(x / y)
# tensor([[0.2500, 0.6667],
# [1.5000, 4.0000]])
▫︎ 바꿔치기 연산(in-place)
x = torch.tensor([[5,6], [7,8]])
y = torch.tensor([[3,1], [4,2]])
x.add_(y)
print(x)
# tensor([[ 8, 7],
# [11, 10]])
x.fill_(0)
print(x)
# tensor([[0, 0],
# [0, 0]])
▫︎ 각종 연산
x = torch.tensor([[1.1,2.2,3.3], [4,5,6], [-1,-3.14,-6]])
print("절대값", torch.abs(x))
# 절대값 tensor([[1.1000, 2.2000, 3.3000],
# [4.0000, 5.0000, 6.0000],
# [1.0000, 3.1400, 6.0000]])
print("올림", torch.ceil(x))
# 올림 tensor([[ 2., 3., 4.],
# [ 4., 5., 6.],
# [-1., -3., -6.]])
print("반올림", torch.round(x))
# 반올림 tensor([[ 1., 2., 3.],
# [ 4., 5., 6.],
# [-1., -3., -6.]])
print("내림", torch.floor(x))
# 내림 tensor([[ 1., 2., 3.],
# [ 4., 5., 6.],
# [-1., -4., -6.]])
print("모든 원소의 합", torch.sum(x))
# 모든 원소의 합 tensor(11.4600)
print("모든 원소의 곱", torch.prod(x))
# 모든 원소의 곱 tensor(-18054.7500)
print("최소값", torch.min(x))
# 최소값 tensor(-6.)
print("최대값", torch.max(x))
# 최대값 tensor(6.)
print("최소값의 인덱스", torch.argmin(x))
# 최소값의 인덱스 tensor(8)
print("최대값의 인덱스", torch.argmax(x))
# 최대값의 인덱스 tensor(5)
print("평균값", torch.mean(x))
# 평균값 tensor(1.2733)
print("표준편차", torch.std(x))
# 표준편차 tensor(3.9719)
print("중복제거", torch.unique(torch.tensor([1,1,1,2,2,2,3,3,3,4,4])))
# 중복제거 tensor([1, 2, 3, 4])
- 클램프 : 최소값과 최대값을 정하고 그 범위 안으로 값을 맞춤
print("클램프", torch.clamp(x, -2, 2))
# 클램프 tensor([[ 1.1000, 2.0000, 2.0000],
# [ 2.0000, 2.0000, 2.0000],
# [-1.0000, -2.0000, -2.0000]]