python可以实现哪些功能_Python中实现机器学习功能的四种方法介绍
本篇文章給大家?guī)淼膬?nèi)容是關(guān)于Python中實(shí)現(xiàn)機(jī)器學(xué)習(xí)功能的四種方法介紹,有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對你有所幫助。
在本文中,我們將介紹從數(shù)據(jù)集中選擇要素的不同方法; 并使用Scikit-learn(sklearn)庫討論特征選擇算法的類型及其在Python中的實(shí)現(xiàn) :單變量特征選擇
遞歸特征消除(RFE)
主成分分析(PCA)
特征選擇 (feature importance)
單變量特征選擇
統(tǒng)計(jì)測試可用于選擇與輸出變量具有最強(qiáng)關(guān)系的那些特征。
scikit-learn庫提供SelectKBest類,可以與一組不同的統(tǒng)計(jì)測試一起使用,以選擇特定數(shù)量的功能。
以下示例使用chi平方(chi ^ 2)統(tǒng)計(jì)檢驗(yàn)非負(fù)特征來選擇Pima Indians糖尿病數(shù)據(jù)集中的四個最佳特征:#Feature Extraction with Univariate Statistical Tests (Chi-squared for classification)
#Import the required packages
#Import pandas to read csv import pandas
#Import numpy for array related operations import numpy
#Import sklearn's feature selection algorithm
from sklearn.feature_selection import SelectKBest
#Import chi2 for performing chi square test from sklearn.feature_selection import chi2
#URL for loading the dataset
url ="https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians diabetes/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[:,0:8]
Y = array[:,8]
#We will select the features using chi square
test = SelectKBest(score_func=chi2, k=4)
#Fit the function for ranking the features by score
fit = test.fit(X, Y)
#Summarize scores numpy.set_printoptions(precision=3) print(fit.scores_)
#Apply the transformation on to dataset
features = fit.transform(X)
#Summarize selected features print(features[0:5,:])
每個屬性的分?jǐn)?shù)和所選的四個屬性(分?jǐn)?shù)最高的分?jǐn)?shù)):plas,test,mass和age。
每個功能的分?jǐn)?shù):[111.52 1411.887 17.605 53.108 2175.565 127.669 5.393
181.304]
特色:[[148. 0. 33.6 50. ]
[85. 0. 26.6 31. ]
[183. 0. 23.3 32. ]
[89. 94. 28.1 21. ]
[137. 168. 43.1 33. ]]
遞歸特征消除(RFE)
RFE通過遞歸刪除屬性并在剩余的屬性上構(gòu)建模型來工作。它使用模型精度來識別哪些屬性(和屬性組合)對預(yù)測目標(biāo)屬性的貢獻(xiàn)最大。以下示例使用RFE和邏輯回歸算法來選擇前三個特征。算法的選擇并不重要,只要它技巧性和一致性:#Import the required packages
#Import pandas to read csv import pandas
#Import numpy for array related operations import numpy
#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[:,0: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_)
執(zhí)行后,我們將獲得:Num Features: 3
Selected Features: [ True False False False False True True False]
Feature Ranking: [1 2 3 5 6 1 1 4]
您可以看到RFE選擇了前三個功能,如preg,mass和pedi。這些在support_數(shù)組中標(biāo)記為True,并在ranking_數(shù)組中標(biāo)記為選項(xiàng)1。
主成分分析(PCA)
PCA使用線性代數(shù)將數(shù)據(jù)集轉(zhuǎn)換為壓縮形式。通常,它被認(rèn)為是數(shù)據(jù)簡化技術(shù)。PCA的一個屬性是您可以選擇轉(zhuǎn)換結(jié)果中的維數(shù)或主成分?jǐn)?shù)。
在以下示例中,我們使用PCA并選擇三個主要組件:#Import the required packages
#Import pandas to read csv import pandas
#Import numpy for array related operations import numpy
#Import sklearn's PCA algorithm
from sklearn.decomposition import PCA
#URL for loading the dataset
url =
"https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians diabetes/pima-indians-diabetes.data"
#Define the attribute names
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
#Create array from data values
array = dataframe.values
#Split the data into input and target
X = array[:,0:8]
Y = array[:,8]
#Feature extraction
pca = PCA(n_components=3) fit = pca.fit(X)
#Summarize components
print("Explained Variance: %s") % fit.explained_variance_ratio_
print(fit.components_)
您可以看到轉(zhuǎn)換后的數(shù)據(jù)集(三個主要組件)與源數(shù)據(jù)幾乎沒有相似之處:Explained Variance: [ 0.88854663 0.06159078 0.02579012]
[[ -2.02176587e-03 9.78115765e-02 1.60930503e-02 6.07566861e-02
9.93110844e-01 1.40108085e-02 5.37167919e-04 -3.56474430e-03]
[ -2.26488861e-02 -9.72210040e-01 -1.41909330e-01 5.78614699e-02 9.46266913e-02 -4.69729766e-02 -8.16804621e-04 -1.40168181e-01
[ -2.24649003e-02 1.43428710e-01 -9.22467192e-01 -3.07013055e-01 2.09773019e-02 -1.32444542e-01 -6.39983017e-04 -1.25454310e-01]]
特征選擇 (feature importance)
特征重要性是用于使用訓(xùn)練有監(jiān)督的分類器來選擇特征的技術(shù)。當(dāng)我們訓(xùn)練分類器(例如決策樹)時(shí),我們會評估每個屬性以創(chuàng)建分裂; 我們可以將此度量用作特征選擇器。讓我們詳細(xì)了解它。
隨機(jī)森林是最受歡迎的 機(jī)器學(xué)習(xí)方法之一,因?yàn)樗鼈兙哂邢鄬^好的準(zhǔn)確性,穩(wěn)健性和易用性。它們還提供了兩種直接的特征選擇方法 - 平均降低雜質(zhì)和平均降低精度。
隨機(jī)森林由許多決策樹組成。決策樹中的每個節(jié)點(diǎn)都是單個要素上的條件,旨在將數(shù)據(jù)集拆分為兩個,以便類似的響應(yīng)值最終出現(xiàn)在同一個集合中。選擇(局部)最佳條件的度量稱為雜質(zhì)。對于分類,它通常是基尼系數(shù)
雜質(zhì)或信息增益/熵,對于回歸樹,它是方差。因此,當(dāng)訓(xùn)練樹時(shí),可以通過每個特征減少樹中的加權(quán)雜質(zhì)的程度來計(jì)算它。對于森林,可以對每個特征的雜質(zhì)減少進(jìn)行平均,并且根據(jù)該度量對特征進(jìn)行排序。
讓我們看看如何使用隨機(jī)森林分類器進(jìn)行特征選擇,并評估特征選擇前后分類器的準(zhǔn)確性。我們將使用Otto數(shù)據(jù)集。
該數(shù)據(jù)集描述了超過61,000種產(chǎn)品的93個模糊細(xì)節(jié),這些產(chǎn)品分為10個產(chǎn)品類別(例如,時(shí)裝,電子產(chǎn)品等)。輸入屬性是某種不同事件的計(jì)數(shù)。
目標(biāo)是將新產(chǎn)品的預(yù)測作為10個類別中每個類別的概率數(shù)組,并使用多類對數(shù)損失(也稱為交叉熵)來評估模型。
我們將從導(dǎo)入所有庫開始:#Import the supporting libraries
#Import pandas to load the dataset from csv file
from pandas import read_csv
#Import numpy for array based operations and calculations
import numpy as np
#Import Random Forest classifier class from sklearn
from sklearn.ensemble import RandomForestClassifier
#Import feature selector class select model of sklearn
from sklearn.feature_selection
import SelectFromModel
np.random.seed(1)
讓我們定義一種方法將數(shù)據(jù)集拆分為訓(xùn)練和測試數(shù)據(jù); 我們將在訓(xùn)練部分訓(xùn)練我們的數(shù)據(jù)集,測試部分將用于評估訓(xùn)練模型:#Function to create Train and Test set from the original dataset def getTrainTestData(dataset,split):
np.random.seed(0) training = [] testing = []
np.random.shuffle(dataset) shape = np.shape(dataset)
trainlength = np.uint16(np.floor(split*shape[0]))
for i in range(trainlength): training.append(dataset[i])
for i in range(trainlength,shape[0]): testing.append(dataset[i])
training = np.array(training) testing = np.array(testing)
return training,testing
我們還需要添加一個函數(shù)來評估模型的準(zhǔn)確性; 它將預(yù)測和實(shí)際輸出作為輸入來計(jì)算百分比準(zhǔn)確度:#Function to evaluate model performance
def getAccuracy(pre,ytest): count = 0
for i in range(len(ytest)):
if ytest[i]==pre[i]: count+=1
acc = float(count)/len(ytest)
return acc
這是加載數(shù)據(jù)集的時(shí)間。我們將加載train.csv文件; 此文件包含超過61,000個訓(xùn)練實(shí)例。我們將在我們的示例中使用50000個實(shí)例,其中我們將使用35,000個實(shí)例來訓(xùn)練分類器,并使用15,000個實(shí)例來測試分類器的性能:#Load dataset as pandas data frame
data = read_csv('train.csv')
#Extract attribute names from the data frame
feat = data.keys()
feat_labels = feat.get_values()
#Extract data values from the data frame
dataset = data.values
#Shuffle the dataset
np.random.shuffle(dataset)
#We will select 50000 instances to train the classifier
inst = 50000
#Extract 50000 instances from the dataset
dataset = dataset[0:inst,:]
#Create Training and Testing data for performance evaluation
train,test = getTrainTestData(dataset, 0.7)
#Split data into input and output variable with selected features
Xtrain = train[:,0:94] ytrain = train[:,94] shape = np.shape(Xtrain)
print("Shape of the dataset ",shape)
#Print the size of Data in MBs
print("Size of Data set before feature selection: %.2f MB"%(Xtrain.nbytes/1e6))
我們在這里注意數(shù)據(jù)大小; 因?yàn)槲覀兊臄?shù)據(jù)集包含大約35000個具有94個屬性的訓(xùn)練實(shí)例; 我們的數(shù)據(jù)集的大小非常大。讓我們來看看:Shape of the dataset (35000, 94)
Size of Data set before feature selection: 26.32 MB
如您所見,我們的數(shù)據(jù)集中有35000行和94列,超過26 MB數(shù)據(jù)。
在下一個代碼塊中,我們將配置隨機(jī)林分類器; 我們將使用250棵樹,最大深度為30,隨機(jī)要素的數(shù)量為7.其他超參數(shù)將是sklearn的默認(rèn)值:#Lets select the test data for model evaluation purpose
Xtest = test[:,0:94] ytest = test[:,94]
#Create a random forest classifier with the following Parameters
trees = 250
max_feat = 7
max_depth = 30
min_sample = 2
clf = RandomForestClassifier(n_estimators=trees,
max_features=max_feat,
max_depth=max_depth,
min_samples_split= min_sample, random_state=0,
n_jobs=-1)
#Train the classifier and calculate the training time
import time
start = time.time() clf.fit(Xtrain, ytrain) end = time.time()
#Lets Note down the model training time
print("Execution time for building the Tree is: %f"%(float(end)- float(start)))
pre = clf.predict(Xtest)
Let's see how much time is required to train the model on the training dataset:
Execution time for building the Tree is: 2.913641
#Evaluate the model performance for the test data
acc = getAccuracy(pre, ytest)
print("Accuracy of model before feature selection is %.2f"%(100*acc))
我們模型的準(zhǔn)確性是:
特征選擇前的模型精度為98.82
正如您所看到的,我們正在獲得非常好的準(zhǔn)確性,因?yàn)槲覀儗⒔?9%的測試數(shù)據(jù)分類到正確的類別中。這意味著我們正在對15,000個正確類中的14,823個實(shí)例進(jìn)行分類。
那么,現(xiàn)在我的問題是:我們是否應(yīng)該進(jìn)一步改進(jìn)?好吧,為什么不呢?如果可以的話,我們肯定會尋求更多的改進(jìn); 在這里,我們將使用功能重要性來選擇功能。如您所知,在樹木構(gòu)建過程中,我們使用雜質(zhì)測量來選擇節(jié)點(diǎn)。選擇具有最低雜質(zhì)的屬性值作為樹中的節(jié)點(diǎn)。我們可以使用類似的標(biāo)準(zhǔn)進(jìn)行特征選擇。我們可以更加重視雜質(zhì)較少的功能,這可以使用sklearn庫的feature_importances_函數(shù)來完成。讓我們找出每個功能的重要性:
#Once我們培養(yǎng)的模型中,我們的排名將所有功能的功能在拉鏈(feat_labels,clf.feature_importances_):print(feature)
('id', 0.33346650420175183)
('feat_1', 0.0036186958628801214)
('feat_2', 0.0037243050888530957)
('feat_3', 0.011579217472062748)
('feat_4', 0.010297382675187445)
('feat_5', 0.0010359139416194116)
('feat_6', 0.00038171336038056165)
('feat_7', 0.0024867672489765021)
('feat_8', 0.0096689721610546085)
('feat_9', 0.007906150362995093)
('feat_10', 0.0022342480802130366)
正如您在此處所看到的,每個要素都基于其對最終預(yù)測的貢獻(xiàn)而具有不同的重要性。
我們將使用這些重要性分?jǐn)?shù)來排列我們的功能; 在下面的部分中,我們將選擇功能重要性大于0.01的模型訓(xùn)練功能:#Select features which have higher contribution in the final prediction
sfm = SelectFromModel(clf, threshold=0.01) sfm.fit(Xtrain,ytrain)
在這里,我們將根據(jù)所選的特征屬性轉(zhuǎn)換輸入數(shù)據(jù)集。在下一個代碼塊中,我們將轉(zhuǎn)換數(shù)據(jù)集。然后,我們將檢查新數(shù)據(jù)集的大小和形狀:#Transform input dataset
Xtrain_1 = sfm.transform(Xtrain) Xtest_1 = sfm.transform(Xtest)
#Let's see the size and shape of new dataset print("Size of Data set before feature selection: %.2f MB"%(Xtrain_1.nbytes/1e6))
shape = np.shape(Xtrain_1)
print("Shape of the dataset ",shape)
Size of Data set before feature selection: 5.60 MB Shape of the dataset (35000, 20)
你看到數(shù)據(jù)集的形狀了嗎?在功能選擇過程之后,我們只剩下20個功能,這將數(shù)據(jù)庫的大小從26 MB減少到5.60 MB。這比原始數(shù)據(jù)集減少了約80%。
在下一個代碼塊中,我們將訓(xùn)練一個新的隨機(jī)森林分類器,它具有與之前相同的超參數(shù),并在測試數(shù)據(jù)集上進(jìn)行測試。讓我們看看修改訓(xùn)練集后得到的準(zhǔn)確度:#Model training time
start = time.time() clf.fit(Xtrain_1, ytrain) end = time.time()
print("Execution time for building the Tree is: %f"%(float(end)- float(start)))
#Let's evaluate the model on test data
pre = clf.predict(Xtest_1) count = 0
acc2 = getAccuracy(pre, ytest)
print("Accuracy after feature selection %.2f"%(100*acc2))
Execution time for building the Tree is: 1.711518 Accuracy after feature selection 99.97
你能看到!! 我們使用修改后的數(shù)據(jù)集獲得了99.97%的準(zhǔn)確率,這意味著我們在正確的類中對14,996個實(shí)例進(jìn)行了分類,而之前我們只正確地對14,823個實(shí)例進(jìn)行了分類。
這是我們在功能選擇過程中取得的巨大進(jìn)步; 我們可以總結(jié)下表中的所有結(jié)果:評估標(biāo)準(zhǔn)在選擇特征之前選擇功能后功能數(shù)量9420
數(shù)據(jù)集的大小26.32 MB5.60 MB
訓(xùn)練時(shí)間2.91秒1.71秒
準(zhǔn)確性98.82%99.97%
上表顯示了特征選擇的實(shí)際優(yōu)點(diǎn)。您可以看到我們顯著減少了要素?cái)?shù)量,從而降低了數(shù)據(jù)集的模型復(fù)雜性和維度。尺寸減小后我們的訓(xùn)練時(shí)間縮短,最后,我們克服了過度擬合問題,獲得了比以前更高的精度。
以上就是Python中實(shí)現(xiàn)機(jī)器學(xué)習(xí)功能的四種方法介紹的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
本文轉(zhuǎn)載于:segmentfault,如有侵犯,請聯(lián)系a@php.cn刪除
總結(jié)
以上是生活随笔為你收集整理的python可以实现哪些功能_Python中实现机器学习功能的四种方法介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android 大视图风格通知栏,And
- 下一篇: python实战项目书 题库系统_Pyt