sklearn—特征工程


 sklearn實戰-乳腺癌細胞數據挖掘(博主親自錄制視頻)

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

 

項目合作QQ:231469242

 

變量篩選:(邏輯回歸)

好處:

變量少,模型運行速度快,更容易解讀和理解

壞處:

會犧牲掉少量精確性

 

變量不篩選:(random forest)

好處:

提高准確性

壞處:

變量多,運行速度慢

 

 logistic模型為什么要考慮共線性問題? 
共線性問題會導致估計結果不准確,系數方向都可能發生改變。不管是logistic回歸模型,還是ols都要考慮。

 

官網

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

 

 

 

測試結果隨機森林特征工程效果最好,其次是支持向量l2模式

 主成分一個就可以解釋98%以上方差,和spss結果差距大,需要核實

# -*- coding: utf-8 -*-
"""
Created on Sat Apr 14 19:36:29 2018

@author: Administrator
#乳腺癌數據測試中,卡方檢驗效果不如隨機森林,卡方篩選的2個最好因子在隨機森林中權重不是最大

"""
from sklearn.decomposition import PCA
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.datasets import load_breast_cancer
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.svm import LinearSVC
cancer = load_breast_cancer()
X= cancer.data
y= cancer.target

#特征工程-卡方篩選K個最佳特征
#乳腺癌數據測試中,卡方檢驗效果不如隨機森林,卡方篩選的2個最好因子在隨機森林中權重不是最大
#we can perform a \chi^2 test to the samples to retrieve only the two best features as follows:
X_chi2 = SelectKBest(chi2, k=2).fit_transform(X, y)
print("X_chi2 shapes:",X_chi2.shape) 

##特征工程-支持向量l1
#根據模型選擇最佳特征,線性svc選出5個最佳特征
lsvc = LinearSVC(C=0.01, penalty="l1", dual=False).fit(X, y)
model = SelectFromModel(lsvc, prefit=True)
X_lsvc1 = model.transform(X)
print("LinearSVC l1 shapes:",X_lsvc1.shape) 

#特征工程-支持向量l2
lsvc = LinearSVC(C=0.01, penalty="l2", dual=False).fit(X, y)
model = SelectFromModel(lsvc, prefit=True)
X_lsvc2 = model.transform(X)
print("LinearSVC l2 shapes:",X_lsvc2.shape) 

#特征工程-forest of trees 隨機森林
trees = ExtraTreesClassifier(n_estimators=10000)
trees = trees.fit(X, y)
trees.feature_importances_  
model = SelectFromModel(trees, prefit=True)
X_trees = model.transform(X)
print("forest trees shapes:",X_trees.shape) 

'''
測試結果隨機森林特征工程效果最好,其次是支持向量l2模式
X_chi2 shapes: (569, 2)
LinearSVC l1 shapes: (569, 5)
LinearSVC l2 shapes: (569, 9)
forest trees shapes: (569, 10)
'''

#主成分分析
pca =PCA(n_components=0.98)
#pca= PCA(n_components='mle')

digits = load_breast_cancer()
X_digits = cancer.data
y_digits = digits.target

#scaled_x=preprocessing.scale(X_digits)
# Plot the PCA spectrum
#pca.fit(scaled_x)
pca.fit(X_digits)
print("PCA analysis:")
print (pca.explained_variance_ratio_)
print (pca.explained_variance_)
print (pca.n_components_)

#計算協方差
pca.get_covariance()
#Estimated precision of data.計算數據估計的准確性
pca.get_precision()
              

  

 德國信用評分卡測試

數據必須整理為數字型,不接受分類變量

 

# -*- coding: utf-8 -*-
"""
Created on Sat Apr 14 19:36:29 2018

@author: Administrator
#乳腺癌數據測試中,卡方檢驗效果不如隨機森林,卡方篩選的2個最好因子在隨機森林中權重不是最大

"""
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.svm import LinearSVC
from sklearn.ensemble import RandomForestClassifier

trees=100
#讀取文件
readFileName="GermanData_total.xlsx"
#讀取excel
df=pd.read_excel(readFileName)
list_columns=list(df.columns[:-1])
X=df.ix[:,:-1]
y=df.ix[:,-1]
#X_dummy=pd.get_dummies(X)

