用python手动编写均方误差,均方根误差,平均绝对误差,R方各自函数的代码
时间: 2024-09-18 20:14:04 浏览: 62
在Python中,我们可以手动编写计算统计指标如均方误差(Mean Squared Error, MSE),均方根误差(Root Mean Squared Error, RMSE),平均绝对误差(Average Absolute Error, MAE)以及R方(R-squared)的函数。以下是简单的示例:
```python
import numpy as np
def mean_squared_error(y_true, y_pred):
"""
计算均方误差
:param y_true: 真实值数组
:param y_pred: 预测值数组
:return: MSE
"""
mse = np.mean((y_true - y_pred)**2)
return mse
def root_mean_squared_error(y_true, y_pred):
"""
计算均方根误差
:param y_true: 真实值数组
:param y_pred: 预测值数组
:return: RMSE
"""
rmse = np.sqrt(mean_squared_error(y_true, y_pred))
return rmse
def average_absolute_error(y_true, y_pred):
"""
计算平均绝对误差
:param y_true: 真实值数组
:param y_pred: 预测值数组
:return: MAE
"""
mae = np.mean(np.abs(y_true - y_pred))
return mae
def r_squared(y_true, y_pred):
"""
计算R方 (只适用于回归模型)
:param y_true: 真实值数组
:param y_pred: 预测值数组
:return: R^2
"""
ss_total = np.sum((y_true - np.mean(y_true))**2)
ss_residual = np.sum((y_true - y_pred)**2)
r_squared = 1 - (ss_residual / ss_total)
return r_squared
# 使用示例
y_true = [1, 2, 3, 4, 5]
y_pred = [1.5, 2.5, 3.5, 4.5, 5.5]
mse = mean_squared_error(y_true, y_pred)
rmse = root_mean_squared_error(y_true, y_pred)
mae = average_absolute_error(y_true, y_pred)
r_squared_value = r_squared(y_true, y_pred)
print(f"MSE: {mse}, RMSE: {rmse}, MAE: {mae}, R^2: {r_squared_value}")
```
阅读全文