一、Standardization
方法一:StandardScaler
1 2 3 4 5 6 | from sklearn.preprocessing import StandardScaler
sds = StandardScaler()
sds.fit(x_train)
x_train_sds = sds.transform(x_train)
x_test_sds = sds.transform(x_test)
|
方法二:MinMaxScaler 特征縮放至特定范圍 , default=(0, 1)
1 2 3 4 5 6 | from sklearn.preprocessing import MinMaxScaler
mns = MinMaxScaler(( 0 , 1 ))
mns.fit(x_train)
x_train_mns = mns.transform(x_train)
x_test_mns = mns.transform(x_test)
|
二、Normalization 使單個樣本具有單位范數(shù)的縮放操作。 經(jīng)常在文本分類和聚類當中使用。
1 2 3 4 5 6 | from sklearn.preprocessing import Normalizer
normalizer = Normalizer()
normalizer.fit(x_train)
x_train_nor = normalizer.transform(x_train)
x_test_nor = normalizer.transform(x_test)
|
三、Binarization 特征二值化是將數(shù)值型特征變成布爾型特征。
1 2 3 4 5 6 | from sklearn.preprocessing import Binarizer
bi = Binarizer(threshold = 0.0 ) # 設置閾值默認0.0 大于閾值設置為1 , 小于閾值設置為0
XX = bi.fit_transform(x_train[ "xx" ]) # shape (1行,X列)
x_train[ "XX" ] = XX.T
# x_train["XX"] = XX[0,:]
|
四、連續(xù)性變量劃分份數(shù)
1 2 3 4 | pandas.cut(x, bins, right = True , labels = None , retbins = False , precision = 3 , include_lowest = False )
x:array - like # 要分箱的數(shù)組
bin : int # 在x范圍內的等寬單元的數(shù)量。
<br>pd.cut(df[ "XXX" ], 5 )
|
進行分箱操作后得到得值是字符串,還需要進行Encoding categorical features
五、one-hot Encoding / Encoding categorical features
1 2 3 4 5 | pandas.get_dummies(data, prefix = None , prefix_sep = '_' , dummy_na = False , columns = None , sparse = False , drop_first = False )
dummy_na = False # 是否把 missing value單獨存放一列
pd.get_dummies(df , columns = [ 'xx' , 'xx' , ... ])
|
六、Imputation of missing values 缺失值處理
①、將無限大,無限小,Missing Value (NaN)替換成其他值;
②、sklearn 不接收包含NaN的值;
1 2 3 4 5 6 7 8 | class sklearn.preprocessing.Imputer(missing_values = 'NaN' , strategy = 'mean' , axis = 0 , verbose = 0 , copy = True )
strategy : (default = ”mean”) # median , most_frequent
axis : (default = ” 0 ”) # 表示用列上所有值進行計算
from sklearn.preprocessing import Imputer
im = Imputer()
im.fit_transform(df[ 'xxx' ])
|
③、使用無意義的值來填充,如-999。
1 2 3 4 | df.replace( np.inf , np.nan )
# 先用NaN值替換,再用-999填充NaN值。
df.fillna( - 999 )
df.fillna( - 1 ) # 注意: -1與標準化的數(shù)值可能有意義關系
|
七、Feature selection 特征選擇
①:基于 L1-based feature selection

