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 datasets iris = 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 svm clf = 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 datasets from sklearn import svm clf = 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 plot plot.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 metrics from sklearn import datasets, svm, metrics # The digits dataset digits = 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 classifier classifier = svm.SVC(gamma=0.001) # We learn the digits on the first half of the digits classifier.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 92 avg / total 0.97 0.97 0.97 899 Confusion 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] 機器學習實戰