python自编函数计算均方误差,均方根误差,平均绝对误差,R方。不可借用现有计算函数
时间: 2024-09-17 20:08:18 浏览: 57
Python 自编函数来计算均方误差 (Mean Squared Error, MSE)、均方根误差 (Root Mean Squared Error, RMSE)、平均绝对误差 (Mean Absolute Error, MAE),以及 R 方 (R-squared) 的步骤如下:
1. **均方误差(MSE)**:
- 计算公式: `MSE = sum((y_true - y_pred)^2) / len(y_true)`
```python
def mse(y_true, y_pred):
diff = [y_true[i] - y_pred[i] for i in range(len(y_true))]
squared_diff = [d**2 for d in diff]
return sum(squared_diff) / len(y_true)
```
2. **均方根误差(RMSE)**:
- 先计算MSE,然后取其平方根
```python
def rmse(y_true, y_pred):
mse_val = mse(y_true, y_pred)
return math.sqrt(mse_val) if mse_val > 0 else 0 # 防止除以零
```
3. **平均绝对误差(MAE)**:
- 计算公式: `MAE = sum(abs(y_true - y_pred)) / len(y_true)`
```python
def mae(y_true, y_pred):
abs_diff = [abs(y_true[i] - y_pred[i]) for i in range(len(y_true))]
return sum(abs_diff) / len(y_true)
```
4. **R方(R-squared)**:
- 也称为决定系数,表示模型预测效果的好坏,范围在0到1之间,值越大说明拟合越好。
- 公式: `R^2 = 1 - (SS_res / SS_tot)`,其中`SS_res`是残差平方和,`SS_tot`是总平方和。
- 为了简化,我们可以先计算相关系数(`corr`),再利用它推导出R方。
```python
import numpy as np
def r_squared(y_true, y_pred):
corr = np.corrcoef(y_true, y_pred)[0][1]
ss_res = np.sum((y_true - y_pred) ** 2)
ss_tot = np.sum((y_true - np.mean(y_true)) ** 2)
return 1 - (ss_res / ss_tot)
# 使用示例
y_true = [1, 2, 3, 4, 5]
y_pred = [1.2, 2.3, 3.1, 4.0, 5.1]
mse_val = mse(y_true, y_pred)
rmse_val = rmse(y_true, y_pred)
mae_val = mae(y_true, y_pred)
r2_val = r_squared(y_true, y_pred)
print(f"MSE: {mse_val}, RMSE: {rmse_val}, MAE: {mae_val}, R²: {r2_val}")
```
阅读全文