亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

在Python中實(shí)現(xiàn)機(jī)器學(xué)習(xí)功能的4種方法

XFLY / 2558人閱讀

摘要:在中實(shí)現(xiàn)機(jī)器學(xué)習(xí)功能的種方法來(lái)源愿碼內(nèi)容編輯愿碼連接每個(gè)程序員的故事網(wǎng)站愿碼愿景打造全學(xué)科系統(tǒng)免費(fèi)課程,助力小白用戶初級(jí)工程師成本免費(fèi)系統(tǒng)學(xué)習(xí)低成本進(jìn)階,幫助一線資深工程師成長(zhǎng)并利用自身優(yōu)勢(shì)創(chuàng)造睡后收入。

在Python中實(shí)現(xiàn)機(jī)器學(xué)習(xí)功能的4種方法

來(lái)源 | 愿碼(ChainDesk.CN)內(nèi)容編輯

愿碼Slogan | 連接每個(gè)程序員的故事

網(wǎng)站 | http://chaindesk.cn

愿碼愿景 | 打造全學(xué)科IT系統(tǒng)免費(fèi)課程,助力小白用戶、初級(jí)工程師0成本免費(fèi)系統(tǒng)學(xué)習(xí)、低成本進(jìn)階,幫助BAT一線資深工程師成長(zhǎng)并利用自身優(yōu)勢(shì)創(chuàng)造睡后收入。

官方公眾號(hào) | 愿碼 | 愿碼服務(wù)號(hào) | 區(qū)塊鏈部落

免費(fèi)加入愿碼全思維工程師社群 | 任一公眾號(hào)回復(fù)“愿碼”兩個(gè)字獲取入群二維碼


本文閱讀時(shí)長(zhǎng):13min

在本文中,我們將介紹從數(shù)據(jù)集中選擇要素的不同方法; 并使用Scikit-learn(sklearn)庫(kù)討論特征選擇算法的類型及其在Python中的實(shí)現(xiàn) :

單變量特征選擇

遞歸特征消除(RFE)

主成分分析(PCA)

特征選擇 (feature importance)

單變量特征選擇

統(tǒng)計(jì)測(cè)試可用于選擇與輸出變量具有最強(qiáng)關(guān)系的那些特征。

scikit-learn庫(kù)提供SelectKBest類,可以與一組不同的統(tǒng)計(jì)測(cè)試一起使用,以選擇特定數(shù)量的功能。

以下示例使用chi平方(chi ^ 2)統(tǒng)計(jì)檢驗(yàn)非負(fù)特征來(lái)選擇Pima Indians糖尿病數(shù)據(jù)集中的四個(gè)最佳特征:

#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,:])

每個(gè)屬性的分?jǐn)?shù)和所選的四個(gè)屬性(分?jǐn)?shù)最高的分?jǐn)?shù)):plas,test,mass和age。

每個(gè)功能的分?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)建模型來(lái)工作。它使用模型精度來(lái)識(shí)別哪些屬性(和屬性組合)對(duì)預(yù)測(cè)目標(biāo)屬性的貢獻(xiàn)最大。以下示例使用RFE和邏輯回歸算法來(lái)選擇前三個(gè)特征。算法的選擇并不重要,只要它技巧性和一致性:

#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選擇了前三個(gè)功能,如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ù)簡(jiǎn)化技術(shù)。PCA的一個(gè)屬性是您可以選擇轉(zhuǎn)換結(jié)果中的維數(shù)或主成分?jǐn)?shù)。

在以下示例中,我們使用PCA并選擇三個(gè)主要組件:

#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ù)集(三個(gè)主要組件)與源數(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)督的分類器來(lái)選擇特征的技術(shù)。當(dāng)我們訓(xùn)練分類器(例如決策樹)時(shí),我們會(huì)評(píng)估每個(gè)屬性以創(chuàng)建分裂; 我們可以將此度量用作特征選擇器。讓我們?cè)敿?xì)了解它。

隨機(jī)森林是最受歡迎的 機(jī)器學(xué)習(xí)方法之一,因?yàn)樗鼈兙哂邢鄬?duì)較好的準(zhǔn)確性,穩(wěn)健性和易用性。它們還提供了兩種直接的特征選擇方法 - 平均降低雜質(zhì)平均降低精度

