sklearn:如何获得多项式特征的系数

Mor*_*itz 11 python scikit-learn

我知道可以通过使用:获得多项式特征作为数字polynomial_features.transform(X).根据手册,两度的特点是:[1, a, b, a^2, ab, b^2].但是,如何获得更高订单的功能描述?.get_params()没有显示任何功能列表.

pre*_*rez 23

顺便说一句,现在有更合适的功能: PolynomialFeatures.get_feature_names.

from sklearn.preprocessing import PolynomialFeatures
import pandas as pd
import numpy as np

data = pd.DataFrame.from_dict({
    'x': np.random.randint(low=1, high=10, size=5),
    'y': np.random.randint(low=-1, high=1, size=5),
})

p = PolynomialFeatures(degree=2).fit(data)
print p.get_feature_names(data.columns)
Run Code Online (Sandbox Code Playgroud)

这将输出如下:

['1', 'x', 'y', 'x^2', 'x y', 'y^2']
Run Code Online (Sandbox Code Playgroud)

NB出于某种原因,您必须先使用PolynomialFeatures对象,然后才能使用get_feature_names().

如果您是Pandas-lover(就像我一样),您可以使用以下所有新功能轻松构建DataFrame:

features = DataFrame(p.transform(data), columns=p.get_feature_names(data.columns))
print features
Run Code Online (Sandbox Code Playgroud)

结果将如下所示:

     1    x    y   x^2  x y  y^2
0  1.0  8.0 -1.0  64.0 -8.0  1.0
1  1.0  9.0 -1.0  81.0 -9.0  1.0
2  1.0  1.0  0.0  1.0   0.0  0.0
3  1.0  6.0  0.0  36.0  0.0  0.0
4  1.0  5.0 -1.0  25.0 -5.0  1.0
Run Code Online (Sandbox Code Playgroud)

  • 函数“get_feature_names”现已弃用,应使用“get_feature_names_out”来代替。 (2认同)

ome*_*rbp 6

import numpy as np
from sklearn.preprocessing import PolynomialFeatures

X = np.array([2,3])

poly = PolynomialFeatures(3)
Y = poly.fit_transform(X)
print Y
# prints [[ 1  2  3  4  6  9  8 12 18 27]]
print poly.powers_
Run Code Online (Sandbox Code Playgroud)

此代码将打印:

[[0 0]
 [1 0]
 [0 1]
 [2 0]
 [1 1]
 [0 2]
 [3 0]
 [2 1]
 [1 2]
 [0 3]]
Run Code Online (Sandbox Code Playgroud)

因此,如果第i个细胞是(x,y),那就意味着Y[i]=(a**x)*(b**y).例如,在代码示例中[2 1]等于(2**2)*(3**1)=12.