import pandas as pd import numpy as np # 读取Excel文件 path = r'F:\BM2023\BM20230531\冠幅\all.xlsx' df = pd.read_excel(path) # 从数据框中提取两列数据,并转换为numpy数组 x = df["wp"].values y = df["w"].values # 进行直线拟合,并计算拟合误差的均方根 coefficients = np.polyfit(x, y, 1) y_fit = np.polyval(coefficients, x) rmse = np.sqrt(np.mean((y - y_fit) ** 2)) print("拟合误差的均方根为:", rmse)增加计算R2的代码
时间: 2024-03-04 14:51:45 浏览: 285
python数据分析与可视化 import pandas as pd import numpy as np import m
要计算R2,需要先计算总离差平方和(TSS)和残差平方和(RSS),然后用1减去RSS/TSS即可得到R2的值。以下是增加计算R2的代码:
import pandas as pd
import numpy as np
from sklearn.metrics import r2_score # 导入r2_score函数
# 读取Excel文件
path = r'F:\BM2023\BM20230531\冠幅\all.xlsx'
df = pd.read_excel(path)
# 从数据框中提取两列数据,并转换为numpy数组
x = df["wp"].values
y = df["w"].values
# 进行直线拟合,并计算拟合误差的均方根
coefficients = np.polyfit(x, y, 1)
y_fit = np.polyval(coefficients, x)
rmse = np.sqrt(np.mean((y - y_fit) ** 2))
# 计算R2
y_mean = np.mean(y)
tss = np.sum((y - y_mean) ** 2)
rss = np.sum((y - y_fit) ** 2)
r2 = 1 - rss / tss
print("拟合误差的均方根为:", rmse)
print("R2为:", r2)
阅读全文