python怎么计算均方根误差和平均绝对误差
时间: 2024-06-12 10:08:30 浏览: 167
要计算均方根误差(RMSE)和平均绝对误差(MAE),你可以使用以下公式:
均方根误差(RMSE):
RMSE = sqrt((1/n) * Σ(yi - mxi - b)^2)
平均绝对误差(MAE):
MAE = (1/n) * Σ|yi - mxi - b|
其中,n是数据集中的样本数量,yi是实际值,m是斜率,xi是自变量,b是截距。
下面是一个示例代码,演示如何使用Python计算均方根误差和平均绝对误差:
import math
def calculate_rmse(records_real, records_predict, m, b):
n = len(records_real)
rmse = math.sqrt(sum([(y - (m*x + b))**2 for x, y in zip(records_real, records_predict)]) / n)
return rmse
def calculate_mae(records_real, records_predict, m, b):
n = len(records_real)
mae = sum([abs(y - (m*x + b)) for x, y in zip(records_real, records_predict)]) / n
return mae
# 用法示例
records_real = [1, 2, 3, 4, 5]
records_predict = [1.5, 2.5, 3.5, 4.5, 5.5]
m = 0.5
b = 0.5
rmse = calculate_rmse(records_real, records_predict, m, b)
mae = calculate_mae(records_real, records_predict, m, b)
print("均方根误差(RMSE):", rmse)
print("平均绝对误差(MAE):", mae)
阅读全文