python勒让德函数 del函数python( 三 )


195196.2328.975209.9309.9112.0751951
Employed
194760.323
194861.122
194960.171
195061.187
195163.221
#设置预测变量和结果变量,用 GNP 预测 Employed
In [6]: y=df.Employed #结果变量
In [7]: X=df.GNP #预测变量
#为模型增加常数项,即回归线在 y 轴上的截距
In [8]: X=sm.add_constant(X)
#执行最小二乘回归,X 可以是 numpy array 或 pandas dataframe(行数等于数据点个数,列数为预测变量个数),y 可以是一维数组(numpy array)或 pandas series
In [10]: est=sm.OLS(y,X)
使用 OLS 对象的 fit() 方法来进行模型拟合
In [11]: est=est.fit()
#查看模型拟合的结果
In [12]: est.summary()
Out[12]:
#查看最终模型的参数
In [13]: est.params
Out[13]:
const51.843590
GNP0.034752
dtype: float64
#选择 100 个从最小值到最大值平均分布(equally spaced)的数据点
In [14]: X_prime=np.linspace(X.GNP.min(), X.GNP.max(),100)[:,np.newaxis]
In [15]: X_prime=sm.add_constant(X_prime)
#计算预测值
In [16]: y_hat=est.predict(X_prime)
In [17]: plt.scatter(X.GNP, y, alpha=0.3) #画出原始数据
#分别给 x 轴和 y 轴命名
In [18]: plt.xlabel("Gross National Product")
In [19]: plt.ylabel("Total Employment")
In [20]: plt.plot(X_prime[:,1], y_hat, 'r', alpha=0.9) #添加回归线,红色
多元线性回归(预测变量不止一个)
我们用一条直线来描述一元线性模型中预测变量和结果变量的关系,而在多元回归中 , 我们将用一个多维(p)空间来拟合多个预测变量 。下面表现了两个预测变量的三维图形:商品的销量以及在电视和广播两种不同媒介的广告预算 。
数学模型是:
Sales = beta_0 + beta_1*TV + beta_2*Radio
图中,白色的数据点是平面上的点 , 黑色的数据点事平面下的点 。平面的颜色是由对应的商品销量的高低决定的,高是红色,低是蓝色 。
利用 statsmodels 进行多元线性回归
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: import statsmodels.api as sm
In [4]: df_adv=pd.read_csv('g.csv',index_col=0)
In [6]: X=df_adv[['TV','Radio']]
In [7]: y=df_adv['Sales']
In [8]: df_adv.head()
Out[8]:
TVRadioNewspaperSales
1230.137.869.222.1
244.539.345.110.4
317.245.969.39.3
4151.541.358.518.5
5180.810.858.412.9
In [9]: X=sm.add_constant(X)
In [10]: est=sm.OLS(y,X).fit()
In [11]: est.summary()
Out[11]:
你也可以使用 statsmodels 的 formula 模块来建立多元回归模型
In [12]: import statsmodels.formula.api as smf
In [13]: est=smf.ols(formula='Sales ~ TV + Radio',data=https://www.04ip.com/post/df_adv).fit()
处理分类变量
性别或地域都属于分类变量 。
In [15]: df= pd.read_csv('httd.edu/~tibs/ElemStatLearn/datasets/SAheart.data', index_col=0)
In [16]: X=df.copy()
利用 dataframe 的 pop 方法将 chd 列单独提取出来
In [17]: y=X.pop('chd')
In [18]: df.head()
Out[18]:
sbptobaccoldladiposityfamhisttypeaobesityalcohol\
row.names
116012.005.7323.11Present4925.3097.20
21440.014.4128.61Absent5528.872.06
31180.083.4832.28Present5229.143.81
41707.506.4138.03Present5131.9924.26
513413.603.5027.78Present6025.9957.34
agechd
row.names
1521
2631
3460
4581
5491
In [19]: y.groupby(X.famhist).mean()
Out[19]:
famhist
Absent0.237037
Present0.500000
Name: chd, dtype: float64
In [20]: import statsmodels.formula.api as smf
In [21]: df['famhist_ord']=pd.Categorical(df.famhist).labels
In [22]: est=smf.ols(formula="chd ~ famhist_ord", data=https://www.04ip.com/post/df).fit()

推荐阅读