Python與Scikit-Learn的機器學習探索詳解

黄舟
發布: 2017-10-17 10:24:29
原創
1723 人瀏覽過

這篇文章主要介紹了基於Python和Scikit-Learn的機器學習探索的相關內容,小編覺得還挺不錯的,這裡分享給大家,供需要的朋友學習和參考。

你好,%用戶名%!

我叫Alex,在機器學習和網路圖分析(主要是理論)有所涉獵。我同時在為一家俄羅斯行動電信商開發大數據產品。這是我第一次在網路上寫文章,不喜勿噴。

現在,很多人想開發高效率的演算法以及參加機器學習的競賽。所以他們過來問我:「該如何開始?」。一段時間以前,我在一個俄羅斯聯邦政府的下屬機構中領導了媒體和社群網路大數據分析工具的開發。我仍然有一些我團隊使用過的文檔,我樂意與你們分享。前提是讀者已經有很好的數學和機器學習的知識(我的團隊主要由MIPT(莫斯科物理與技術大學)和數據分析學院的畢業生組成)。

這篇文章是對資料科學的簡介,這門學科最近太火了。機器學習的競賽也越來越多(如,Kaggle, TudedIT),而且他們的資金通常很可觀。

R和Python是提供給資料科學家的最常用的兩種工具。每一個工具都有其優缺點,但Python最近在各方面都有所勝出(僅為鄙人愚見,雖然我兩者都用)。這一切的發生是因為Scikit-Learn函式庫的騰空出世,它包含有完善的文件和豐富的機器學習演算法。
請注意,我們將主要在這篇文章中探討機器學習演算法。通常用Pandas套件去進行主資料分析會比較好,而且這很容易你自己完成。所以,讓我們集中精力在實現上。為了確定性,我們假設有一個特徵-物件矩陣作為輸入,被存在一個*.csv檔案中。

資料載入

#首先,資料要載入到記憶體中,才能對其操作。 Scikit-Learn函式庫在它的實作用使用了NumPy數組,所以我們會用NumPy來載入*.csv檔。讓我們從UCI Machine Learning Repository下載其中一個資料集。


import numpy as np
import urllib
# url with dataset
url = “http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data”
# download the file
raw_data = urllib.urlopen(url)
# load the CSV file as a numpy matrix
dataset = np.loadtxt(raw_data, delimiter=“,”)
# separate the data from the target attributes
X = dataset[:,0:7]
y = dataset[:,8]
登入後複製

我們將在下面所有的例子裡使用這個資料組,換言之,使用X特徵物數組和y目標變數的值。

資料標準化

#我們都知道大多數的梯度方法(幾乎所有的機器學習演算法都基於此)對於資料的縮放很敏感。因此,在運行演算法之前,我們應該進行標準化,或所謂的規格化。標準化包括取代所有特徵的名義值,讓它們每一個的值在0和1之間。而對於規格化,它包括資料的預處理,使得每個特徵的值有0和1的離差。 Scikit-Learn函式庫已經為其提供了對應的函數。


from sklearn
import metrics
from sklearn.ensemble
import ExtraTreesClassifier
model = ExtraTreesClassifier()
model.fit(X, y)# display the relative importance of each attribute
print(model.feature_importances_)
登入後複製
登入後複製

特徵的選取

#毫無疑問,解決一個問題最重要的是是恰當選取特徵、甚至創造特徵的能力。這叫做特徵選取和特徵工程。雖然特徵工程是一個相當有創意的過程,有時候更多的是靠直覺和專業的知識,但對於特徵的選取,已經有許多的演算法可供直接使用。如樹演算法就可以計算特徵的資訊量。


from sklearn
import metrics
from sklearn.ensemble
import ExtraTreesClassifier
model = ExtraTreesClassifier()
model.fit(X, y)# display the relative importance of each attribute
print(model.feature_importances_)
登入後複製
登入後複製

其他所有的方法都是基於對特徵子集的高效搜索,從而找到最好的子集,意味著演化了的模型在這個子集上有最好的品質。遞歸特徵消除演算法(RFE)是這些搜尋演算法的其中之一,Scikit-Learn函式庫同樣也有提供。


from sklearn.feature_selection
import RFE
from sklearn.linear_model
import LogisticRegression
model = LogisticRegression()# create the RFE model and select 3 attributes
rfe = RFE(model, 3)
rfe = rfe.fit(X, y)# summarize the selection of the attributes
print(rfe.support_)
print(rfe.ranking_)
登入後複製