#特征工程-卡方篩選K個最佳特征
#乳腺癌數據測試中,卡方檢驗效果不如隨機森林,卡方篩選的2個最好因子在隨機森林中權重不是最大
#we can perform a \chi^2 test to the samples to retrieve only the two best features as follows:
X_chi2 = SelectKBest(chi2, k=2).fit_transform(X, y)
print("X_chi2 shapes:",X_chi2.shape) 

##特征工程-支持向量l1
#根據模型選擇最佳特征,線性svc選出5個最佳特征
lsvc = LinearSVC(C=0.01, penalty="l1", dual=False).fit(X, y)
model = SelectFromModel(lsvc, prefit=True)
X_lsvc1 = model.transform(X)
print("LinearSVC l1 shapes:",X_lsvc1.shape) 

#特征工程-支持向量l2
lsvc = LinearSVC(C=0.01, penalty="l2", dual=False).fit(X, y)
model = SelectFromModel(lsvc, prefit=True)
X_lsvc2 = model.transform(X)
print("LinearSVC l2 shapes:",X_lsvc2.shape) 

#特征工程-forest of trees 隨機森林
trees = ExtraTreesClassifier(n_estimators=10000)
trees = trees.fit(X, y)
trees.feature_importances_  
model = SelectFromModel(trees, prefit=True)
X_trees = model.transform(X)
print("forest trees shapes:",X_trees.shape) 

'''
測試結果隨機森林特征工程效果最好,其次是支持向量l2模式
X_chi2 shapes: (569, 2)
LinearSVC l1 shapes: (569, 5)
LinearSVC l2 shapes: (569, 9)
forest trees shapes: (569, 10)
'''

#主成分分析
pca =PCA(n_components=0.98)
#pca= PCA(n_components='mle')

#scaled_x=preprocessing.scale(X_digits)
# Plot the PCA spectrum
#pca.fit(scaled_x)
pca.fit(X)
print("PCA analysis:")
print (pca.explained_variance_ratio_)
print (pca.explained_variance_)
print (pca.n_components_)

#計算協方差
pca.get_covariance()
#Estimated precision of data.計算數據估計的准確性
pca.get_precision()
              

  

 

 

 

 

The classes in the sklearn.feature_selection module can be used for feature selection/dimensionality reduction on sample sets, either to improve estimators’ accuracy scores or to boost their performance on very high-dimensional datasets.

1.13.1. Removing features with low variance

VarianceThreshold is a simple baseline approach to feature selection. It removes all features whose variance doesn’t meet some threshold. By default, it removes all zero-variance features, i.e. features that have the same value in all samples.

As an example, suppose that we have a dataset with boolean features, and we want to remove all features that are either one or zero (on or off) in more than 80% of the samples. Boolean features are Bernoulli random variables, and the variance of such variables is given by

\mathrm{Var}[X] = p(1 - p)

so we can select using the threshold .8 (1 .8):

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

As expected, VarianceThreshold has removed the first column, which has a probability p = 5/6 > .8 of containing a zero.

1.13.2. Univariate feature selection

Univariate feature selection works by selecting the best features based on univariate statistical tests. It can be seen as a preprocessing step to an estimator. Scikit-learn exposes feature selection routines as objects that implement the transformmethod:

  • SelectKBest removes all but the k highest scoring features
  • SelectPercentile removes all but a user-specified highest scoring percentage of features
  • using common univariate statistical tests for each feature: false positive rate SelectFpr, false discovery rate SelectFdr, or family wise error SelectFwe.
  • GenericUnivariateSelect allows to perform univariate feature selection with a configurable strategy. This allows to select the best univariate selection strategy with hyper-parameter search estimator.

For instance, we can perform a \chi^2 test to the samples to retrieve only the two best features as follows:

>>>
>>> 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) 

These objects take as input a scoring function that returns univariate scores and p-values (or only scores for SelectKBestand SelectPercentile):

The methods based on F-test estimate the degree of linear dependency between two random variables. On the other hand, mutual information methods can capture any kind of statistical dependency, but being nonparametric, they require more samples for accurate estimation.

Feature selection with sparse data