1 2 3 4 5 6 7 8 9 10 11 | from sklearn.linear_model import Lasso
lasso = Lasso()
lasso.fit(xdata,ydata)
lasso.coef_ # 查看特征系數(shù)
array([ 1.85720489 , 0. , - 0.03700954 , 0.09217834 , - 0.01157946 ,
- 0.53603543 , 0.72312094 , - 0.231194 , 1.26363755 , - 0. ,
0. , - 0. , 0. , 0. , 0. ,
- 0. , - 0. , - 0. , 0. , - 0. ,
0. , 5.21977984 , - 0. , - 0. , 7.00192208 ,
- 0. , 0. , 0. , - 0. ])
|
可以發(fā)現(xiàn),經(jīng)過One-hot Encod的變量都變成0 , 需要手工進一步篩選 , 不能去掉One-hot的變量 !
利用模型進行篩選的方法:
1 2 3 4 5 | class sklearn.feature_selection.SelectFromModel(estimator, threshold = None , prefit = False )
from sklearn.feature_selection import SelectFromModel
model = SelectFromModel(lasso,prefit = True )
x_new = model.transform(xdata)
|
②:基于 Tree-based feature selection
采用 Random Forests
1 2 3 4 5 6 7 8 | from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor()
rf.fit(xdata,ydata)
rf.feature_importances_
array([ 8.76227379e - 02 , 4.41726855e - 02 , 2.12394498e - 02 ,
1.98631826e - 01 , 1.75612945e - 02 , 6.72095736e - 02 ,
4.25518536e - 01 , 3.50132246e - 02 , 7.23241098e - 02 , ... ]
|
非線性模型, 沒有系數(shù), 只有變量重要性!!!!
變量重要性大,放前面, 小的刪除或者放后面
③:基于Removing features with low variance 移除所有方差不滿足閾值的特征
1 2 3 4 5 | class sklearn.feature_selection.VarianceThreshold(threshold = 0.0 )
from sklearn.feature_selection import VarianceThreshold
v = VarianceThreshold( 1 )
v.fit_transform(xdata)
|
④:基于Univariate feature selection 單變量特征選擇
1、SelectKBest 移除得分前 k 名以外的所有特征
1 2 3 4 | class sklearn.feature_selection.SelectKBest(score_func = <function f_classif>, k = 10 )
score_func : 統(tǒng)計指標函數(shù)
K : 個數(shù)
|
模型衡量指標:

導入相應的函數(shù)即可!
1 2 3 4 5 | from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_regression
skb = SelectKBest(f_regression,k = 10 )
skb.fit_transform(xdata,ydata)
xdata.shape
|
2、移除得分在用戶指定百分比以后的特征
1 2 3 4 | class sklearn.feature_selection.SelectPercentile(score_func = <function f_classif>, percentile = 10 )
score_func:采用統(tǒng)計指標函數(shù)
percentile:百分數(shù)
|
推薦使用 Feature importtance , Tree-base > L1-base > ... //
八、Dimensionality reduction 減少要考慮的隨機變量的數(shù)量
方法一:PCA ,主成分分析 , 計算協(xié)方差矩陣
1 2 3 4 5 6 7 | sklearn.decomposition.PCA(n_components = None , copy = True , whiten = False , svd_solver = 'auto' , tol = 0.0 , iterated_power = 'auto' , random_state = None )
# n_components : 設置留下來幾列
from sklearn.decomposition import PCA
pca = PCA( 15 )
newdata = pca.fit_transform(xdata)
newdata.shape
|
univariate feature selection 與 PCA 區(qū)別:
1/ 計算每一個feature 統(tǒng)計量 , 然后選擇前幾個
2/ PCA 是考慮整個數(shù)據(jù)集 , 列與列存在關系 , 計算整個矩陣方差共線,
1 2 | pca.explained_variance_ # 可解釋的方差
pca.explained_variance_ratio_ # 百分比
|
注意:PCA 前先將數(shù)據(jù)進行標準化!!!
1 2 3 | from sklearn.preprocessing import StandardScaler
ss = StandardScaler()
pca.fit_transform(ss.fit_transform(xdata))
|
方法二:TruncatedSVD
TruncatedSVD 原來N列 可以選擇指定保留k列 , 降維
SVD 產(chǎn)生N*N矩陣 , 沒有降維
1 2 3 | sklearn.decomposition.TruncatedSVD(n_components = 2 , algorithm = 'randomized' , n_iter = 5 , random_state = None , tol = 0.0 )
n_components: int , 輸出數(shù)據(jù)的期望維度。
|
九、思維導圖

十、fit、fit_transform和transform的區(qū)別
我們使用sklearn進行文本特征提取/預處理數(shù)據(jù)??梢钥吹匠柧殻A測和評估以外,處理其他工作的類都實現(xiàn)了3個方法:fit、transform和fit_transform。
從命名中可以看到,fit_transform方法是先調用fit然后調用transform,我們只需要關注fit方法和transform方法即可。
transform方法主要用來對特征進行轉換。從可利用信息的角度來說,轉換分為無信息轉換和有信息轉換。
通過總結常用的轉換類,我們得到下表:

fit方法主要對整列,整個feature進行操作,但是對于處理樣本獨立的操作類,fit操作沒有實質作用!
十一、特征工程選擇





變化率例子: 10月 : (20% - 10%) / 10% = 100%
|