【回归算法 评价指标】MAE,MSE,RMSE,R-square计算函数

无意中发现了一个巨牛的人工智能教程,忍不住分享一下给大家。教程不仅是零基础,通俗易懂,而且非常风趣幽默,像看小说一样!觉得太牛了,所以分享给大家。点这里可以跳转到教程。人工智能教程

回归算法,经常需要用到一些评估指标,它们分别是MAE,MSE,RMSE,R方,python实现如下:

# -*- coding: utf-8 -*-

import math
import numpy as np
import pandas as pd

# 回归评估指标计算,平均绝对误差,均方误差,均方根误差
def compute_mae_mse_rmse(target,prediction):
    error = []
    for i in range(len(target)):
        error.append(target[i] - prediction[i])
    squaredError = []
    absError = []
    for val in error:
        squaredError.append(val * val)  # target-prediction之差平方
        absError.append(abs(val))  # 误差绝对值
    mae=sum(absError)/len(absError)  # 平均绝对误差MAE
    mse=sum(squaredError)/len(squaredError)  # 均方误差MSE
    RMSE=sum(absError)/len(absError)
    return mae,mse,RMSE



def compute_rsquared(X, Y):
    xBar = np.mean(X)
    yBar = np.mean(Y)
    SSR = 0
    varX = 0
    varY = 0
    for i in range(0, len(X)):
        diffXXBar = X[i] - xBar
        diffYYBar = Y[i] - yBar
        SSR += (diffXXBar * diffYYBar)
        varX += diffXXBar ** 2
        varY += diffYYBar ** 2

    SST = math.sqrt(varX * varY)
    r2=round((SSR / SST) ** 2,3)
    return r2

if __name__ == '__main__':
    testX = [174.5, 171.2, 172.9, 161.6, 123.6, 112.1, 107.1, 98.6, 98.7, 97.5, 95.8, 93.5, 91.1, 85.2, 75.6, 72.7,
             68.6,
             69.1, 63.8, 60.1, 65.2, 71, 75.8, 77.8]
    testY = [88.3, 87.1, 88.7, 85.8, 89.4, 88, 83.7, 73.2, 71.6, 71, 71.2, 70.5, 69.2, 65.1, 54.8, 56.7, 62, 68.2, 71.1,
             76.1, 79.8, 80.9, 83.7, 85.8]


    mae,mse,rmse=compute_mae_mse_rmse(testX,testY)
    print("MAE:%.4f " %mae)
    print("MSE:%.4f " %mse)
    print("RMSE:%.4f "%rmse)

    r2=compute_rsquared(testX,testY)
    print("R2:%.4f " %r2)

运行结果:

MAE:28.6917 
MSE:1467.3342 
RMSE:28.6917 
R2:0.3710 
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读