隨機(jī)森林由許多決策樹組成。決策樹中的每個(gè)節(jié)點(diǎn)都是單個(gè)要素上的條件,旨在將數(shù)據(jù)集拆分為兩個(gè),以便類似的響應(yīng)值最終出現(xiàn)在同一個(gè)集合中。選擇(局部)最佳條件的度量稱為雜質(zhì)。對(duì)于分類,它通常是基尼系數(shù)

雜質(zhì)或信息增益/熵,對(duì)于回歸樹,它是方差。因此,當(dāng)訓(xùn)練樹時(shí),可以通過每個(gè)特征減少樹中的加權(quán)雜質(zhì)的程度來(lái)計(jì)算它。對(duì)于森林,可以對(duì)每個(gè)特征的雜質(zhì)減少進(jìn)行平均,并且根據(jù)該度量對(duì)特征進(jìn)行排序。

讓我們看看如何使用隨機(jī)森林分類器進(jìn)行特征選擇,并評(píng)估特征選擇前后分類器的準(zhǔn)確性。我們將使用Otto數(shù)據(jù)集。

該數(shù)據(jù)集描述了超過61,000種產(chǎn)品的93個(gè)模糊細(xì)節(jié),這些產(chǎn)品分為10個(gè)產(chǎn)品類別(例如,時(shí)裝,電子產(chǎn)品等)。輸入屬性是某種不同事件的計(jì)數(shù)。

目標(biāo)是將新產(chǎn)品的預(yù)測(cè)作為10個(gè)類別中每個(gè)類別的概率數(shù)組,并使用多類對(duì)數(shù)損失(也稱為交叉熵)來(lái)評(píng)估模型。

我們將從導(dǎo)入所有庫(kù)開始:

#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)練和測(cè)試數(shù)據(jù); 我們將在訓(xùn)練部分訓(xùn)練我們的數(shù)據(jù)集,測(cè)試部分將用于評(píng)估訓(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

我們還需要添加一個(gè)函數(shù)來(lái)評(píng)估模型的準(zhǔn)確性; 它將預(yù)測(cè)和實(shí)際輸出作為輸入來(lái)計(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個(gè)訓(xùn)練實(shí)例。我們將在我們的示例中使用50000個(gè)實(shí)例,其中我們將使用35,000個(gè)實(shí)例來(lái)訓(xùn)練分類器,并使用15,000個(gè)實(shí)例來(lái)測(cè)試分類器的性能:

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

我們?cè)谶@里注意數(shù)據(jù)大小; 因?yàn)槲覀兊臄?shù)據(jù)集包含大約35000個(gè)具有94個(gè)屬性的訓(xùn)練實(shí)例; 我們的數(shù)據(jù)集的大小非常大。讓我們來(lái)看看:

Shape of the dataset (35000, 94)

Size of Data set before feature selection: 26.32 MB

如您所見,我們的數(shù)據(jù)集中有35000行和94列,超過26 MB數(shù)據(jù)。

在下一個(gè)代碼塊中,我們將配置隨機(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)槲覀儗⒔?em>99%的測(cè)試數(shù)據(jù)分類到正確的類別中。這意味著我們正在對(duì)15,000個(gè)正確類中的14,823個(gè)實(shí)例進(jìn)行分類。

那么,現(xiàn)在我的問題是:我們是否應(yīng)該進(jìn)一步改進(jìn)?好吧,為什么不呢?如果可以的話,我們肯定會(huì)尋求更多的改進(jìn); 在這里,我們將使用功能重要性來(lái)選擇功能。如您所知,在樹木構(gòu)建過程中,我們使用雜質(zhì)測(cè)量來(lái)選擇節(jié)點(diǎn)。選擇具有最低雜質(zhì)的屬性值作為樹中的節(jié)點(diǎn)。我們可以使用類似的標(biāo)準(zhǔn)進(jìn)行特征選擇。我們可以更加重視雜質(zhì)較少的功能,這可以使用sklearn庫(kù)的feature_importances_函數(shù)來(lái)完成。讓我們找出每個(gè)功能的重要性:

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

正如您在此處所看到的,每個(gè)要素都基于其對(duì)最終預(yù)測(cè)的貢獻(xiàn)而具有不同的重要性。

