搜尋
首頁後端開發Python教學Python中實現機器學習功能的四種方法介紹

Python中實現機器學習功能的四種方法介紹

Apr 13, 2019 am 11:41 AM
python開發機器學習程式設計語言

這篇文章帶給大家的內容是關於Python中實現機器學習功能的四種方法介紹,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

在本文中,我們將介紹從資料集中選擇要素的不同方法; 並使用Scikit-learn(sklearn)函式庫討論特徵選擇演算法的類型及其在Python中的實作:

  1. 單變量特徵選擇
  2. 遞歸特徵消除(RFE)
  3. 主成分分析(PCA)
  4. 特徵選擇(feature importance)

#單變數特徵選擇

統計檢定可用來選擇與輸出變數具有最強關係的那些特徵。

scikit-learn函式庫提供SelectKBest類,可以與一組不同的統計檢定一起使用,以選擇特定數量的功能。

以下範例使用chi平方(chi ^ 2)統計檢定非負特徵來選擇Pima Indians糖尿病資料集中的四個最佳特徵:

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

每個屬性的分數和所選的四個屬性(分數最高的分數):plas,test,mass和age。

每個函數的分數:

[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透過遞歸刪除屬性並在剩餘的屬性上建立模型來工作。它使用模型精確度來識別哪些屬性(和屬性組合)對預測目標屬性的貢獻最大。以下範例使用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_)

執行後,我們將獲得:

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_數組中標記為True,並在ranking_數組中標記為選項1。

主成分分析(PCA)

PCA使用線性代數將資料集轉換為壓縮形式。通常,它被認為是數據簡化技術。 PCA的一個屬性是您可以選擇轉換結果中的維度或主成分數。

在以下範例中,我們使用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_)

您可以看到轉換後的資料集(三個主要元件)與來源資料幾乎沒有相似之處:

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)

特徵重要性是用來使用訓練有監督的分類器來選擇特徵的技術。當我們訓練分類器(例如決策樹)時,我們會評估每個屬性以建立分裂; 我們可以將此測量值用作特徵選擇器。讓我們詳細了解它。

隨機森林是最受歡迎的 機器學習方法之一,因為它們具有相對較好的準確性,穩健性和易用性。它們還提供了兩種直接的特徵選擇方法 - 平均降低雜質平均降低精度

隨機森林由許多決策樹組成。決策樹中的每個節點都是單一要素上的條件,旨在將資料集拆分為兩個,以便類似的回應值最終出現在同一個集合中。選擇(局部)最佳條件的量測稱為雜質。對於分類,它通常是基尼係數

雜質或資訊增益/熵,對於迴歸樹,它是變異數。因此,當訓練樹時,可以透過每個特徵減少樹中的加權雜質的程度來計算它。對於森林,可以對每個特徵的雜質減少進行平均,並且根據該度量對特徵進行排序。

讓我們看看如何使用隨機森林分類器進行特徵選擇,並評估特徵選擇前後分類器的準確性。我們將使用Otto資料集。

此資料集描述了超過61,000種產品的93個模糊細節,這些產品分為10個產品類別(例如,時裝,電子產品等) 。輸入屬性是某種不同事件的計數。

目標是將新產品的預測作為10個類別中每個類別的機率數組,並使用多類別對數損失(也稱為交叉熵)來評估模型。

我們將從導入所有庫開始:

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

讓我們定義一種方法將資料集拆分為訓練和測試資料; 我們將在訓練部分訓練我們的資料集,測試部分將用於評估訓練模型:

#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

我們還需要添加一個函數來評估模型的準確性; 它將預測和實際輸出作為輸入來計算百分比準確度:

#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

這是載入資料集的時間。我們將載入train.csv檔案; 此檔案包含超過61,000個訓練實例。我們將在我們的範例中使用50000個實例,其中我們將使用35,000個實例來訓練分類器,並使用15,000個實例來測試分類器的效能:

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

我們在這裡注意到資料大小; 因為我們的資料集包含大約35000個具有94個屬性的訓練實例; 我們的資料集的大小非常大。讓我們來看看:

Shape of the dataset (35000, 94)

Size of Data set before feature selection: 26.32 MB

如您所見,我們的資料集中有35000行和94列,超過26 MB資料。

在下一個程式碼區塊中,我們將配置隨機林分類器; 我們將使用250棵樹,最大深度為30,隨機要素的數量為7.其他超參數將是sklearn的預設值:

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

我们模型的准确性是:

特征选择前的模型精度为98.82

正如您所看到的,我们正在获得非常好的准确性,因为我们将近99%的测试数据分类到正确的类别中。这意味着我们正在对15,000个正确类中的14,823个实例进行分类。

