gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:33:09 24 4
gpt4 key购买 nike

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

给定准备代码:

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])

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

它们的顺序是a0, a1, a2, b0, b1, b2 或者作为a0, b0, a< sup>1, b1, a2, b2?

最佳答案

您可以使用 get_feature_names() PolynomialFeatures 的顺序。

在管道中你可以这样做:

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']

关于python - Scikit 学习多元线性回归和多项式特征的系数顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54859865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com