程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

回歸評估指標-Python實現

編輯:Python


常用回歸模型評估指標的python計算邏輯。python和相關package版本:

import
sys

import sklearn
import pandas as pd
import numpy as np
import math
print( "Python版本:", sys. version)
print( "sklearn版本:", sklearn. __version__)
print( "pandas:", pd. __version__)
print( "numpy:", np. __version__)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
Python版本: 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)]

sklearn版本: 0.22
pandas: 0.23.4
numpy: 1.17.4
  • 1.
  • 2.
  • 3.
  • 4.

MAE

from
sklearn.
metrics
import
mean_absolute_error

y_true = [ 3, - 0.5, 2, 7]
y_pred = [ 2.5, 0.0, 2, 8]
mean_absolute_error( y_true, y_pred)
  • 1.
  • 2.
  • 3.
  • 4.
0.5

  • 1.
sum([
abs(
y_true[
i]
-
y_pred[
i])
for
i
in
range(
len(
y_true))])
/
len(
y_true)

  • 1.
0.5

  • 1.

MSE

from
sklearn.
metrics
import
mean_squared_error

y_true = [ 3, - 0.5, 2, 7]
y_pred = [ 2.5, 0.0, 2, 8]
mean_squared_error( y_true, y_pred)
  • 1.
  • 2.
  • 3.
  • 4.
0.375

  • 1.
sum([
abs(
y_true[
i]
-
y_pred[
i])
*
*
2
for
i
in
range(
len(
y_true))])
/
len(
y_true)

  • 1.
0.375

  • 1.

RMSE

這個沒啥說的,mse開方就行

math.
sqrt(
mean_squared_error(
y_true,
y_pred))

  • 1.
0.6123724356957945

  • 1.

R方

from
sklearn.
metrics
import
r2_score

r2_score( y_true, y_pred)
  • 1.
  • 2.
0.9486081370449679

  • 1.
1
-
sum([(
y_true[
i]
-
y_pred[
i])
*
*
2
for
i
in
range(
len(
y_true))])
/
sum(

[( y_true[ i] - sum( y_true) / len( y_true)) * * 2 for i in range( len( y_true))])
  • 1.
  • 2.
0.9486081370449679

  • 1.

整合

mape由於可能存在分母為0的情況,因此暫時沒有統計。把其他指標整合一下,格式化輸出:

from
sklearn.
metrics
import
mean_absolute_error

from sklearn. metrics import mean_squared_error
from sklearn. metrics import r2_score
def reg_metric( y_true, y_predict):
mae = mean_absolute_error( y_true, y_pred)
mse = mean_squared_error( y_true, y_pred)
rmse = math. sqrt( mean_squared_error( y_true, y_pred))
r2 = r2_score( y_true, y_pred)
print( "MAE:", mae)
print( "MSE:", mse)
print( "RMSE:", rmse)
print( "R Square:", r2)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
reg_metric(
y_true
=
y_true,
y_predict
=
y_pred)

  • 1.
MAE: 0.5

MSE: 0.375
RMSE: 0.6123724356957945
R Square: 0.9486081370449679
  • 1.
  • 2.
  • 3.
  • 4.

2020-06-16、連綿梅雨季 於南京市江寧區九龍湖



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved