特征選取


python機器學習-sklearn實戰(博主親自錄制視頻,包含諸多特征篩選方法和代碼)

https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campaign=commission&utm_source=cp-400000000398149&utm_medium=share

 

特征選擇(Feature Selection):choosing a subset of all the features(the ones more informative)。最終得到的特征選是原來特征的一個子集。

參考: 

https://blog.csdn.net/a1368783069/article/details/52048349
常用特征選取算法 
http://www.cnblogs.com/wymlnn/p/4569437.html

Feature selection 
http://scikit-learn.org/stable/modules/feature_selection.html

特征選取是機器學習領域非常重要的一個方向。 
主要有兩個功能:

(1)減少特征數量、降維,使模型泛化能力更強,減少過擬合

(2)增強特征和特征值之間的理解



1, 去掉取值變化小的特征(Removing features with low variance)

這應該是最簡單的特征選擇方法了:假設某特征的特征值只有0和1,並且在所有輸入樣本中,95%的實例的該特征取值都是1,那就可以認為這個特征作用不大。如果100%都是1,那這個特征就沒意義了。當特征值都是離散型變量的時候這種方法才能用,如果是連續型變量,就需要將連續變量離散化之后才能用,而且實際當中,一般不太會有95%以上都取某個值的特征存在,所以這種方法雖然簡單但是不太好用。可以把它作為特征選擇的預處理,先去掉那些取值變化小的特征,然后再從接下來提到的的特征選擇方法中選擇合適的進行進一步的特征選擇。

sklearn.feature_selection.VarianceThreshold(threshold=0.0)
from sklearn.feature_selection import VarianceThreshold
X = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]] sel = VarianceThreshold(threshold=(.8 * (1 - .8))) sel.fit_transform(X) #array([[0, 1], [1, 0], [0, 0], [1, 1], [1, 0], [1, 1]])

 

第一列的特征被去掉


2, 單變量特征選擇(Univariate feature selection)

基於單變量統計測試。

單變量特征選擇能夠對每一個特征進行測試,衡量該特征和響應變量之間的關系,根據得分扔掉不好的特征。對於回歸和分類問題可以采用卡方檢驗等方式對特征進行測試。 
方法簡單,易於運行,易於理解,通常對於理解數據有較好的效果(但對特征優化、提高泛化能力來說不一定有效);這種方法有許多改進的版本、變種。

因此建議作為特征選擇的前處理中的一步。

sklearn.feature_selection.SelectKBest(score_func=<function f_classif>, k=10)

 

選擇前k個分數較高的特征,去掉其他的特征。

sklearn.feature_selection.SelectPercentile(score_func=<function f_classif>, percentile=10)

 

f_regression(單因素線性回歸試驗)用作回歸 
chi2卡方檢驗,f_classif(方差分析的F值)等用作分類

from sklearn.datasets import load_iris from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 iris = load_iris() X, y = iris.data, iris.target X.shape #(150, 4) X_new = SelectKBest(chi2, k=2).fit_transform(X, y) X_new.shape #(150, 2)

 

選擇一定百分比的最高的評分的特征。

sklearn.feature_selection.SelectFpr(score_func=<function f_classif>, alpha=0.05)

 

根據配置的參選搜索

