코딩걸음마

[딥러닝] Mean Square Error (MSE) Loss 본문

딥러닝_Pytorch

[딥러닝] Mean Square Error (MSE) Loss

코딩걸음마 2022. 6. 27. 21:35
728x90

import torch
def mse(x_hat, x):
    # |x_hat| = (batch_size, dim)
    # |x| = (batch_size, dim)
    y = ((x - x_hat)**2).mean()
    
    return y

x = torch.FloatTensor([[1, 1],
                       [2, 2]])
x_hat = torch.FloatTensor([[0, 0],
                           [0, 0]])

print(x.size(), x_hat.size())
torch.Size([2, 2]) torch.Size([2, 2])

 

 

mse(x_hat, x)
tensor(2.5000)
 
 

MSE in PyTorch

import torch.nn.functional as F
F.mse_loss(x_hat, x)
tensor(2.5000)

 

reduction 값을 입력하면, 연산 후 스칼라가 반환됩니다.

F.mse_loss(x_hat, x, reduction='sum')
tensor(10.)
F.mse_loss(x_hat, x, reduction='mean') #reduction 차원축소
tensor(2.5000)

 

vector 그대로 출력하기

F.mse_loss(x_hat, x, reduction='none')  #vector 그대로 출력하기
tensor([[1., 1.],
        [4., 4.]])

 

 

import torch.nn as nn
mse_loss = nn.MSELoss()

mse_loss(x_hat, x)
tensor(2.5000)
 
 
728x90
Comments