import pandas as pd
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
from scipy.special import factorial
# 导入自己的数据
x = [2,4,2,7,2,1,4,4,3,3,2,2,3,3,5,3,3,3,2,4,6,3,2,1,3,2,1,2,2,2,3,7,1,1,1,5,2,4,2,2,2,4,2,6,2,4,4,2,1,4,3,2,2,4,4,3,2,3,2,5,2,3,4,1]
y = [34,77,68,130,65,61,87,85,78,54,49,75,64,82,100,69,44,40,44,75,84,96,54,35,82,58,44,67,74,43,99,120,85,23,81,64,51,78,45,73,52,62,53,75,42,53,61,61,42,39,80,61,71,53,79,70,41,77,42,78,82,37,67,48]
# add intercept term to predictor variable
x = sm.add_constant(x)
# fit linear regression model
model = sm.OLS(y, x).fit()
# print model summary
print(model.summary())
# plot data and fitted line
fig, ax = plt.subplots()
ax.scatter(x[:,1], y, alpha=0.5)
ax.plot(x[:,1], model.predict(x), 'r', label='OLS regression')
ax.legend()
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.show()
# 导出结果至xls.
# store regression results in a pandas dataframe
regression_results = pd.DataFrame({'Coefficients': model.params, 'Standard Error': model.bse, 't-value': model.tvalues, 'p-value': model.pvalues})
# save dataframe as Excel file
regression_results.to_excel('regression_results.xlsx', index_label='Variable')
丝毫不懂代码——多元线性回归(python)
最新推荐文章于 2023-07-21 23:39:01 发布