기술(Tech, IT)/머신 러닝(Machine Learning)

[ML] MSE(Mean Squared Error, 평균 제곱 오차)

Daniel803 2023. 2. 26. 07:00

 Machine Learning 강의 수강 시 가장 먼저 접하게 되는 Loss(Cost) Function 중에 하나다. MSE를 계산하는 방법은 간단하다. 모델이 예측한 값(모델의 output)과 실제값의 차이를 제곱하고 이를 전체 데이터로 나누어준 평균값이다. MSE는 굉장히 큰 에러(예측값과 실제값의 차)를 갖는 이상점이 없는 모델에선 훌륭하지만, 그렇지 않을 경우 예측값과 실제값의 차이를 제곱하기에 이상점에 상대적으로 큰 비중이 실릴 수 있어 바람직하지 못한 결과를 낳는다. 아래는 MSE를 식으로 나타낸 것으로 N은 전제 데이터의 개수다.

 

 아래는 MSE에 대한 샘플 파이썬 코드다.

import numpy as np
import matplotlib.pyplot as plt

# MSE loss function
def mse_loss(y_pred, y_true):
    squared_error = (y_pred - y_true) ** 2
    sum_squared_error = np.sum(squared_error)
    loss = sum_squared_error / y_true.size
    return loss
    
# Plotting
x_vals = np.arange(-20, 20, 0.01)
y_vals = np.square(x_vals)

plt.plot(x_vals, y_vals, "blue")
plt.grid(True, which="major")
plt.show()

 

출처

- https://towardsdatascience.com/understanding-the-3-most-common-loss-functions-for-machine-learning-regression-23e0ef3e14d3

- https://en.wikipedia.org/wiki/Mean_squared_error