[Python & Machine Learning] 學習筆記之scikit-learn機器學習庫

來源:互聯網
上載者:User

標籤:

1. scikit-learn介紹

  scikit-learn是Python的一個開源機器學習模組,它建立在NumPy,SciPy和matplotlib模組之上。值得一提的是,scikit-learn最先是由David Cournapeau在2007年發起的一個Google Summer of Code項目,從那時起這個項目就已經擁有很多的貢獻者了,而且該項目目前為止也是由一個志願者團隊在維護著。

  scikit-learn最大的特點就是,為使用者提供各種機器學習演算法介面,可以讓使用者簡單、高效地進行資料採礦和資料分析。

  scikit-learn首頁:scikit-learn homepage

2. scikit-learn安裝

  scikit-learn的安裝方法有很多種,而且也是適用於各種主流作業系統,scikit-learn首頁上也分別詳細地介紹了在不同作業系統下的三種安裝方法,具體安裝詳情請移步至 installing scikit-learn。

  在這裡,首先向大家推薦一款學習Python的強大的開發環境python(x,y)。python(x,y)是一個基於python的科學計算軟體包,它包含整合式開發環境Eclipse和Python開發外掛程式pydev、資料互動式編輯和視覺化檢視spyder,而且還內嵌了Python的基礎資料庫numpy和進階數學庫scipy、3D視覺化檢視集MayaVi、Python介面開發庫PyQt、Python與C/C++混合編譯器SWIG。除此之外,python(x,y)配備了豐富齊全的協助文檔,非常方便科研人員使用。

  對於像樓主這樣,在學校習慣了用Matlab模擬搞科研的學生而言,python(x,y)是學習Python的一個絕佳選擇,其中內嵌的spyder提供了類似於Matlab的互動介面,可以很方便地使用。python(x,y)的下載請點擊這裡:python(x,y)下載。

  由於scikit-learn是基於NumPy、SciPy和matplotlib模組的,所以在安裝scikit-learn之前必須要安裝這3個模組,這就很麻煩。但是,如果你提前像樓主這樣安裝了python(x,y),它本身已經包含上述的模組,你只需下載與你匹配的scikit-learn版本,直接點擊安裝即可。

  scikit-learn各種版本下載:scikit-learn下載。

3. scikit-learn載入資料集

  scikit-learn內包含了常用的機器學習資料集,比如做分類的iris和digit資料集,用於迴歸的經典資料集Boston house prices。

  scikit-learn載入資料集執行個體:

from sklearn import datasetsiris = datasets.load_iris()

  scikit-learn載入的資料集是以類似於字典的形式存放的,該對象中包含了所有有關該資料的資料資訊(甚至還有參考文獻)。其中的資料值統一存放在.data的成員中,比如我們要將iris資料顯示出來,只需顯示iris的data成員:

print iris.data

  資料都是以n維(n個特徵)矩陣形式存放和展現,iris資料中每個執行個體有4維特徵,分別為:sepal length、sepal width、petal length和petal width。顯示iris資料:

[[ 5.1  3.5  1.4  0.2] [ 4.9  3.   1.4  0.2]    ... ... [ 5.9  3.   5.1  1.8]]

  如果是對於監督學習,比如分類問題,資料中會包含對應的分類結果,其存在.target成員中:

print iris.target

  對於iris資料而言,就是各個執行個體的分類結果:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
4. scikit-learn學習和預測

  scikit-learn提供了各種機器學習演算法的介面,允許使用者可以很方便地使用。每個演算法的調用就像一個黑箱,對於使用者來說,我們只需要根據自己的需求,設定相應的參數。

  比如,調用最常用的支撐向量分類機(SVC):

from sklearn import svmclf = svm.SVC(gamma=0.001, C=100.) #不希望使用預設參數,使用使用者自己給定的參數
print clf

  分類器的具體資訊和參數:

SVC(C=100.0, cache_size=200, class_weight=None, coef0=0.0, degree=3,    gamma=0.001, kernel=‘rbf‘, max_iter=-1, probability=False,    random_state=None, shrinking=True, tol=0.001, verbose=False)

  分類器的學習和預測可以分別利用 fit(X,Y) 和 predict(T) 來實現。

  例如,將digit資料劃分為訓練集和測試集,前n-1個執行個體為訓練集,最後一個為測試集(這裡只是舉例說明fit和predict函數的使用)。然後利用fit和predict分別完成學習和預測,代碼如下:

from sklearn import datasetsfrom sklearn import svmclf = svm.SVC(gamma=0.001, C=100.)digits = datasets.load_digits()clf.fit(digits.data[:-1], digits.target[:-1])result=clf.predict(digits.data[-1])print result

  預測結果為:[8]

  我們可以通過程式來查看測試集中的手寫體執行個體到底長什麼樣來簡單驗證一下分類效果,代碼和結果如下所示:

