赞
踩
首先先上概念:
(yi为测量值,yi_hat为拟合值)
决定系数R2(coefficient of determination),也称判定系数或者拟合优度:
实数拟合中的计算代码如下:
其中Z为测量值,Z_fit为拟合值
原生实现:(代码1)
- # 原生实现 衡量线性回归的MSE 、 RMSE、 MAE、r2
- import numpy as np
- from math import sqrt
- mse = np.sum((Z - Z_fit) ** 2) / len(Z)
- rmse = sqrt(mse)
- mae = np.sum(np.absolute(Z - Z_fit)) / len(Z)
- r2 = 1-mse/ np.var(Z) # 均方误差/方差
- print(" mae:",mae,"mse:",mse," rmse:",rmse," r2:",r2)
python的sklearn库内置函数实现:(代码2)
其中y_test为测量值, y_predict为拟合值
- # 使用sklearn调用衡量线性回归的MSE 、 RMSE、 MAE、r2
- import numpy as np
- from sklearn.metrics import mean_absolute_error
- from sklearn.metrics import mean_squared_error
- from sklearn.metrics import r2_score
- print("mean_absolute_error:", mean_absolute_error(y_test, y_predict))
- print("mean_squared_error:", mean_squared_error(y_test, y_predict))
- print("rmse:", np.sqrt(mean_squared_error(y_test, y_predict)))
- print("r2 score:", r2_score(y_test, y_predict))
复数拟合:电化学阻抗谱等效电路等需要复数拟合曲线评价R2分数和RMSE,即Z和Z_fit为复数时(格式为:a+bj)需要将距离改成模值,将差的平方改成模的平方,将求方差改成先求模值再求模值的方差,具体代码如下:(改编代码1,代码2的库函数不能应用于复数域)
- """
- # 实数拟合的MSE 、 RMSE、 MAE、r2
- mse = np.sum((Z - Z_fit) ** 2) / len(Z)
- rmse = sqrt(mse)
- mae = np.sum(np.absolute(Z - Z_fit)) / len(Z)
- r2 = 1-mse/ np.var(Z)
- """
- # 复数拟合的MSE 、 RMSE、 MAE、r2
- mse = np.sum(abs(Z - Z_fit) ** 2) / len(Z)
- rmse = sqrt(mse)
- mae = np.sum(abs(Z - Z_fit)) / len(Z)
- r2 = 1-mse/ np.var(abs(Z))#均方误差/方差
- print(" mae:",mae,"mse:",mse," rmse:",rmse," r2:",r2)
希望对你有帮助~嘻嘻
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。