首页 > 文章列表 > python如何实现均方误差和均方根误差?

python如何实现均方误差和均方根误差?

python基础
104 2022-08-07

一、python实现均方误差

均方误差是各数据偏离真实值的距离平方和的平均数,也即误差平方和的平均数。

用法:一般被用在机器学习的预测值与真实值之间的距离。均方误差对应的是最小二乘法。

# -*- coding: utf-8 -*-
import math

def get_mse(records_real, records_predict):
    """
    均方误差
    """
    if len(records_real) == len(records_predict):
        return sum([(x - y) ** 2 for x, y in zip(records_real, records_predict)]) / len(records_real)
    else:
        return None

二、python实现均方根误差

均方根误差亦称标准误差,是均方误差的算术平方根。

# -*- coding: utf-8 -*-
import math

def get_rmse(records_real, records_predict):
    """
    均方根误差
    """
    mse = get_mse(records_real, records_predict)
    if mse:
        return math.sqrt(mse)
    else:
        return None