본문 바로가기

STUDY/인공지능

까먹지 않기 위한 파이토치 공부 내용 정리2

728x90

*  Broadcasting

행렬의 크기가 다르더라도 연산을 위해 자동으로 크기를 맞춰 주는 기능.

편리하나, Naive하게 크기가 맞춰지므로 주의해서 사용해야 함.

'''Broadcasting'''

# Same shape
m1 = torch.FloatTensor([[3, 3]])
m2 = torch.FloatTensor([[2, 2]])
print(m1 + m2) 
# tensor([[5, 5]])

# Vector + scalar
m1 = torch.FloatTensor([[1, 2]])
m2 = torch.FloatTensor([3]) # 변형 된다. 3 -> [[3, 3]]
print(m1, m2)
# tensor([[4., 5.]])

# 2X1 Vector + 1X2 Vector
m1 = torch.FloatTensor([[1, 2]])
m2 = torch.FloatTensor([[3], [4]])
print(m1 + m2)
# m1 ->  1  1
#        2  2
# m2 ->  3  4 
#        3  4
# tensor([[4., 5.],
		  [5., 6.]])

 

* Multiplication vs Matrix Multiplication

.matmul : 행렬 곱셈

              : 2X2(행렬), 2X1(벡터)의 행렬 곱셈의 결과  

.mul 또는 * : 원소 별 곱셈

        : 서로 다른 크기의 행렬이 브로드캐스팅 된 후에 행렬 곱셈이 아닌 element-wise 곱셈을 취함.

# Mul vs MatMul
m1 = torch.FloatTensor([[1, 2], [3, 4]])
m2 = torch.FloatTensor([[1], [2]])
print('Shape of Matrix 1: ', m1.shape) # 2X2
print('Shape of Matrix 2: ', m2.shape) # 2X1
print(m1.matmul(m2)) # 2X1
# Shape of Matrix 1: torch.Size([2, 2])
# Shape of Matrix 2: torch.Size([2, 1])
#=======================================
# 과정
#=======================================
# m1 > 1 2
#	   3 4
# m2 > 1
#	   2
# m1 X m2 = 1X1 + 2X2
# 			3X1 + 4X2
#=======================================
# Result
#=======================================
# tensor([[5.],
#		  [11.])
          
          
m1 = torch.FloatTensor([[1, 2], [3, 4]])
m2 = torch.FloatTensor([[1], [2]])
print('Shape of Matrix 1: ', m1.shape)
print('Shape of Matrix 2: ', m2.shape)
print(m1 * m2)
print(m1.mul(m2)
# Shape of Matrix 1: torch.Size([2, 2])
# Shape of Matrix 2: torch.Size([2, 1])
#=======================================
# 과정
#=======================================
# m1 > 1 2
#	   3 4
# m2 > 1 1
#	   2 2
# m1 X m2 = 1X1 + 2X1
# 			3X2 + 4X2
#=======================================
# Result
#=======================================
# tensor([[1., 2.],
#		  [6., 8.])  # m1 X m2
# tensor([[1., 2.],
#		  [6., 8.])  # m1.mul(m2)

 

* Mean

dim = 0 : 첫번째 차원. 행렬에서는 '행'을 의미

mean()의 인자로 dim을 주면 해당 차원을 제거한다는 의미, dim=0이면 열만 남기겠다는 의미

mean(dim=1)은 두번째 차원인 열을 제거한 텐서

mean(dim=-1)은 마지막 차원을 제거한다는 의미로, 열을 제거한다는 의미

'''Mean'''

t = torch.FloatTensor([[1, 2]])
print(t.mean())
# tensor(1.5000)

# Can't use mean() on integers
t = torch.FloatTensor([[1, 2]])
try:
	print(t.mean())
except Exception as exc:
	print(exc)
# Can't only calculate the mean of floating types. Got Lone instead.
# You can also use t.mean for higher rank tensors to get mean of all elements, or mean by paricular dimension.

t = torch.FloatTensor([[1, 2], [3, 4]])
print(t)
# tensor([[1., 2.],
#		  [3., 4.]])

print(t.mean())
print(t.mean(dim=0))
print(t.mean(dim=1))
print(t.mean(dim=-1))
# tensor(2.5000)
# tensor([2., 3.]) # 열 단위로 평균
# tensor([1.5000, 3.5000]) # 행 단위로 평균
# tensor([1.5000, 3.5000]) # dim = -1은 마지막 차원을 제거한다는 의미, 열의 차원을 제거하고 행 단위로 평균

 

* Sum

'''Sum'''
t = torch.FloatTensor([[1, 2],[3, 4]])
print(t)
# tensor([[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 and Argmax

t = torch.FloatTensor([[1, 2], [3, 4]])
print(t)
# tensor([[1., 2.],
#		  [3., 4.]])

# The max operator returns one value if it is called without an argument.
print(t.max()) # Returns one value : max
# tensor(4.)

# The max operator returns 2 values when called with dimension specified. The first value is the maximum value, and the second value is the argmax :  the index of the element with maximum value.
print(t.max(dim=0))
print('Max: ', t.max(dim=0)[0])
print('Argmax: ', t.max(dim=0)[1])
# (tensor([3., 4.]), tensor([1, 1])) # 뒤에는 max의 인덱스 값
# Max: tensor([3., 4.])
# Argmax: tensor([1, 1])

print(t.max(dim=1))
print(t.max(dim=-1))
# tensor([2., 4.]), tensor([1, 1])
# tensor([2., 4.]), tensor([1, 1])

이 글은 공부 내용을 정리한 글로, 자세한 내용을 공부하고 싶으신 분들은 '부스트코스-파이토치로 시작하는 딥러닝 기초'를 보시기 바랍니다.

728x90