If you use sparse data (i.e. data represented as sparse matrices), chi2mutual_info_regressionmutual_info_classifwill deal with the data without making it dense.

Warning

 

Beware not to use a regression scoring function with a classification problem, you will get useless results.

1.13.3. Recursive feature elimination

Given an external estimator that assigns weights to features (e.g., the coefficients of a linear model), recursive feature elimination (RFE) is to select features by recursively considering smaller and smaller sets of features. First, the estimator is trained on the initial set of features and the importance of each feature is obtained either through a coef_ attribute or through a feature_importances_ attribute. Then, the least important features are pruned from current set of features.That procedure is recursively repeated on the pruned set until the desired number of features to select is eventually reached.

RFECV performs RFE in a cross-validation loop to find the optimal number of features.

Examples:

1.13.4. Feature selection using SelectFromModel

SelectFromModel is a meta-transformer that can be used along with any estimator that has a coef_ or feature_importances_attribute after fitting. The features are considered unimportant and removed, if the corresponding coef_ or feature_importances_ values are below the provided threshold parameter. Apart from specifying the threshold numerically, there are built-in heuristics for finding a threshold using a string argument. Available heuristics are “mean”, “median” and float multiples of these like “0.1*mean”.

For examples on how it is to be used refer to the sections below.

Examples

1.13.4.1. L1-based feature selection

Linear models penalized with the L1 norm have sparse solutions: many of their estimated coefficients are zero. When the goal is to reduce the dimensionality of the data to use with another classifier, they can be used along with feature_selection.SelectFromModel to select the non-zero coefficients. In particular, sparse estimators useful for this purpose are the linear_model.Lasso for regression, and of linear_model.LogisticRegression and svm.LinearSVC for classification:

>>>
>>> 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) 

With SVMs and logistic-regression, the parameter C controls the sparsity: the smaller C the fewer features selected. With Lasso, the higher the alpha parameter, the fewer features selected.

Examples:

L1-recovery and compressive sensing

For a good choice of alpha, the Lasso can fully recover the exact set of non-zero variables using only few observations, provided certain specific conditions are met. In particular, the number of samples should be “sufficiently large”, or L1 models will perform at random, where “sufficiently large” depends on the number of non-zero coefficients, the logarithm of the number of features, the amount of noise, the smallest absolute value of non-zero coefficients, and the structure of the design matrix X. In addition, the design matrix must display certain specific properties, such as not being too correlated.

There is no general rule to select an alpha parameter for recovery of non-zero coefficients. It can by set by cross-validation (LassoCV or LassoLarsCV), though this may lead to under-penalized models: including a small number of non-relevant variables is not detrimental to prediction score. BIC (LassoLarsIC) tends, on the opposite, to set high values of alpha.

Reference Richard G. Baraniuk “Compressive Sensing”, IEEE Signal Processing Magazine [120] July 2007http://dsp.rice.edu/sites/dsp.rice.edu/files/cs/baraniukCSlecture07.pdf

1.13.4.2. Tree-based feature selection

Tree-based estimators (see the sklearn.tree module and forest of trees in the sklearn.ensemble module) can be used to compute feature importances, which in turn can be used to discard irrelevant features (when coupled with the 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) 

Examples:

1.13.5. Feature selection as part of a pipeline

Feature selection is usually used as a pre-processing step before doing the actual learning. The recommended way to do this in scikit-learn is to use a sklearn.pipeline.Pipeline:

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

In this snippet we make use of a sklearn.svm.LinearSVC coupled with sklearn.feature_selection.SelectFromModel to evaluate feature importances and select the most relevant features. Then, a sklearn.ensemble.RandomForestClassifier is trained on the transformed output, i.e. using only relevant features. You can perform similar operations with the other feature selection methods and also classifiers that provide a way to evaluate feature importances of course. See the sklearn.pipeline.Pipeline examples for more details.

 

 

 

 

 

 

https://www.cnblogs.com/jasonfreak/p/5448385.html

一個懶惰的人,總是想設計更智能的程序來避免做重復性工作

 

目錄

1 特征工程是什么?
2 數據預處理
  2.1 無量綱化
    2.1.1 標准化
    2.1.2 區間縮放法
    2.1.3 標准化與歸一化的區別
  2.2 對定量特征二值化
  2.3 對定性特征啞編碼
  2.4 缺失值計算
  2.5 數據變換
  2.6 回顧
3 特征選擇
  3.1 Filter
    3.1.1 方差選擇法
    3.1.2 相關系數法
    3.1.3 卡方檢驗
    3.1.4 互信息法
  3.2 Wrapper
    3.2.1 遞歸特征消除法
  3.3 Embedded
    3.3.1 基於懲罰項的特征選擇法
    3.3.2 基於樹模型的特征選擇法
  3.4 回顧
4 降維
  4.1 主成分分析法(PCA)
  4.2 線性判別分析法(LDA)
  4.3 回顧
5 總結
6 參考資料


1 特征工程是什么?

  有這么一句話在業界廣泛流傳:數據和特征決定了機器學習的上限,而模型和算法只是逼近這個上限而已。那特征工程到底是什么呢?顧名思義,其本質是一項工程活動,目的是最大限度地從原始數據中提取特征以供算法和模型使用。通過總結和歸納,人們認為特征工程包括以下方面:

  特征處理是特征工程的核心部分,sklearn提供了較為完整的特征處理方法,包括數據預處理,特征選擇,降維等。首次接觸到sklearn,通常會被其豐富且方便的算法模型庫吸引,但是這里介紹的特征處理庫也十分強大!

  本文中使用sklearn中的IRIS(鳶尾花)數據集來對特征處理功能進行說明。IRIS數據集由Fisher在1936年整理,包含4個特征(Sepal.Length(花萼長度)、Sepal.Width(花萼寬度)、Petal.Length(花瓣長度)、Petal.Width(花瓣寬度)),特征值都為正浮點數,單位為厘米。目標值為鳶尾花的分類(Iris Setosa(山鳶尾)、Iris Versicolour(雜色鳶尾),Iris Virginica(維吉尼亞鳶尾))。導入IRIS數據集的代碼如下:

復制代碼
 1 from sklearn.datasets import load_iris
 2 
 3 #導入IRIS數據集
 4 iris = load_iris()
 5 
 6 #特征矩陣
 7 iris.data
 8 
 9 #目標向量
10 iris.target
復制代碼

2 數據預處理

  通過特征提取,我們能得到未經處理的特征,這時的特征可能有以下問題:

  • 不屬於同一量綱:即特征的規格不一樣,不能夠放在一起比較。無量綱化可以解決這一問題。
  • 信息冗余:對於某些定量特征,其包含的有效信息為區間划分,例如學習成績,假若只關心“及格”或不“及格”,那么需要將定量的考分,轉換成“1”和“0”表示及格和未及格。二值化可以解決這一問題。
  • 定性特征不能直接使用:某些機器學習算法和模型只能接受定量特征的輸入,那么需要將定性特征轉換為定量特征。最簡單的方式是為每一種定性值指定一個定量值,但是這種方式過於靈活,增加了調參的工作。通常使用啞編碼的方式將定性特征轉換為定量特征:假設有N種定性值,則將這一個特征擴展為N種特征,當原始特征值為第i種定性值時,第i個擴展特征賦值為1,其他擴展特征賦值為0。啞編碼的方式相比直接指定的方式,不用增加調參的工作,對於線性模型來說,使用啞編碼后的特征可達到非線性的效果。
  • 存在缺失值:缺失值需要補充。
  • 信息利用率低:不同的機器學習算法和模型對數據中信息的利用是不同的,之前提到在線性模型中,使用對定性特征啞編碼可以達到非線性的效果。類似地,對定量變量多項式化,或者進行其他的轉換,都能達到非線性的效果。

  我們使用sklearn中的preproccessing庫來進行數據預處理,可以覆蓋以上問題的解決方案。

2.1 無量綱化

  無量綱化使不同規格的數據轉換到同一規格。常見的無量綱化方法有標准化和區間縮放法。標准化的前提是特征值服從正態分布,標准化后,其轉換成標准正態分布。區間縮放法利用了邊界值信息,將特征的取值區間縮放到某個特點的范圍,例如[0, 1]等。

2.1.1 標准化

  標准化需要計算特征的均值和標准差,公式表達為:

  使用preproccessing庫的StandardScaler類對數據進行標准化的代碼如下:

1 from sklearn.preprocessing import StandardScaler
2 
3 #標准化,返回值為標准化后的數據
4 StandardScaler().fit_transform(iris.data)

2.1.2 區間縮放法

  區間縮放法的思路有多種,常見的一種為利用兩個最值進行縮放,公式表達為:

  使用preproccessing庫的MinMaxScaler類對數據進行區間縮放的代碼如下:

1 from sklearn.preprocessing import MinMaxScaler
2 
3 #區間縮放,返回值為縮放到[0, 1]區間的數據
4 MinMaxScaler().fit_transform(iris.data)

2.1.3 標准化與歸一化的區別

  簡單來說,標准化是依照特征矩陣的列處理數據,其通過求z-score的方法,將樣本的特征值轉換到同一量綱下。歸一化是依照特征矩陣的行處理數據,其目的在於樣本向量在點乘運算或其他核函數計算相似性時,擁有統一的標准,也就是說都轉化為“單位向量”。規則為l2的歸一化公式如下:

  使用preproccessing庫的Normalizer類對數據進行歸一化的代碼如下:

1 from sklearn.preprocessing import Normalizer
2 
3 #歸一化,返回值為歸一化后的數據
4 Normalizer().fit_transform(iris.data)

2.2 對定量特征二值化

  定量特征二值化的核心在於設定一個閾值,大於閾值的賦值為1,小於等於閾值的賦值為0,公式表達如下:

  使用preproccessing庫的Binarizer類對數據進行二值化的代碼如下:

1 from sklearn.preprocessing import Binarizer
2 
3 #二值化,閾值設置為3,返回值為二值化后的數據
4 Binarizer(threshold=3).fit_transform(iris.data)

2.3 對定性特征啞編碼

  由於IRIS數據集的特征皆為定量特征,故使用其目標值進行啞編碼(實際上是不需要的)。使用preproccessing庫的OneHotEncoder類對數據進行啞編碼的代碼如下:

1 from sklearn.preprocessing import OneHotEncoder
2 
3 #啞編碼,對IRIS數據集的目標值,返回值為啞編碼后的數據
4 OneHotEncoder().fit_transform(iris.target.reshape((-1,1)))

2.4 缺失值計算

  由於IRIS數據集沒有缺失值,故對數據集新增一個樣本,4個特征均賦值為NaN,表示數據缺失。使用preproccessing庫的Imputer類對數據進行缺失值計算的代碼如下:

復制代碼
1 from numpy import vstack, array, nan
2 from sklearn.preprocessing import Imputer
3 
4 #缺失值計算,返回值為計算缺失值后的數據
5 #參數missing_value為缺失值的表示形式,默認為NaN
6 #參數strategy為缺失值填充方式,默認為mean(均值)
7 Imputer().fit_transform(vstack((array([nan, nan, nan, nan]), iris.data)))
復制代碼

2.5 數據變換

  常見的數據變換有基於多項式的、基於指數函數的、基於對數函數的。4個特征,度為2的多項式轉換公式如下:

  使用preproccessing庫的PolynomialFeatures類對數據進行多項式轉換的代碼如下:

1 from sklearn.preprocessing import PolynomialFeatures
2 
3 #多項式轉換
4 #參數degree為度,默認值為2
5 PolynomialFeatures().fit_transform(iris.data)

  基於單變元函數的數據變換可以使用一個統一的方式完成,使用preproccessing庫的FunctionTransformer對數據進行對數函數轉換的代碼如下:

1 from numpy import log1p
2 from sklearn.preprocessing import FunctionTransformer
3 
4 #自定義轉換函數為對數函數的數據變換
5 #第一個參數是單變元函數
6 FunctionTransformer(log1p).fit_transform(iris.data)

2.6 回顧

功能 說明
StandardScaler 無量綱化 標准化,基於特征矩陣的列,將特征值轉換至服從標准正態分布
MinMaxScaler 無量綱化 區間縮放,基於最大最小值,將特征值轉換到[0, 1]區間上
Normalizer 歸一化 基於特征矩陣的行,將樣本向量轉換為“單位向量”
Binarizer 二值化 基於給定閾值,將定量特征按閾值划分
OneHotEncoder 啞編碼 將定性數據編碼為定量數據
Imputer 缺失值計算 計算缺失值,缺失值可填充為均值等
PolynomialFeatures 多項式數據轉換 多項式數據轉換
FunctionTransformer 自定義單元數據轉換 使用單變元的函數來轉換數據

 


 

