scikit-learn使用筆記與sign prediction簡單小結

原帖地址:http://www.cnblogs.com/xupeizhi/archive/2013/07/05/3174703.html

經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代碼,只要輸入文件保持本文開頭所述的格式(且不包含註釋信息),即可用多種不同算法測試分類效果。

發佈了21 篇原創文章 · 獲贊 4 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章