那么,现在我的问题是:我们是否应该进一步改进?好吧,为什么不呢?如果可以的话,我们肯定会寻求更多的改进; 在这里,我们将使用功能重要性来选择功能。如您所知,在树木构建过程中,我们使用杂质测量来选择节点。选择具有最低杂质的属性值作为树中的节点。我们可以使用类似的标准进行特征选择。我们可以更加重视杂质较少的功能,这可以使用sklearn库的feature_importances_函数来完成。让我们找出每个功能的重要性:

#Once我们培养的模型中,我们的排名将所有功能的功能拉链(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)

正如您在此处所看到的,每个要素都基于其对最终预测的贡献而具有不同的重要性。

我们将使用这些重要性分数来排列我们的功能; 在下面的部分中,我们将选择功能重要性大于0.01的模型训练功能:

#Select features which have higher contribution in the final prediction

sfm = SelectFromModel(clf, threshold=0.01) sfm.fit(Xtrain,ytrain)

在这里,我们将根据所选的特征属性转换输入数据集。在下一个代码块中,我们将转换数据集。然后,我们将检查新数据集的大小和形状:

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

你看到数据集的形状了吗?在功能选择过程之后,我们只剩下20个功能,这将数据库的大小从26 MB减少到5.60 MB。这比原始数据集减少了约80%

在下一个代码块中,我们将训练一个新的随机森林分类器,它具有与之前相同的超参数,并在测试数据集上进行测试。让我们看看修改训练集后得到的准确度:

#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

你能看到!! 我们使用修改后的数据集获得了99.97%的准确率,这意味着我们在正确的类中对14,996个实例进行了分类,而之前我们只正确地对14,823个实例进行了分类。

这是我们在功能选择过程中取得的巨大进步; 我们可以总结下表中的所有结果:

评估标准 在选择特征之前 选择功能后
功能数量 94 20
数据集的大小 26.32 MB 5.60 MB
训练时间 2.91秒 1.71秒
准确性 98.82% 99.97%

上表显示了特征选择的实际优点。您可以看到我们显着减少了要素数量,从而降低了数据集的模型复杂性和维度。尺寸减小后我们的训练时间缩短,最后,我们克服了过度拟合问题,获得了比以前更高的精度。

以上是Python中實現機器學習功能的四種方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:segmentfault。如有侵權,請聯絡admin@php.cn刪除
您如何切成python陣列?您如何切成python陣列?May 01, 2025 am 12:18 AM

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

在什麼情況下,列表的表現比數組表現更好?在什麼情況下,列表的表現比數組表現更好?May 01, 2025 am 12:06 AM

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

如何將Python數組轉換為Python列表?如何將Python數組轉換為Python列表?May 01, 2025 am 12:05 AM

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

當Python中存在列表時,使用數組的目的是什麼?當Python中存在列表時,使用數組的目的是什麼?May 01, 2025 am 12:04 AM

choosearraysoverlistsinpythonforbetterperformanceandmemoryfliceSpecificScenarios.1)largenumericaldatasets:arraysreducememoryusage.2)績效 - 臨界雜貨:arraysoffersoffersOffersOffersOffersPoostSfoostSforsssfortasssfortaskslikeappensearch orearch.3)testessenforcety:arraysenforce:arraysenforc

說明如何通過列表和數組的元素迭代。說明如何通過列表和數組的元素迭代。May 01, 2025 am 12:01 AM

在Python中,可以使用for循環、enumerate和列表推導式遍歷列表;在Java中,可以使用傳統for循環和增強for循環遍歷數組。 1.Python列表遍歷方法包括:for循環、enumerate和列表推導式。 2.Java數組遍歷方法包括:傳統for循環和增強for循環。

什麼是Python Switch語句?什麼是Python Switch語句?Apr 30, 2025 pm 02:08 PM

本文討論了版本3.10中介紹的Python的新“匹配”語句,該語句與其他語言相同。它增強了代碼的可讀性,並為傳統的if-elif-el提供了性能優勢

Python中有什麼例外組?Python中有什麼例外組?Apr 30, 2025 pm 02:07 PM

Python 3.11中的異常組允許同時處理多個異常,從而改善了並發方案和復雜操作中的錯誤管理。

Python中的功能註釋是什麼?Python中的功能註釋是什麼?Apr 30, 2025 pm 02:06 PM

Python中的功能註釋將元數據添加到函數中,以進行類型檢查,文檔和IDE支持。它們增強了代碼的可讀性,維護,並且在API開發,數據科學和圖書館創建中至關重要。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器