3 特征選擇

  當數據預處理完成后,我們需要選擇有意義的特征輸入機器學習的算法和模型進行訓練。通常來說,從兩個方面考慮來選擇特征:

  • 特征是否發散:如果一個特征不發散,例如方差接近於0,也就是說樣本在這個特征上基本上沒有差異,這個特征對於樣本的區分並沒有什么用。
  • 特征與目標的相關性:這點比較顯見,與目標相關性高的特征,應當優選選擇。除方差法外,本文介紹的其他方法均從相關性考慮。

  根據特征選擇的形式又可以將特征選擇方法分為3種:

  • Filter:過濾法,按照發散性或者相關性對各個特征進行評分,設定閾值或者待選擇閾值的個數,選擇特征。
  • Wrapper:包裝法,根據目標函數(通常是預測效果評分),每次選擇若干特征,或者排除若干特征。
  • Embedded:嵌入法,先使用某些機器學習的算法和模型進行訓練,得到各個特征的權值系數,根據系數從大到小選擇特征。類似於Filter方法,但是是通過訓練來確定特征的優劣。

  我們使用sklearn中的feature_selection庫來進行特征選擇。

3.1 Filter

3.1.1 方差選擇法

  使用方差選擇法,先要計算各個特征的方差,然后根據閾值,選擇方差大於閾值的特征。使用feature_selection庫的VarianceThreshold類來選擇特征的代碼如下:

1 from sklearn.feature_selection import VarianceThreshold
2 
3 #方差選擇法,返回值為特征選擇后的數據
4 #參數threshold為方差的閾值
5 VarianceThreshold(threshold=3).fit_transform(iris.data)

3.1.2 相關系數法

  使用相關系數法,先要計算各個特征對目標值的相關系數以及相關系數的P值。用feature_selection庫的SelectKBest類結合相關系數來選擇特征的代碼如下:

復制代碼
1 from sklearn.feature_selection import SelectKBest
2 from scipy.stats import pearsonr
3 
4 #選擇K個最好的特征,返回選擇特征后的數據
5 #第一個參數為計算評估特征是否好的函數,該函數輸入特征矩陣和目標向量,輸出二元組(評分,P值)的數組,數組第i項為第i個特征的評分和P值。在此定義為計算相關系數
6 #參數k為選擇的特征個數
7 SelectKBest(lambda X, Y: array(map(lambda x:pearsonr(x, Y), X.T)).T, k=2).fit_transform(iris.data, iris.target)
復制代碼

3.1.3 卡方檢驗

  經典的卡方檢驗是檢驗定性自變量對定性因變量的相關性。假設自變量有N種取值,因變量有M種取值,考慮自變量等於i且因變量等於j的樣本頻數的觀察值與期望的差距,構建統計量:

  這個統計量的含義簡而言之就是自變量對因變量的相關性。用feature_selection庫的SelectKBest類結合卡方檢驗來選擇特征的代碼如下:

1 from sklearn.feature_selection import SelectKBest
2 from sklearn.feature_selection import chi2
3 
4 #選擇K個最好的特征,返回選擇特征后的數據
5 SelectKBest(chi2, k=2).fit_transform(iris.data, iris.target)

3.1.4 互信息法

  經典的互信息也是評價定性自變量對定性因變量的相關性的,互信息計算公式如下:

  為了處理定量數據,最大信息系數法被提出,使用feature_selection庫的SelectKBest類結合最大信息系數法來選擇特征的代碼如下:

復制代碼
 1 from sklearn.feature_selection import SelectKBest
 2 from minepy import MINE
 3 
 4 #由於MINE的設計不是函數式的,定義mic方法將其為函數式的,返回一個二元組,二元組的第2項設置成固定的P值0.5
 5 def mic(x, y):
 6     m = MINE()
 7     m.compute_score(x, y)
 8     return (m.mic(), 0.5)
 9 
