我是python的新手并试图计算一个简单的线性回归。我的模型有一个因变量和一个自变量。我正在使用sklearn包中的linear_model.LinearRegression()。我的R平方值为.16 然后我使用import statsmodels.api作为sm mod = sm.OLS(Y_train,X_train) 我得到了0.61的R平方。下面是从大查询中获取数据的代码
****Code for linear regression****
train_data_df = pd.read_gbq(query,project_id)
train_data_df.head()
X_train = train_data_df.revisit_next_day_rate[:, np.newaxis]
Y_train = train_data_df.demand_1yr_per_new_member[:, np.newaxis]
#scikit-learn version to get prediction R2
model_sci = linear_model.LinearRegression()
model_sci.fit(X_train, Y_train)
print model_sci.intercept_
print ('Coefficients: \n', model_sci.coef_)
print("Residual sum of squares %.2f"
% np.mean((model_sci.predict(X_train) - Y_train ** 2)))
print ('Variance score: %.2f' %model_sci.score(X_train, Y_train))
Y_train_predict = model_sci.predict(X_train)
print ('R Square', r2_score(Y_train,Y_train_predict) )
****for OLM****
print Y_train[:3]
print X_train[:3]
mod = sm.OLS(Y_train,X_train)
res = mod.fit()
print res.summary()
我对此很新。试图了解我应该使用哪个线性回归包?
答案 0 :(得分:0)
找出差异。这是拦截。 OLS默认不接受它。所以通过在下面的代码中添加匹配的答案。
X = sm.add_constant(X)
sm.OLS(y,X)