Scikit学习多项式线性回归和多项式特征的系数顺序

时间:2019-02-25 05:14:43

标签: python scikit-learn regression

我正在拟合一个简单的多项式回归模型,我想从拟合的模型中获取系数。

给出准备代码:

import pandas as pd
from itertools import product
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline

# data creation
sa = [1, 0, 1, 2, 3]
sb = [2, 1, 0, 1, 2]
raw = {'a': [], 'b': [], 'w': []}
for (ai, av), (bi, bv) in product(enumerate(sa), enumerate(sb)):
    raw['a'].append(ai)
    raw['b'].append(bi)
    raw['w'].append(av + bv)
data = pd.DataFrame(raw)

# regression
x = data[['a', 'b']].values
y = data['w']
poly = PolynomialFeatures(2)
linr = LinearRegression()
model = make_pipeline(poly, linr)
model.fit(x, y)

根据this answer,我知道可以使用with

获得系数
model.steps[1][1].coef_
>>> array([  0.00000000e+00,  -5.42857143e-01,  -1.71428571e+00,
             2.85714286e-01,   1.72774835e-16,   4.28571429e-01])

但这提供了一个一维数组,我不确定哪个数字对应哪个变量。

他们以 a 0 ,a 1 ,a 2 ,b 0 , b 1 ,b 2 或作为 a 0 ,b 0 ,a < sup> 1 ,b 1 ,a 2 ,b 2

2 个答案:

答案 0 :(得分:3)

您可以使用PolynomialFeatures中的get_feature_names()来了解顺序。

您可以在管道中执行以下操作:

model.steps[0][1].get_feature_names()

# Output:
['1', 'x0', 'x1', 'x0^2', 'x0 x1', 'x1^2']

如果您拥有地图项的名称(在您的情况下为“ a”,“ b”),则可以将其传递以获取实际的地图项。

model.steps[0][1].get_feature_names(['a', 'b'])

# Output:
['1', 'a', 'b', 'a^2', 'a b', 'b^2']

答案 1 :(得分:1)

首先,次数为2的多项式的系数为1,a,b,a ^ 2,ab和b ^ 2,它们在scikit-learn实现中按此顺序排列。您可以通过创建一组简单的输入来验证这一点,例如

x = np.array([[2, 3], [2, 3], [2, 3]])
print(x)
[[2 3]
 [2 3]
 [2 3]]

然后创建多项式特征:

poly = PolynomialFeatures(2)
x_poly = poly.fit_transform(x)
print(x_poly)
[[1. 2. 3. 4. 6. 9.]
 [1. 2. 3. 4. 6. 9.]
 [1. 2. 3. 4. 6. 9.]]

您可以看到第一个和第二个特征是a和b(不计算偏差系数1),第三个特征是a ^ 2(即2 ^ 2),第四个特征是ab = 2 * 3,并且最后是b ^ 2 = 3 ^ 2。即您的模型是:

enter image description here