10 #選擇K個最好的特征,返回特征選擇后的數據
11 SelectKBest(lambda X, Y: array(map(lambda x:mic(x, Y), X.T)).T, k=2).fit_transform(iris.data, iris.target)
復制代碼

3.2 Wrapper

3.2.1 遞歸特征消除法

  遞歸消除特征法使用一個基模型來進行多輪訓練,每輪訓練后,消除若干權值系數的特征,再基於新的特征集進行下一輪訓練。使用feature_selection庫的RFE類來選擇特征的代碼如下:

復制代碼
1 from sklearn.feature_selection import RFE
2 from sklearn.linear_model import LogisticRegression
3 
4 #遞歸特征消除法,返回特征選擇后的數據
5 #參數estimator為基模型
6 #參數n_features_to_select為選擇的特征個數
7 RFE(estimator=LogisticRegression(), n_features_to_select=2).fit_transform(iris.data, iris.target)
復制代碼

3.3 Embedded

3.3.1 基於懲罰項的特征選擇法

  使用帶懲罰項的基模型,除了篩選出特征外,同時也進行了降維。使用feature_selection庫的SelectFromModel類結合帶L1懲罰項的邏輯回歸模型,來選擇特征的代碼如下:

1 from sklearn.feature_selection import SelectFromModel
2 from sklearn.linear_model import LogisticRegression
3 
4 #帶L1懲罰項的邏輯回歸作為基模型的特征選擇
5 SelectFromModel(LogisticRegression(penalty="l1", C=0.1)).fit_transform(iris.data, iris.target)

  L1懲罰項降維的原理在於保留多個對目標值具有同等相關性的特征中的一個,所以沒選到的特征不代表不重要。故,可結合L2懲罰項來優化。具體操作為:若一個特征在L1中的權值為1,選擇在L2中權值差別不大且在L1中權值為0的特征構成同類集合,將這一集合中的特征平分L1中的權值,故需要構建一個新的邏輯回歸模型:

  View Code

  使用feature_selection庫的SelectFromModel類結合帶L1以及L2懲罰項的邏輯回歸模型,來選擇特征的代碼如下:

1 from sklearn.feature_selection import SelectFromModel
2 
3 #帶L1和L2懲罰項的邏輯回歸作為基模型的特征選擇
4 #參數threshold為權值系數之差的閾值
5 SelectFromModel(LR(threshold=0.5, C=0.1)).fit_transform(iris.data, iris.target)

3.3.2 基於樹模型的特征選擇法

  樹模型中GBDT也可用來作為基模型進行特征選擇,使用feature_selection庫的SelectFromModel類結合GBDT模型,來選擇特征的代碼如下:

1 from sklearn.feature_selection import SelectFromModel
2 from sklearn.ensemble import GradientBoostingClassifier
3 
4 #GBDT作為基模型的特征選擇
5 SelectFromModel(GradientBoostingClassifier()).fit_transform(iris.data, iris.target)

3.4 回顧

所屬方式 說明
VarianceThreshold Filter 方差選擇法
SelectKBest Filter 可選關聯系數、卡方校驗、最大信息系數作為得分計算的方法
RFE Wrapper 遞歸地訓練基模型,將權值系數較小的特征從特征集合中消除
SelectFromModel Embedded 訓練基模型,選擇權值系數較高的特征

 


4 降維

  當特征選擇完成后,可以直接訓練模型了,但是可能由於特征矩陣過大,導致計算量大,訓練時間長的問題,因此降低特征矩陣維度也是必不可少的。常見的降維方法除了以上提到的基於L1懲罰項的模型以外,另外還有主成分分析法(PCA)和線性判別分析(LDA),線性判別分析本身也是一個分類模型。PCA和LDA有很多的相似點,其本質是要將原始的樣本映射到維度更低的樣本空間中,但是PCA和LDA的映射目標不一樣:PCA是為了讓映射后的樣本具有最大的發散性;而LDA是為了讓映射后的樣本有最好的分類性能。所以說PCA是一種無監督的降維方法,而LDA是一種有監督的降維方法。

4.1 主成分分析法(PCA)

  使用decomposition庫的PCA類選擇特征的代碼如下:

