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