gpt4 book ai didi

python - 为什么线性回归图不正确?提供代码和图片

转载 作者:太空宇宙 更新时间:2023-11-03 17:11:26 26 4
gpt4 key购买 nike

我在 Python 中使用 statsmodels 进行线性回归,当我绘制结果时,它看起来是错误的。我使用 this question 中的代码检查了不同的数据集。

但即使我使用以下代码(取自上面链接的问题),最佳拟合线仍然无法正确显示。我不确定问题是什么。

代码:

import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt

X = np.random.rand(100)
Y = X + np.random.rand(100)*0.1

results = sm.OLS(Y,sm.add_constant(X)).fit()

print results.summary()

plt.scatter(X,Y)

X_plot = np.linspace(0,1,100)
plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

plt.show()

我的输出:

Bad Linear Regression

为什么最佳拟合线不正确?

最佳答案

add_constant 默认情况下会在前面添加常量,这意味着常量是第一个参数,斜率是后面的参数。

预测值也可作为 fittedvalues 或通过调用不带参数的预测来获得。

对于显式计算,需要更正params的索引,即

预测 = X_plot*results.params[1] + results.params[0]

关于python - 为什么线性回归图不正确?提供代码和图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34048033/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com