以下内容转自 数析学院,只节选了部分,有需要的同学可以直接查看原文
线性回归是最常见的统计建模方法之一,今天将向大家介绍 Scikit-Learn 中线性回归工具的使用方法,以及一些常用的操作技巧。
首先,我们导入需要用到的其他工具库,并对构建的示例数据进行展示:
- %matplotlib inline
- import matplotlib.pyplot as plt
- import seaborn as sns; sns.set()
- import numpy as np
- rng = np.random.RandomState(1)
- x = 10 * rng.rand(50)
- y = 2 * x - 5 + rng.randn(50)
- plt.scatter(x, y);
可以看到,这些随机样本的两个特征在二维空间中表现为较明显的正相关关系:
通过导入 Scikit-Learn 的 LinearRegression 函数,我们可以很轻松地构建一个线性回归模型,模型的构建过程及拟合效果如下:
- from sklearn.linear_model import LinearRegression
- model = LinearRegression(fit_intercept=True)
- model.fit(x[:, np.newaxis], y)
- xfit = np.linspace(0, 10, 1000)
- yfit = model.predict(xfit[:, np.newaxis])
- plt.scatter(x, y)
- plt.plot(xfit, yfit);
我们可以通过模型对象的 coef_ 和 intercept_ 属性查看回归曲线的斜率与截距:
- print("Model slope: ", model.coef_[0])
- print("Model intercept:", model.intercept_)
当存在多个自变量时,线性回归模型将会默认地拟合估计截距与自变量相对应的回归系数数组:
- rng = np.random.RandomState(1)
- X = 10 * rng.rand(100, 3)
- y = 0.5 + np.dot(X, [1.5, -2., 1.])
- model.fit(X, y)
- print(model.intercept_)
- print(model.coef_)
在前几节中我们曾经谈到过, Scikit-Learn 中的 PolynomialFeatures 函数可以帮助我们生成自变量 x 的幂,从而方便我们构建多项式线性回归:
- from sklearn.preprocessing import PolynomialFeatures
- x = np.array([2, 3, 4])
- poly = PolynomialFeatures(3, include_bias=False)
- poly.fit_transform(x[:, None])
array([[ 2., 4., 8.], [ 3., 9., 27.], [ 4., 16., 64.]])
还可以通过 make_pipeline 来构建一个整合一体的 pipeline 模型:
- from sklearn.pipeline import make_pipeline
- poly_model = make_pipeline(PolynomialFeatures(7),
- LinearRegression())
后文还有介绍 高斯过程回归、Rigde 回归、 Lasso 回归、实际分析案例等,内容较多,先搬运到这,有需要的同学可以先直接到 数析学院 查看原文