[轉]0.python:scikit-learn基本用法

來源:互聯網
上載者:User

標籤:

感謝百小度治哥,該文原地址:here

經Edwin Chen的推薦,認識了scikit-learn這個非常強大的python機器學習工具包。這個文章作為筆記。(其實都沒有筆記的意義,因為他家文檔做的太好了,不過還是為自己記記吧,為以後節省若干分鐘)。如果有幸此文被想用scikit-learn的你看見,也還是非常希望你去它們的首頁看文檔。首頁中最值得關注的幾個部分:User Guide幾乎是machine learning的索引,各種方法如何使用都有,Reference是各個類的用法索引。

S1. 匯入資料

大多數資料的格式都是M個N維向量,分為訓練集和測試集。所以,知道如何匯入向量(矩陣)資料是最為關鍵的一點。這裡要用到numpy來協助。假設資料格式是:

 

Stock prices    indicator1    indicator2

2.0             123           1252

1.0             ..            ..

..              .             .

.

匯入代碼參考:

 

import numpy as np

f = open("filename.txt")

f.readline()  # skip the header

data = np.loadtxt(f)

X = data[:, 1:]  # select columns 1 through end

y = data[:, 0]   # select column 0, the stock price

libsvm格式的資料匯入:

 

>>> from sklearn.datasets import load_svmlight_file

>>> X_train, y_train = load_svmlight_file("/path/to/train_dataset.txt")

...

>>>X_train.todense()#將疏鬆陣列轉化為完整特徵矩陣

更多格式資料匯入與產生參考:http://scikit-learn.org/stable/datasets/index.html

S2. Supervised Classification 幾種常用方法:

Logistic Regression

>>> from sklearn.linear_model import LogisticRegression

>>> clf2 = LogisticRegression().fit(X, y)

>>> clf2

LogisticRegression(C=1.0, intercept_scaling=1, dual=False, fit_intercept=True,

penalty=‘l2‘, tol=0.0001)

>>> clf2.predict_proba(X_new)

array([[  9.07512928e-01,   9.24770379e-02,   1.00343962e-05]])

Linear SVM (Linear kernel)

 

>>> from sklearn.svm import LinearSVC

>>> clf = LinearSVC()

 

>>> clf.fit(X, Y)

>>> X_new = [[ 5.0,  3.6,  1.3,  0.25]]

>>> clf.predict(X_new)#reuslt[0] if class label

array([0], dtype=int32)

SVM (RBF or other kernel)

 

>>> from sklearn import svm

>>> clf = svm.SVC()

>>> clf.fit(X, Y)

SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3,

gamma=0.0, kernel=‘rbf‘, probability=False, shrinking=True, tol=0.001,

verbose=False)

>>> clf.predict([[2., 2.]])

array([ 1.])

Naive Bayes (Gaussian likelihood)

 

 

from sklearn.naive_bayes import GaussianNB

>>> from sklearn import datasets

>>> gnb = GaussianNB()

>>> gnb = gnb.fit(x, y)

>>> gnb.predict(xx)#result[0] is the most likely class label

Decision Tree (classification not regression)

 

>>> from sklearn import tree

>>> clf = tree.DecisionTreeClassifier()

>>> clf = clf.fit(X, Y)

>>> clf.predict([[2., 2.]])

array([ 1.])

Ensemble (Random Forests, classification not regression)

>>> from sklearn.ensemble import RandomForestClassifier

>>> clf = RandomForestClassifier(n_estimators=10)

>>> clf = clf.fit(X, Y)

>>> clf.predict(X_test)

S3. Model Selection (Cross-validation)

手工分training data和testing data當然可以了,但是更方便的方法是自動進行,scikit-learn也有相關的功能,這裡記錄下cross-validation的代碼:

 

>>> from sklearn import cross_validation

>>> from sklearn import svm

>>> clf = svm.SVC(kernel=‘linear‘, C=1)

>>> scores = cross_validation.cross_val_score(clf, iris.data, iris.target, cv=5)#5-fold cv

#change metrics

>>> from sklearn import metrics

>>> cross_validation.cross_val_score(clf, iris.data, iris.target, cv=5, score_func=metrics.f1_score)

#f1 score: http://en.wikipedia.org/wiki/F1_score

more about cross-validation: http://scikit-learn.org/stable/modules/cross_validation.html

Note: if using LR, clf = LogisticRegression().

S4. Sign Prediction Experiment

資料集,EPINIONS,有user與user之間的trust與distrust關係,以及interaction(對使用者評論的有用程度打分)。

Features:網路拓撲feature參考"Predict positive and negative links in online social network",使用者互動資訊feature。

一共設了3類instances,每類3次訓練+測試,訓練資料是測試資料的10倍,~80,000個29/5/34維向量,得出下面一些結論。時間 上,GNB最快(所有instance都是2~3秒跑完),DT非常快(有一類instance只用了1秒,其他都要4秒),LR很快(三類 instance的時間分別是2秒,5秒,~30秒),RF也不慢(一個instance9秒,其他26秒),linear kernel的SVM要比LR慢好幾倍(所有instance要跑30多秒),RBF kernel的SVM比linear SVM要慢20+倍到上百倍(第一個instance要11分鐘,第二個instance跑了近兩個小時)。準確度上 RF>LR>DT>GNB>SVM(RBF kernel)>SVM(Linear kernel)。GNB和SVM(linear kernel)、SVM(rbf kernel)在第二類instance上差的比較遠(10~20個百分點),LR、DT都差不多,RF確實體現了ENSEMBLE方法的強大,比LR有 較為顯著的提升(近2~4個百分點)。(註:由於到該文提交為止,RBF版的SVM才跑完一次測試中的兩個instance,上面結果僅基於此。另外,我 還嘗試了SGD等方法,總體上都不是特別理想,就不記了)。在feature的有效性上面,使用者互動feature比網路拓撲feature更加有效百分 五到百分十。

S5.通用測試原始碼

這裡是我寫的用包括上述演算法在內的多種演算法的自動分類並10fold cross-validation的python代碼,只要輸入檔案保持本文開頭所述的格式(且不包含注釋資訊),即可用多種不同演算法測試分類效果。

 

 

[轉]0.python: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.