用sklearn的PolynomialFeatures无法理解

Tec*_*101 7 python machine-learning scikit-learn polynomials

在sklearn的Polynomial Features中需要帮助.它对一个功能很有效,但每当我添加多个功能时,除了提升到度数的值之外,它还会在数组中输出一些值.例如:对于这个数组,

X=np.array([[230.1,37.8,69.2]])
Run Code Online (Sandbox Code Playgroud)

当我尝试

X_poly=poly.fit_transform(X)
Run Code Online (Sandbox Code Playgroud)

它输出

[[ 1.00000000e+00 2.30100000e+02 3.78000000e+01 6.92000000e+01
5.29460100e+04 8.69778000e+03 1.59229200e+04 1.42884000e+03
2.61576000e+03 4.78864000e+03]]
Run Code Online (Sandbox Code Playgroud)

这是8.69778000e+03,1.59229200e+04,2.61576000e+03什么?

dim*_*dim 11

如果你有功能[a, b, c],默认的多项式功能(在sklearn度数是2)应该是[1, a, b, c, a^2, b^2, c^2, ab, bc, ca].

2.61576000e+0337.8x62.2=2615,76(2615,76 = 2.61576000 x 10^3)

用一种简单的方法PolynomialFeatures就可以创建新功能.这是一个很好的参考这里.当然有使用的缺点("过度拟合")PolynomialFeatures(见这里).

编辑:
使用多项式特征时我们必须小心.计算多项式特征的数量的公式是N(n,d)=C(n+d,d)其中n是特征的数量,d是多项式的次数,C是二项式系数(组合).在我们的例子中,数字是C(3+2,2)=5!/(5-2)!2!=10但是当特征的数量或度数是高度时,多项式特征变得太多.例如:

N(100,2)=5151
N(100,5)=96560646
Run Code Online (Sandbox Code Playgroud)

因此,在这种情况下,您可能需要应用正则化来惩罚某些权重.很可能该算法将开始遭受维数的诅咒(这里也是一个非常好的讨论).

  • 尽管“bc”的位置是正确的,但多项式特征公式不正确。请参阅`poly.get_feature_names(['a','b','c'])`,它将给出`['1', 'a', 'b', 'c', 'a^2', ' a b'、'a c'、'b^2'、'b c'、'c^2']`。 (3认同)
  • 为什么它给出 ab、bc、ca? (2认同)

Pra*_*wal 8

PolynomialFeatures生成具有给定程度的所有特征的多项式组合的新矩阵。

像[a]将2度转换为[1,a,a ^ 2]。

您可以可视化将输入转换为由PolynomialFeatures生成的矩阵。

from sklearn.preprocessing import PolynomialFeatures
a = np.array([1,2,3,4,5])
a = a[:,np.newaxis]
poly = PolynomialFeatures(degree=2)
a_poly = poly.fit_transform(a)
print(a_poly)
Run Code Online (Sandbox Code Playgroud)

输出:

 [[ 1.  1.  1.]
 [ 1.  2.  4.]
 [ 1.  3.  9.]
 [ 1.  4. 16.]
 [ 1.  5. 25.]]
Run Code Online (Sandbox Code Playgroud)

您可以看到以[1,a,a ^ 2]形式生成的矩阵

为了观察散点图上的多项式特征,让我们使用数字1-100。

import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures

#Making 1-100 numbers
a = np.arange(1,100,1)
a = a[:,np.newaxis]

#Scaling data with 0 mean and 1 standard Deviation, so it can be observed easily
scaler = StandardScaler()
a = scaler.fit_transform(a)

#Applying PolynomialFeatures
poly = PolynomialFeatures(degree=2)
a_poly = poly.fit_transform(a)

#Flattening Polynomial feature matrix (Creating 1D array), so it can be plotted. 
a_poly = a_poly.flatten()
#Creating array of size a_poly with number series. (For plotting)
xarr = np.arange(1,a_poly.size+1,1)

#Plotting
plt.scatter(xarr,a_poly)
plt.title("Degree 2 Polynomial")
plt.show()
Run Code Online (Sandbox Code Playgroud)

输出:

2度

改变度= 3,我们得到:

3度


np8*_*np8 6

检查功能的一般方法是使用poly.get_feature_names(). 在这种情况下,它将是

>>> poly.get_feature_names(['a','b','c'])
    ['1', 'a', 'b', 'c', 'a^2', 'a b', 'a c', 'b^2', 'b c', 'c^2']
Run Code Online (Sandbox Code Playgroud)

并且8.69778000e+03,1.59229200e+04,2.61576000e+03相应地对应于a*ba*cb*c项。