日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

機(jī)器學(xué)習(xí)中特征選擇的幾種方法原理和代碼實(shí)現(xiàn)(python)

系統(tǒng) 2243 0

?

一.特征選擇-單變量特征選擇

1.SelectKBest可以依據(jù)相關(guān)性對特征進(jìn)行選擇,保留k個評分最高的特征。

方差分析

分類問題使用f_classif,回歸問題使用f_regression。

f_classif:分類任務(wù)

跟目標(biāo)的分類,將樣本劃分成n個子集,S1,S2,..,Sn,我們希望每個子集的均值μ1,μ2,...,μn不相等。

我們假設(shè)H0:μ1=μ2=...=μn,當(dāng)然我們希望拒絕H0,所以我們希望構(gòu)造出來f最大越好。所以我們可以通過第i個特征xi對分類進(jìn)行預(yù)測。f值越大,預(yù)測值越好。

f_regression:回歸任務(wù)

引用參考:https://blog.csdn.net/jetFlow/article/details/78884619

要計算f_regression中的ff值,我們首先要計算的是,這個就是i號特征和因變量y之間的樣本相關(guān)系數(shù)。

我們計算的?,才是f_regression中的ff值,服從F(1,n?2)F(1,n?2)分布。

ff值越大,i號特征和因變量y之間的相關(guān)性就越大,據(jù)此我們做特征選擇。
?

            
              from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif
from sklearn.datasets import load_iris
# 特征選擇
data = load_iris()
slectKBest = SelectKBest(f_classif,k=2)
dataK = slectKBest.fit_transform(data.data,data.target)
            
          

2.基于學(xué)習(xí)模型的特征排序

針對每個單獨(dú)的特征和響應(yīng)變量建立預(yù)測模型。其實(shí)Pearson相關(guān)系數(shù)等價于線性回歸里的標(biāo)準(zhǔn)化回歸系數(shù)。假如某個特征和響應(yīng)變量之間的關(guān)系是非線性的,可以用基于樹的方法(決策樹、隨機(jī)森林)、或者擴(kuò)展的線性模型等。基于樹的方法比較易于使用,因?yàn)樗麄儗Ψ蔷€性關(guān)系的建模比較好,并且不需要太多的調(diào)試。但要注意過擬合問題,因此樹的深度最好不要太大,再就是運(yùn)用交叉驗(yàn)證
在波士頓房價數(shù)據(jù)集使用sklearn的隨機(jī)森林回歸給出一個單變量選擇的例子:

            
              from sklearn.cross_validation import cross_val_score, ShuffleSplit
from sklearn.datasets import load_boston
from sklearn.ensemble import RandomForestRegressor
 
#Load boston housing dataset as an example
boston = load_boston()
X = boston["data"]
Y = boston["target"]
names = boston["feature_names"]
 
rf = RandomForestRegressor(n_estimators=20, max_depth=4)
scores = []
for i in range(X.shape[1]):
     score = cross_val_score(rf, X[:, i:i+1], Y, scoring="r2",
                              cv=ShuffleSplit(len(X), 3, .3))
     scores.append((round(np.mean(score), 3), names[i]))
print sorted(scores, reverse=True)
            
          

結(jié)果:

            
              [(0.636, ‘LSTAT’), (0.59, ‘RM’), (0.472, ‘NOX’), (0.369, ‘INDUS’), (0.311, ‘PTRATIO’), (0.24, ‘TAX’), (0.24, ‘CRIM’), (0.185, ‘RAD’), (0.16, ‘ZN’), (0.087, ‘B’), (0.062, ‘DIS’), (0.036, ‘CHAS’), (0.027, ‘AGE’)]
            
          

二. 遞歸特征消除(RFE)

遞歸特征消除(Recursive feature elimination)

遞歸特征消除的主要思想是反復(fù)構(gòu)建模型,然后選出最好的(或者最差的)特征(根據(jù)系數(shù)來選),把選出來的特征放到一邊,然后在剩余的特征上重復(fù)這個過程,直到遍歷了所有的特征。在這個過程中被消除的次序就是特征的排序。

RFE的穩(wěn)定性很大程度上取決于迭代時,底層用的哪種模型。比如RFE采用的是普通的回歸(LR),沒有經(jīng)過正則化的回歸是不穩(wěn)定的,那么RFE就是不穩(wěn)定的。假如采用的是Lasso/Ridge,正則化的回歸是穩(wěn)定的,那么RFE就是穩(wěn)定的。

下面的示例使用RFE和logistic回歸算法來選出前三個特征。算法的選擇并不重要,只需要熟練并且一致:

            
              Import the required packages

Import pandas to read csv
Import numpy for array related operations

