Scikit 普通最小二乘常数项不起作用
Scikit Ordinary Least Squares Constant Term Not Working
from sklearn import linear_model
from random import randint
temp=[]
for i in range(0,100):
r = randint(0,100)
x=r*r+10*r+1000
y=r
temp.append([x,y])
tempX = [p[0] for p in temp]
tempY = [p[1] for p in temp]
trainX = tempX
trainY = [[1, y, y*y] for y in tempY]
regr = linear_model.LinearRegression()
regr.fit(trainY, trainX)
print regr.coef_
运行 上面的代码给出了以下输出
[ 0. 10. 1.]
普通最小二乘法正确得到r*r和r的系数。它们与我在第 7 行提供的系数相匹配。
为什么不能正确获取常数项?
如何让它按照我想要的方式工作?
使用LinearRegression
,会自动添加截距项。您可以通过以下方式查看此拦截项:
print regr.intercept_ # 1000.0
from sklearn import linear_model
from random import randint
temp=[]
for i in range(0,100):
r = randint(0,100)
x=r*r+10*r+1000
y=r
temp.append([x,y])
tempX = [p[0] for p in temp]
tempY = [p[1] for p in temp]
trainX = tempX
trainY = [[1, y, y*y] for y in tempY]
regr = linear_model.LinearRegression()
regr.fit(trainY, trainX)
print regr.coef_
运行 上面的代码给出了以下输出
[ 0. 10. 1.]
普通最小二乘法正确得到r*r和r的系数。它们与我在第 7 行提供的系数相匹配。
为什么不能正确获取常数项?
如何让它按照我想要的方式工作?
使用LinearRegression
,会自动添加截距项。您可以通过以下方式查看此拦截项:
print regr.intercept_ # 1000.0