演算法的開發

正像我說的,Scikit-Learn函式庫已經實作了所有基本機器學習的演算法。讓我來瞧一瞧它們中的一些。

邏輯迴歸

#大多數情況下用來解決分類問題(二元分類),但多類別的分類(所謂的一對多方法)也適用。這個演算法的優點是對於每一個輸出的物件都有一個對應類別的機率。


from sklearn
import metrics
from sklearn.linear_model
import LogisticRegression
model = LogisticRegression()
model.fit(X, y)
print(model)# make predictions
expected = y
predicted = model.predict(X)# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))
登入後複製

#樸素貝葉斯

它也是最有名的機器學習的演算法之一,它的主要任務是恢復訓練樣本的資料分佈密度。這個方法通常在多類別的分類問題上表現的很好。


from sklearn
import metrics
from sklearn.naive_bayes
import GaussianNB
model = GaussianNB()
model.fit(X, y)
print(model)# make predictions
expected = y
predicted = model.predict(X)# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))
登入後複製

k-最近鄰

kNN(k-最近鄰)方法通常用於一個更複雜分類演算法的一部分。例如,我們可以用它的估計值做為一個物件的特徵。有時候,一個簡單的kNN


from sklearn
import metrics
from sklearn.neighbors
import KNeighborsClassifier# fit a k - nearest neighbor model to the data
model = KNeighborsClassifier()
model.fit(X, y)
print(model)# make predictions
expected = y
predicted = model.predict(X)# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))
登入後複製

#決策樹
##

分类和回归树(CART)经常被用于这么一类问题,在这类问题中对象有可分类的特征且被用于回归和分类问题。决策树很适用于多类分类。


from sklearn
import metrics
from sklearn.tree
import DecisionTreeClassifier# fit a CART model to the data
model = DecisionTreeClassifier()
model.fit(X, y)
print(model)# make predictions
expected = y
predicted = model.predict(X)# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))
登入後複製

支持向量机

SVM(支持向量机)是最流行的机器学习算法之一,它主要用于分类问题。同样也用于逻辑回归,SVM在一对多方法的帮助下可以实现多类分类。


from sklearn import metrics
from sklearn.svm import SVC
# fit a SVM model to the data
model = SVC()
model.fit(X, y)
print(model)
# make predictions
expected = y
predicted = model.predict(X)
# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))
登入後複製

除了分类和回归问题,Scikit-Learn还有海量的更复杂的算法,包括了聚类, 以及建立混合算法的实现技术,如Bagging和Boosting。

如何优化算法的参数

在编写高效的算法的过程中最难的步骤之一就是正确参数的选择。一般来说如果有经验的话会容易些,但无论如何,我们都得寻找。幸运的是Scikit-Learn提供了很多函数来帮助解决这个问题。

作为一个例子,我们来看一下规则化参数的选择,在其中不少数值被相继搜索了:


import numpy as np
from sklearn.linear_model
import Ridge
from sklearn.grid_search
import GridSearchCV# prepare a range of alpha values to test
alphas = np.array([1, 0.1, 0.01, 0.001, 0.0001, 0])# create and fit a ridge regression model, testing each alpha
model = Ridge()
grid = GridSearchCV(estimator = model, param_grid = dict(alpha = alphas))
grid.fit(X, y)
print(grid)# summarize the results of the grid search
print(grid.best_score_)
print(grid.best_estimator_.alpha)
登入後複製

有时候随机地从既定的范围内选取一个参数更为高效,估计在这个参数下算法的质量,然后选出最好的。


import numpy as np
from scipy.stats
import uniform as sp_rand
from sklearn.linear_model
import Ridge
from sklearn.grid_search
import RandomizedSearchCV# prepare a uniform distribution to sample
for the alpha parameter
param_grid = {‘
  alpha': sp_rand()
}#
create and fit a ridge regression model, testing random alpha values
model = Ridge()
rsearch = RandomizedSearchCV(estimator = model, param_distributions = param_grid, n_iter = 100)
rsearch.fit(X, y)
print(rsearch)# summarize the results of the random parameter search
print(rsearch.best_score_)
print(rsearch.best_estimator_.alpha)
登入後複製

至此我们已经看了整个使用Scikit-Learn库的过程,除了将结果再输出到一个文件中。这个就作为你的一个练习吧,和R相比Python的一大优点就是它有很棒的文档说明。

总结

以上是Python與Scikit-Learn的機器學習探索詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!