我們將使用這些重要性分?jǐn)?shù)來(lái)排列我們的功能; 在下面的部分中,我們將選擇功能重要性大于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ù)集。在下一個(gè)代碼塊中,我們將轉(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個(gè)功能,這將數(shù)據(jù)庫(kù)的大小從26 MB減少到5.60 MB。這比原始數(shù)據(jù)集減少了約80%。

在下一個(gè)代碼塊中,我們將訓(xùn)練一個(gè)新的隨機(jī)森林分類器,它具有與之前相同的超參數(shù),并在測(cè)試數(shù)據(jù)集上進(jìn)行測(cè)試。讓我們看看修改訓(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)確率,這意味著我們?cè)谡_的類中對(duì)14,996個(gè)實(shí)例進(jìn)行了分類,而之前我們只正確地對(duì)14,823個(gè)實(shí)例進(jìn)行了分類。

這是我們?cè)诠δ苓x擇過程中取得的巨大進(jìn)步; 我們可以總結(jié)下表中的所有結(jié)果:

評(píng)估標(biāo)準(zhǔn) 在選擇特征之前 選擇功能后
功能數(shù)量 94 20
數(shù)據(jù)集的大小 26.32 MB 5.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í)間縮短,最后,我們克服了過度擬合問題,獲得了比以前更高的精度。

如果您發(fā)現(xiàn)這篇文章很有用,記得轉(zhuǎn)發(fā)~

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/43564.html

相關(guān)文章

  • 入門系列之Scikit-learnPython中構(gòu)建機(jī)器學(xué)習(xí)分類器

    摘要:使用該數(shù)據(jù)集,我們將構(gòu)建機(jī)器學(xué)習(xí)模型以使用腫瘤信息來(lái)預(yù)測(cè)腫瘤是惡性的還是良性的。我們將使用函數(shù)來(lái)確定機(jī)器學(xué)習(xí)分類器的準(zhǔn)確性。您已成功構(gòu)建了第一臺(tái)機(jī)器學(xué)習(xí)分類器?,F(xiàn)在,您可以使用在中加載數(shù)據(jù)組織數(shù)據(jù)訓(xùn)練預(yù)測(cè)和評(píng)估機(jī)器學(xué)習(xí)分類器。 歡迎大家前往騰訊云+社區(qū),獲取更多騰訊海量技術(shù)實(shí)踐干貨哦~ 本文由信姜緣 發(fā)表于云+社區(qū)專欄 介紹 機(jī)器學(xué)習(xí)是計(jì)算機(jī)科學(xué)、人工智能和統(tǒng)計(jì)學(xué)的研究領(lǐng)域。機(jī)器學(xué)...

    Null 評(píng)論0 收藏0
  • 機(jī)器學(xué)習(xí)

    摘要:用離散信一文清晰講解機(jī)器學(xué)習(xí)中梯度下降算法包括其變式算法無(wú)論是要解決現(xiàn)實(shí)生活中的難題,還是要?jiǎng)?chuàng)建一款新的軟件產(chǎn)品,我們最終的目標(biāo)都是使其達(dá)到最優(yōu)狀態(tài)。 提高駕駛技術(shù):用GAN去除(愛情)動(dòng)作片中的馬賽克和衣服 作為一名久經(jīng)片場(chǎng)的老司機(jī),早就想寫一些探討駕駛技術(shù)的文章。這篇就介紹利用生成式對(duì)抗網(wǎng)絡(luò)(GAN)的兩個(gè)基本駕駛技能: 1) 去除(愛情)動(dòng)作片中的馬賽克 2) 給(愛情)動(dòng)作片中...

    wums 評(píng)論0 收藏0
  • 【壓力測(cè)試】Mac下進(jìn)行l(wèi)ocust配置和測(cè)試

    摘要:頁(yè)面數(shù)據(jù)說(shuō)明性能測(cè)試參數(shù)請(qǐng)求的類型,例如。當(dāng)前請(qǐng)求失敗的數(shù)量。中間值,單位毫秒,一半的服務(wù)器響應(yīng)時(shí)間低于該值,而另一半高于該值。平均值,單位毫秒,所有請(qǐng)求的平均響應(yīng)時(shí)間。單個(gè)請(qǐng)求的大小,單位字節(jié)。 寫在前面:此文章在通過學(xué)習(xí)、實(shí)踐網(wǎng)絡(luò)資料寫成,相關(guān)鏈接在文章結(jié)尾。 一、簡(jiǎn)介 1、locust是一種可用python編寫腳本的開源壓測(cè)工具(實(shí)質(zhì)是由python下的一些庫(kù)構(gòu)成),可定義用戶行...

    channg 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<