import matplotlib.pyplot as plotplot.figure(1, figsize=(3, 3))plot.imshow(digits.images[-1], cmap=plot.cm.gray_r, interpolation=‘nearest‘)plot.show()

  最後一個手寫體執行個體為:

  

  我們可以看到,這就是一個手寫的數字“8”的,實際上正確的分類也是“8”。我們通過這個簡單的例子,就是為了簡單的學習如何來使用scikit-learn來解決分類問題,實際上這個問題要複雜得多。(PS:學習就是循序漸進,弄懂一個例子,就會弄懂第二個,... ,然後就是第n個,最後就會形成自己的知識和理論,你就可以輕鬆掌握,來解決各種遇到的複雜問題。)

  再為各位展示一個scikit-learn解決digit分類(手寫體識別)的程式(by Gael Varoquaux),相信看過這個程式大家一定會對scikit-learn機器學習庫有了一定的瞭解和認識。

import matplotlib.pyplot as plt# Import datasets, classifiers and performance metricsfrom sklearn import datasets, svm, metrics# The digits datasetdigits = datasets.load_digits()# The data that we are interested in is made of 8x8 images of digits, let‘s# have a look at the first 3 images, stored in the `images` attribute of the# dataset.  If we were working from image files, we could load them using# pylab.imread.  Note that each image must have the same size. For these# images, we know which digit they represent: it is given in the ‘target‘ of# the dataset.images_and_labels = list(zip(digits.images, digits.target))for index, (image, label) in enumerate(images_and_labels[:4]):    plt.subplot(2, 4, index + 1)    plt.axis(‘off‘)    plt.imshow(image, cmap=plt.cm.gray_r, interpolation=‘nearest‘)    plt.title(‘Training: %i‘ % label)# To apply a classifier on this data, we need to flatten the image, to# turn the data in a (samples, feature) matrix:n_samples = len(digits.images)data = digits.images.reshape((n_samples, -1))# Create a classifier: a support vector classifierclassifier = svm.SVC(gamma=0.001)# We learn the digits on the first half of the digitsclassifier.fit(data[:n_samples / 2], digits.target[:n_samples / 2])# Now predict the value of the digit on the second half:expected = digits.target[n_samples / 2:]predicted = classifier.predict(data[n_samples / 2:])print("Classification report for classifier %s:\n%s\n"      % (classifier, metrics.classification_report(expected, predicted)))print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))images_and_predictions = list(zip(digits.images[n_samples / 2:], predicted))for index, (image, prediction) in enumerate(images_and_predictions[:4]):    plt.subplot(2, 4, index + 5)    plt.axis(‘off‘)    plt.imshow(image, cmap=plt.cm.gray_r, interpolation=‘nearest‘)    plt.title(‘Prediction: %i‘ % prediction)plt.show()

  輸出結果:

Classification report for classifier SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3,  gamma=0.001, kernel=‘rbf‘, max_iter=-1, probability=False,  random_state=None, shrinking=True, tol=0.001, verbose=False):             precision    recall  f1-score   support          0       1.00      0.99      0.99        88          1       0.99      0.97      0.98        91          2       0.99      0.99      0.99        86          3       0.98      0.87      0.92        91          4       0.99      0.96      0.97        92          5       0.95      0.97      0.96        91          6       0.99      0.99      0.99        91          7       0.96      0.99      0.97        89          8       0.94      1.00      0.97        88          9       0.93      0.98      0.95        92avg / total       0.97      0.97      0.97       899Confusion matrix:[[87  0  0  0  1  0  0  0  0  0] [ 0 88  1  0  0  0  0  0  1  1] [ 0  0 85  1  0  0  0  0  0  0] [ 0  0  0 79  0  3  0  4  5  0] [ 0  0  0  0 88  0  0  0  0  4] [ 0  0  0  0  0 88  1  0  0  2] [ 0  1  0  0  0  0 90  0  0  0] [ 0  0  0  0  0  1  0 88  0  0] [ 0  0  0  0  0  0  0  0 88  0] [ 0  0  0  1  0  1  0  0  0 90]]

  

5. 總結

  1)scikit-learn的介紹和安裝;

  2)對scikit-learn有個概括的瞭解,能夠嘗試利用scikit-learn來進行資料採礦和分析。

6. 參考內容

  [1] An introduction to machine learning with scikit-learn

   [2] 機器學習實戰

 

[Python & Machine Learning] 學習筆記之scikit-learn機器學習庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.