Import sklearn's feature selection algorithm from sklearn.feature_selection import RFE

Import LogisticRegression for performing chi square test from sklearn.linear_model import LogisticRegression

#URL for loading the dataset
url ="https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-dia?betes/pima-indians-diabetes.data"
#Define the attribute names

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']

#Create pandas data frame by loading the data from URL

dataframe = pandas.read_csv(url, names=names)

#Create array from data values
array = dataframe.values
#Split the data into input and target

X?=?array[:,:8]

Y?=?array[:,8]

#Feature extraction

model = LogisticRegression() 
rfe = RFE(model, 3)

fit = rfe.fit(X, Y)

print("Num?Features:?%d"%?fit.n_features_)?
print("Selected?Features:?%s"%?fit.support_)

print("Feature?Ranking:?%s"%?fit.ranking_)

            
          

3.主成分分析

原理參考:https://blog.csdn.net/program_developer/article/details/80632779

PCA python 代碼實(shí)現(xiàn):

            
              #Python實(shí)現(xiàn)PCA
import numpy as np
def pca(X,k):#k is the components you want
  #mean of each feature
  n_samples, n_features = X.shape
  mean=np.array([np.mean(X[:,i]) for i in range(n_features)])
  #normalization
  norm_X=X-mean
  #scatter matrix
  scatter_matrix=np.dot(np.transpose(norm_X),norm_X)
  #Calculate the eigenvectors and eigenvalues
  eig_val, eig_vec = np.linalg.eig(scatter_matrix)
  eig_pairs = [(np.abs(eig_val[i]), eig_vec[:,i]) for i in range(n_features)]
  # sort eig_vec based on eig_val from highest to lowest
  eig_pairs.sort(reverse=True)
  # select the top k eig_vec
  feature=np.array([ele[1] for ele in eig_pairs[:k]])
  #get new data
  data=np.dot(norm_X,np.transpose(feature))
  return data
 
X = np.array([[-1, 1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
print(pca(X,1))
            
          

上面代碼實(shí)現(xiàn)了對數(shù)據(jù)X進(jìn)行特征的降維。結(jié)果如下:

            
              [[-0.50917706],[-2.40151069],[]-3.7751606],[1.20075534],[2.05572155],[3.42937146]]
            
          

2)用sklearn的PCA

            
              ##用sklearn的PCA
from sklearn.decomposition import PCA
import numpy as np
X = np.array([[-1, 1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca=PCA(n_components=1)pca.fit(X)
print(pca.transform(X)
            
          

相關(guān)博客:

Reference:

(1) 主成分分析(PCA)原理詳解

http://blog.csdn.net/zhongkelee/article/details/44064401

(2) 機(jī)器學(xué)習(xí)之PCA主成分分析 - steed灬 - 博客園

https://www.cnblogs.com/steed/p/7454329.html

(3) 簡單易學(xué)的機(jī)器學(xué)習(xí)算法——主成分分析(PCA)

https://blog.csdn.net/google19890102/article/details/27969459

(4) 機(jī)器學(xué)習(xí)實(shí)戰(zhàn)之PCA - 笨鳥多學(xué) - 博客園

https://www.cnblogs.com/zy230530/p/7074215.html

(5) 機(jī)器學(xué)習(xí)中的數(shù)學(xué)(5)-強(qiáng)大的矩陣奇異值分解(SVD)及其應(yīng)用 - LeftNotEasy - 博客園

http://www.cnblogs.com/LeftNotEasy/archive/2011/01/19/svd-and-applications.html

(6) 從PCA和SVD的關(guān)系拾遺

https://blog.csdn.net/Dark_Scope/article/details/53150883

(7) CodingLabs - PCA的數(shù)學(xué)原理

http://blog.codinglabs.org/articles/pca-tutorial.html

(8) PCA(主成分分析)python實(shí)現(xiàn)

https://www.jianshu.com/p/4528aaa6dc48

(9) 主成分分析PCA(Principal Component Analysis)在sklearn中的應(yīng)用及部分源碼分析

https://www.cnblogs.com/lochan/p/7001907.html


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 陇川县| 临湘市| 石城县| 绵阳市| 岳普湖县| 怀柔区| 嘉定区| 额尔古纳市| 鹤庆县| 长春市| 阜康市| 吉林市| 南汇区| 合山市| 体育| 崇信县| 交口县| 盐亭县| 政和县| 德格县| 利辛县| 甘孜| 富平县| 松潘县| 精河县| 板桥市| 雷波县| 大竹县| 泌阳县| 伊吾县| 四川省| 松潘县| 共和县| 阜南县| 昔阳县| 太原市| 电白县| 武城县| 浦城县| 罗平县| 西贡区|