sklearn.preprocessing.PolynomialFeatures 生成多项式和交互特征

sklearn.preprocessing.PolynomialFeatures

生成多项式和交互特征。生成由度小于或等于指定度的特征的所有多项式组合组成的新特征矩阵。例如,如果输入样本是二维且格式为[a,b],则2阶多项式特征为[1,a,b,a ^ 2,ab,b ^ 2]

class sklearn.preprocessing.PolynomialFeatures(degree=2, *, interaction_only=False, include_bias=True, order='C')

参数:

  • degree:整数多项式特征的程度。默认值= 2
  • interaction_only:布尔值, default = False,如果为真,那么就不会有特征自己和自己结合的项,(即是没有这a ^ 2和b ^ 2)
  • include_bias:布尔值,如果为True(默认值),是否有全是1的一项,如果为 True 的话,那么结果中就会有 0 次幂项,即全为 1 这一列
  • order:str in {‘C’, ‘F’}, default ‘C’,在密集情况下输出数组的顺序。“ F”阶的计算速度更快,但可能会减慢后续的估计量

属性:

  • powers_ :数组,形状(n_output_features,n_input_features),powers_ [i,j]是第i个输出中第j个输入的指数
  • n_input_features_ int,输入特征的总数
  • n_output_features_ int,多项式输出特征的总数。输出要素的数量是通过迭代所有适当大小的输入要素组合来计算的

方法:

  • fit(X [,y])计算输出要素的数量。
  • fit_transform(X [,y])适合数据,然后对其进行转换。
  • get_feature_names([input_features])返回交互之后的特征的名称
  • get_params([deep])获取此估计量的参数。
  • set_params(**参数)设置此估算器的参数。
  • transform(X)将数据转换为多项式特征

注意:degree太高会导致过度拟合

import numpy as np
from sklearn.preprocessing import PolynomialFeatures
X = np.arange(6).reshape(3, 2)
X
'''
array([[0, 1],
   [2, 3],
   [4, 5]])
'''
poly = PolynomialFeatures(2)
poly.fit_transform(X)
'''
array([[ 1.,  0.,  1.,  0.,  0.,  1.],
   [ 1.,  2.,  3.,  4.,  6.,  9.],
   [ 1.,  4.,  5., 16., 20., 25.]])
'''
poly = PolynomialFeatures(interaction_only=True)
poly.fit_transform(X)
'''
array([[ 1.,  0.,  1.,  0.],
   [ 1.,  2.,  3.,  6.],
   [ 1.,  4.,  5., 20.]])
'''

 

posted on 2020-09-22 18:28  小小喽啰  阅读(965)  评论(2编辑  收藏  举报