使用Python进行线性回归

浏览: 2160

线性回归是最简单同时也是最常用的一个统计模型。线性回归具有结果易于理解,计算量小等优点。如果一个简单的线性回归就能取得非常不错的预测效果,那么就没有必要采用复杂精深的模型了。

今天,我们一起来学习使用Python实现线性回归的几种方法:

  • 通过公式编写矩阵运算程序;
  • 通过使用机器学习库sklearn;
  • 通过使用statmodels库。

这里,先由简至繁,先使用sklearn实现,再讲解矩阵推导实现。

1.使用scikit-learn进行线性回归

设置工作路径

# 
import os
os.getcwd()
os.chdir('D:\my_python_workfile\Project\Writting')

加载扩展包

import pandas as pd
import numpy as np
import pylab as pl
import matplotlib.pyplot as plt

载入数据并可视化分析

这里,为了简单起见,使用sklearn中自带的数据集鸢尾花数据iris进行分析,探索『花瓣宽』和『花瓣长』之间的线性关系。

from sklearn.datasets import load_iris
# load data
iris = load_iris()
# Define a DataFrame
df = pd.DataFrame(iris.data, columns = iris.feature_names)
# take a look
df.head()
#len(df)

Clipboard Image.png

# correlation
df.corr()

Clipboard Image.png


# rename the column name 

df.columns = ['sepal_length','sepal_width','petal_length','petal_width']
df.columns
Index([u'sepal_length', u'sepal_width', u'petal_length', u'petal_width'], dtype='object')
plt.matshow(df.corr())


由上面分析可知,花瓣长sepal length和花瓣宽septal width有着非常显著的相关性。

下面,通过线性回归进一步进行验证。

# save image
fig,ax = plt.subplots(nrows = 1, ncols = 1)
ax.matshow(df.corr())
fig.savefig('./image/iris_corr.png')

建立线性回归模型

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

lr = LinearRegression()
X = df[['petal_length']]
y = df['petal_width']
lr.fit(X,y)
# print the result
lr.intercept_,lr.coef_


(-0.3665140452167297, array([ 0.41641913]))
# get y-hat
yhat = lr.predict(X = df[['petal_length']])

# MSE
mean_squared_error(df['petal_width'],yhat)


# lm plot
plt.scatter(df['petal_length'],df['petal_width'])
plt.plot(df['petal_length'],yhat)

#save image
plt.savefig('./image/iris_lm_fit.png')

2.使用statmodels库

#import statsmodels.api as sm
import statsmodels.formula.api as sm

linear_model = sm.OLS(y,X)

results = linear_model.fit()

results.summary()

Clipboard Image.png

Clipboard Image.png

3.使用公式推导

线性回归,即是使得如下目标函数最小化:

Clipboard Image.png

使用最小二乘法,不难得到ββ的估计:

Clipboard Image.png

从而,我们可以根据此公式,编写求解β^β^的函数。

from numpy import *

#########################
# 定义相应的函数进行矩阵运算求解。
def standRegres(xArr, yArr):
xMat = mat(xArr)
yMat = mat(yArr).T
xTx = xMat.T * xMat
if linalg.det(xTx) == 0.0:
print "this matrix is singular, cannot do inverse!"
return NA
else :
ws = xTx.I * (xMat.T * yMat)
return ws
# test
x0 = np.ones((150,1))
x0 = pd.DataFrame(x0)
X0 = pd.concat([x0,X],axis = 1)
standRegres(X0,y)

matrix([[-0.36651405],
[ 0.41641913]])

结果一致。

参考文献

推荐 4
本文由 黄耀鹏 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册