为什么线性回归图不正确?提供的代码和图片
Why is the graph of the linear regression incorrect? Code and image provided
我在 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()
我的输出:
为什么最佳拟合线不正确?
add_constant
默认在常数前面,也就是说常数是第一个参数,斜率是后面的参数。
预测值也可作为 fittedvalues
或通过调用不带参数的预测获得。
对于显式计算,需要更正 params
的索引,即
predicted = X_plot*results.params[1] + results.params[0]
我在 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()
我的输出:
为什么最佳拟合线不正确?
add_constant
默认在常数前面,也就是说常数是第一个参数,斜率是后面的参数。
预测值也可作为 fittedvalues
或通过调用不带参数的预测获得。
对于显式计算,需要更正 params
的索引,即
predicted = X_plot*results.params[1] + results.params[0]