머신러닝

[pytorch] 행렬 연산(덧셈, 뺄셈, 곱셈, 평균, 최대값)

코딩하는 람지 2022. 9. 16. 17:06

행렬 곱셈(.matmul)

m1 = torch.FloatTensor([[1, 2], [3, 4]])
m2 = torch.FloatTensor([[1], [2]])
print('Shape of Matrix 1: ', m1.shape) # 2 x 2
print('Shape of Matrix 2: ', m2.shape) # 2 x 1
print(m1.matmul(m2)) # 2 x 1

실행결과

Shape of Matrix 1:  torch.Size([2, 2])
Shape of Matrix 2:  torch.Size([2, 1])
tensor([[ 5.],
        [11.]])

 

 

원소 별 곱셈(.mul)

동일한 크기의 행렬이 동일한 위치에 있는 원소끼리 곱함

서로 다른 크기의 행렬에 브로드캐스팅 적용 후 원소 별 곱셈이 수행된다.

m1 = torch.FloatTensor([[1, 2], [3, 4]])
m2 = torch.FloatTensor([[1], [2]])
print('Shape of Matrix 1: ', m1.shape) # 2 x 2
print('Shape of Matrix 2: ', m2.shape) # 2 x 1
print(m1 * m2) # 2 x 2
print(m1.mul(m2))
Shape of Matrix 1:  torch.Size([2, 2])
Shape of Matrix 2:  torch.Size([2, 1])
tensor([[1., 2.],
        [6., 8.]])
tensor([[1., 2.],
        [6., 8.]])
# 브로드캐스팅 과정에서 m2 텐서가 어떻게 변경되는지 보겠습니다.
[1]
[2]
==> [[1, 1],
     [2, 2]]

 

행렬 덧셈(sum)

t = torch.FloatTensor([[1, 2], [3, 4]])
print(t.sum()) # 단순히 원소 전체의 덧셈을 수행
print(t.sum(dim=0)) # 행을 제거
print(t.sum(dim=1)) # 열을 제거
print(t.sum(dim=-1)) # 열을 제거
tensor(10.)
tensor([4., 6.])
tensor([3., 7.])
tensor([3., 7.])

 

최대(Max)

원소의 최대값을 리턴

t = torch.FloatTensor([[1, 2], [3, 4]])
print(t.max()) # Returns one value: max
tensor(4.)

 

아그맥스(ArgMax)

최대값을 가진 인덱스를 리턴(max에 dim 인자를 주면 argmax도 함께 리턴한다)

print(t.max(dim=0))
(tensor([3., 4.]), tensor([1, 1]))
# [1, 1]가 무슨 의미인지 봅시다. 기존 행렬을 다시 상기해봅시다.
[[1, 2],
 [3, 4]]
첫번째 열에서 0번 인덱스는 1, 1번 인덱스는 3입니다.
두번째 열에서 0번 인덱스는 2, 1번 인덱스는 4입니다.
다시 말해 3과 4의 인덱스는 [1, 1]입니다.

※ 본 글은 Pytorch로 시작하는 딥 러닝 입문 교재를 참고하였습니다. https://wikidocs.net/52460