Python线性回归:计算R平方值和绘制拟合直线
以下是如何使用Python进行线性拟合并计算R平方值的代码示例:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
# 生成随机散点数据
x = np.linspace(0, 10, 100)
y = 2 * x + np.random.randn(100)
# 进行线性拟合
reg = LinearRegression().fit(x.reshape(-1, 1), y.reshape(-1, 1))
y_pred = reg.predict(x.reshape(-1, 1))
# 计算R平方值
r2 = r2_score(y, y_pred)
# 绘制散点图和拟合直线
plt.scatter(x, y, label='Data Points')
plt.plot(x, y_pred, color='red', label='Fitted Line')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Scatter Plot with Fitted Line')
plt.legend()
plt.grid(True)
plt.text(2, 25, f'R-squared: {r2:.4f}') # 显示R平方值
plt.show()
使用sklearn库中的LinearRegression进行线性拟合,并使用r2_score函数计算R平方值。最后,将R平方值显示在图表上方。
希望这对你有帮助!如果你还有其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/Rn2 著作权归作者所有。请勿转载和采集!