파이토치 구현

함수 만들기
<mse 함수 구현>
def mse(x_hat, x) :
y = ((x - x_hat)**2).mean()
return y
<mse 손실값 구하기>
x = torch.FloatTensor([[1,1],[2,2]])
x_hat = torch.FloatTensor([[0,0],[0,0]])
# x_hat = torch.zeros(2,2)
print(mse(x_hat, x))
결과
tensor(2.5000)
torch.nn.functional
- 파이토치 내부에서 제공하는 mse함수가 들어있는 모듈
- mse_loss()함수
import torch.nn.functional as F
x = torch.FloatTensor([[1,1],[2,2]])
x_hat = torch.zeros(2,2)
F.mse_loss(x_hat,x)
# F.mse_loss(x_hat, x, reduction = 'sum') -> 덧셈까지 진행
# F.mse_loss(x_hat, x, reduction = 'none') -> 아무것도 안함
결과
tensor(2.5000)
<reduction설정>
F.mse_loss(x_hat, x, reduction = 'sum')
F.mse_loss(x_hat, x, reduction = 'none')
결과
tensor(10.)
tensor([[1., 1.],
[4., 4.]])
torch.nn 안의 nn.MSELoss()
- 거의 차이 없음
- 단, 하나의 레이어처럼 취급가능