scikit支持线性和多项式回归.
在多项式回归部分检查Generalized Linear Models页面:使用基函数扩展线性模型.
例:
>>> from sklearn.preprocessing import PolynomialFeatures
>>> import numpy as np
>>> X = np.arange(6).reshape(3, 2)
>>> X
array([[0, 1],
[2, 3],
[4, 5]])
>>> poly = PolynomialFeatures(degree=2)
>>> poly.fit_transform(X)
array([[ 1, 0, 1, 0, 0, 1],
[ 1, 2, 3, 4, 6, 9],
[ 1, 4, 5, 16, 20, 25]])
X的特征已经从[x_1,x_2]变换为[1,x_1,x_2,x_1 ^ 2,x_1 x_2,x_2 ^ 2],现在可以在任何线性模型中使用.
使用Pipeline工具可以简化这种预处理.可以创建表示简单多项式回归的单个对象,如下所示:
>>> from sklearn.preprocessing import PolynomialFeatures
>>> from sklearn.linear_model import LinearRegression
>>> from sklearn.pipeline import Pipeline
>>> model = Pipeline([('poly', PolynomialFeatures(degree=3)),
... ('linear', LinearRegression(fit_intercept=False))])
>>> # fit to an order-3 polynomial data
>>> x = np.arange(5)
>>> y = 3 - 2 * x + x ** 2 - x ** 3
>>> model = model.fit(x[:, np.newaxis], y)
>>> model.named_steps['linear'].coef_
array([ 3., -2., 1., -1.])
在多项式特征上训练的线性模型能够精确地恢复输入多项式系数.
在某些情况下,没有必要包括任何单个特征的更高权力,而只需要包含最多d个不同特征的所谓交互特征.这些可以通过设置interaction_only = True从PolynomialFeatures获得.