1 from sklearn.decomposition import PCA
2 
3 #主成分分析法,返回降維后的數據
4 #參數n_components為主成分數目
5 PCA(n_components=2).fit_transform(iris.data)

4.2 線性判別分析法(LDA)

  使用lda庫的LDA類選擇特征的代碼如下:

1 from sklearn.lda import LDA
2 
3 #線性判別分析法,返回降維后的數據
4 #參數n_components為降維后的維數
5 LDA(n_components=2).fit_transform(iris.data, iris.target)

4.3 回顧

說明
decomposition PCA 主成分分析法
lda LDA 線性判別分析法

 


5 總結

  再讓我們回歸一下本文開始的特征工程的思維導圖,我們可以使用sklearn完成幾乎所有特征處理的工作,而且不管是數據預處理,還是特征選擇,抑或降維,它們都是通過某個類的方法fit_transform完成的,fit_transform要不只帶一個參數:特征矩陣,要不帶兩個參數:特征矩陣加目標向量。這些難道都是巧合嗎?還是故意設計成這樣?方法fit_transform中有fit這一單詞,它和訓練模型的fit方法有關聯嗎?接下來,我將在《使用sklearn優雅地進行數據挖掘》中闡述其中的奧妙!

 

 

多元回歸分析中篩選自變量的必要性及常用方法

由專業人員選定的自變量往往很多,若將這些自變量全部引入多元回歸方程,不僅使方程過於復雜,更重要的是方程中可能包含很多無統計學意義的變量,由於他們的存在,反而使模型對資料的擬合效果很差,因此,有必要對自變量進行篩選,使那些對因變量貢獻較大的自變量盡可能都能被選入回歸模型,而那些貢獻小的、特別是那些與其他自變量有密切線性關系且起“負作用”的自變量盡可能地被排斥在回歸模型之外。
篩選自變量的方法有8種,其中最常用的方法有以下三種,即“前進法、后退法和逐步法”。其含義分別為:
前進法:事先確定選變量進入回歸方程的顯著性水平(記為sle),回歸方程中自變量的數目從無到有,逐一檢驗每個自變量對因變量的貢獻,若其P值小於sle,就將該自變量引入回歸方程,就這樣一個一個地將回歸方程之外的自變量引入回歸方程,直至回歸方程外無具有統計學意義的自變量可被引入時為止,這是只進不出的篩選自變量的方法。
后退法:事先確定從回歸方程中剔除變量(或將變量保留在回歸方程中)的顯著性水平(記為sls),先將全部自變量(條件是樣本含量大於自變量的個數)放入回歸方程,然后逐一檢驗每個自變量對因變量的貢獻,若其P值大於sls且P的取值最大的自變量最先被剔除到回歸方程之外去,就這樣一個一個地將回歸方程之內的自變量剔除回歸方程,直至回歸方程內無自變量可被剔除時為止,這是只出不進的篩選自變量的方法。
逐步法:由於檢驗自變量對因變量貢獻大小時不是孤立的,而是與此時此刻回歸方程中已存在的自變量的數目以及他們共同對因變量的影響情況有關,因此,無論是“前進法”還是“后退法”都存在一些弊病,於是,人們又想出在每一步計算時,既要考慮將回歸方程之外對因變量可能有較大貢獻的自變量引入回歸方程,也要考慮將已引入回歸方程的“退化變質”的變量剔除回歸方程,稱這種有進有出的篩選變量的方法為“逐步回歸分析法”,簡稱“逐步法”。
當然,逐步法也不是十全十美的,因為每次檢驗都取決於當時回歸方程中包含哪些自變量,每個自變量不可能有機會與其他自變量的各種組合進行搭配到。只有“最優回歸子集法”才能找到全部可能的各種自變量的組合,但計算量很大,僅在自變量的數目較少的場合下才是可行的。

 

“特征選擇”節點有助於識別預測特定結果時最重要的字段。在包含成百乃至上千個預測變量的集合中,“特征選擇”節點可以執行篩選和排序,並選出可能最重要的預測變量。最后,將生成一個速度更快且更高效的模型,此模型使用較少的預測變量、執行速度更快且更易於理解。

 


免責聲明!

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



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