sklearn.feature_selection.GenericUnivariateSelect(score_func=<function f_classif>, mode='percentile', param=1e-05

 


3,遞歸特征消除Recursive feature elimination (RFE)

遞歸特征消除的主要思想是反復的構建模型(如SVM或者回歸模型)然后選出最好的(或者最差的)的特征(可以根據系數來選),把選出來的特征選擇出來,然后在剩余的特征上重復這個過程,直到所有特征都遍歷了。這個過程中特征被消除的次序就是特征的排序。因此,這是一種尋找最優特征子集的貪心算法。 
RFE的穩定性很大程度上取決於在迭代的時候底層用哪種模型。例如,假如RFE采用的普通的回歸,沒有經過正則化的回歸是不穩定的,那么RFE就是不穩定的;假如采用的是Ridge,而用Ridge正則化的回歸是穩定的,那么RFE就是穩定的。

class sklearn.feature_selection.RFECV(estimator, step=1, cv=None, scoring=None, estimator_params=None, verbose=0)

 

from sklearn.svm import SVC from sklearn.datasets import load_digits from sklearn.feature_selection import RFE import matplotlib.pyplot as plt # Load the digits dataset digits = load_digits() X = digits.images.reshape((len(digits.images), -1)) y = digits.target # Create the RFE object and rank each pixel svc = SVC(kernel="linear", C=1) rfe = RFE(estimator=svc, n_features_to_select=1, step=1) rfe.fit(X, y) ranking = rfe.ranking_.reshape(digits.images[0].shape) # Plot pixel ranking plt.matshow(ranking) plt.colorbar() plt.title("Ranking of pixels with RFE") plt.show()

 


4, Feature selection using SelectFromModel

SelectFromModel 是一個 meta-transformer,可以和在訓練完后有一個coef_ 或者 feature_importances_ 屬性的評估器(機器學習算法)一起使用。 
如果相應的coef_ 或者feature_importances_ 的值小於設置的閥值參數,這些特征可以視為不重要或者刪除。除了指定閥值參數外,也可以通過設置一個字符串參數,使用內置的啟發式搜索找到夜歌閥值。可以使用的字符串參數包括:“mean”, “median” 以及這兩的浮點乘積,例如“0.1*mean”.

sklearn.feature_selection.SelectFromModel(estimator, threshold=None, prefit=False)
  • 1

與Lasso一起使用,從boston數據集中選擇最好的兩組特征值。

import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_boston from sklearn.feature_selection import SelectFromModel from sklearn.linear_model import LassoCV # Load the boston dataset. boston = load_boston() X, y = boston['data'], boston['target'] # We use the base estimator LassoCV since the L1 norm promotes sparsity of features. clf = LassoCV() # Set a minimum threshold of 0.25 sfm = SelectFromModel(clf, threshold=0.25) sfm.fit(X, y) n_features = sfm.transform(X).shape[1] # Reset the threshold till the number of features equals two. # Note that the attribute can be set directly instead of repeatedly # fitting the metatransformer. while n_features > 2: sfm.threshold += 0.1 X_transform = sfm.transform(X) n_features = X_transform.shape[1] # Plot the selected two features from X. plt.title( "Features selected from Boston using SelectFromModel with " "threshold %0.3f." % sfm.threshold) feature1 = X_transform[:, 0] feature2 = X_transform[:, 1] plt.plot(feature1, feature2, 'r.') plt.xlabel("Feature number 1") plt.ylabel("Feature number 2") plt.ylim([np.min(feature2), np.max(feature2)]) plt.show()

4.1,L1-based feature selection

L1正則化將系數w的l1范數作為懲罰項加到損失函數上,由於正則項非零,這就迫使那些弱的特征所對應的系數變成0。因此L1正則化往往會使學到的模型很稀疏(系數w經常為0),這個特性使得L1正則化成為一種很好的特征選擇方法。

from sklearn.svm import LinearSVC from sklearn.datasets import load_iris from sklearn.feature_selection import SelectFromModel iris = load_iris() X, y = iris.data, iris.target X.shape #(150, 4) lsvc = LinearSVC(C=0.01, penalty="l1", dual=False).fit(X, y) model = SelectFromModel(lsvc, prefit=True) X_new = model.transform(X) X_new.shape #(150, 3)

 

4.2, 隨機稀疏模型Randomized sparse models

面臨一些相互關聯的特征是基於L1的稀疏模型的限制,因為模型只選擇其中一個特征。為了減少這個問題,可以使用隨機特征選擇方法,通過打亂設計的矩陣或者子采樣的數據並,多次重新估算稀疏模型,並且統計有多少次一個特定的回歸量是被選中。

RandomizedLasso使用Lasso實現回歸設置

sklearn.linear_model.RandomizedLasso(alpha='aic', scaling=0.5, sample_fraction=0.75, n_resampling=200, selection_threshold=0.25, fit_intercept=True, verbose=False, normalize=True, precompute='auto', max_iter=500, eps=2.2204460492503131e-16, random_state=None, n_jobs=1, pre_dispatch='3*n_jobs', memory=Memory(cachedir=None))

 

RandomizedLogisticRegression 使用邏輯回歸 logistic regression,適合分類任務

sklearn.linear_model.RandomizedLogisticRegression(C=1, scaling=0.5, sample_fraction=0.75, n_resampling=200, selection_threshold=0.25, tol=0.001, fit_intercept=True, verbose=False, normalize=True, random_state=None, n_jobs=1, pre_dispatch='3*n_jobs', memory=Memory(cachedir=None))

 

4.3, 基於樹的特征選擇Tree-based feature selection

基於樹的評估器 (查看sklearn.tree 模塊以及在sklearn.ensemble模塊中的樹的森林) 可以被用來計算特征的重要性,根據特征的重要性去掉無關緊要的特征 (當配合sklearn.feature_selection.SelectFromModel meta-transformer):

from sklearn.ensemble import ExtraTreesClassifier
from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectFromModel
iris = load_iris()
X, y = iris.data, iris.target
X.shape
#(150, 4) clf = ExtraTreesClassifier() clf = clf.fit(X, y) clf.feature_importances_ array([ 0.04..., 0.05..., 0.4..., 0.4...]) model = SelectFromModel(clf, prefit=True) X_new = model.transform(X) X_new.shape #(150, 2)

5, Feature selection as part of a pipeline

在進行學習之前,特征選擇通常被用作預處理步驟。在scikit-learn中推薦使用的處理的方法是sklearn.pipeline.Pipeline

sklearn.pipeline.Pipeline(steps)

 

Pipeline of transforms with a final estimator. 
Sequentially 應用一個包含 transforms and a final estimator的列表 ,pipeline中間的步驟必須是‘transforms’, 也就是它們必須完成fit 以及transform 方法s. final estimator 僅僅只需要完成 fit方法.

使用pipeline是未來組合多個可以在設置不同參數時進行一起交叉驗證的步驟 。因此,它允許設置不同步驟中的參數事使用參數名,這些參數名使用‘__’進行分隔。如下實例中所示:

from sklearn import svm
from sklearn.datasets import samples_generator
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_regression
from sklearn.pipeline import Pipeline
# generate some data to play with X, y = samples_generator.make_classification( ... n_informative=5, n_redundant=0, random_state=42) # ANOVA SVM-C anova_filter = SelectKBest(f_regression, k=5) clf = svm.SVC(kernel='linear') anova_svm = Pipeline([('anova', anova_filter), ('svc', clf)]) # You can set the parameters using the names issued # For instance, fit using a k of 10 in the SelectKBest # and a parameter 'C' of the svm anova_svm.set_params(anova__k=10, svc__C=.1).fit(X, y) ... Pipeline(steps=[...]) prediction = anova_svm.predict(X) anova_svm.score(X, y) 0.77... # getting the selected features chosen by anova_filter anova_svm.named_steps['anova'].get_support() #array([ True, True, True, False, False, True, False, True, True, True, False, False, True, False, True, False, False, False, False, True], dtype=bool)

 

簡單語法示例:

clf = Pipeline([
  ('feature_selection', SelectFromModel(LinearSVC(penalty="l1"))), ('classification', RandomForestClassifier()) ]) clf.fit(X, y)

 

python風控評分卡建模和風控常識

 微信掃二維碼,免費學習更多python資源

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM