天天看點

sklearnsklearn

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline1">1. Overview</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline2">2. Building Blocks</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline7">3. Supervised Learning</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline3">3.1. Support Vector Machines</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline4">3.2. Ensemble methods</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline5">3.3. Nearest Neighbors</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline6">3.4. Naive Bayes</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline14">4. Model selection and evaluation</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline8">4.1. Cross-validation: evaluating estimator performance</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline9">4.2. Grid Search: searching for estimator parameters</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline10">4.3. Pipeline: chaining estimators</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline11">4.4. Model evaluation: quantifying the quality of predictions</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline12">4.5. Model persistence</a>

<a href="http://www.cnblogs.com/hhh5460/p/5186197.html#orgheadline13">4.6. Validation curves: plotting scores to evaluate models</a>

<a href="http://www.cnblogs.com/images/scikit-learn-ml-map.png">一張圖說明如何選擇正确算法</a>

supervised learning

classification # Identifying to which set of categories a new observation belong to.

regression # Predicting a continuous value for a new example.

unsupervised learning

clustering # Automatic grouping of similar objects into sets.

dimensionality reduction # Reducing the number of random variables to consider.

model selection and evaluation # Comparing, validating and choosing parameters and models.

dataset transformations # Feature extraction and normalization.

dataset loading utilities

<a href="https://docs.scipy.org/doc/numpy-dev/user/quickstart.html">https://docs.scipy.org/doc/numpy-dev/user/quickstart.html</a>

<a href="http://cs231n.github.io/python-numpy-tutorial/">http://cs231n.github.io/python-numpy-tutorial/</a>

numpy. 數組/矩陣的表示和運算能力. # import numpy as np

numpy provides:

extension package to Python for multi-dimensional arrays

closer to hardware (efficiency)

designed for scientific computation (convenience)

also known as array oriented computing

array attributes

ndim # 次元

shape # 每個次元大小

dtype # 存儲類型

T # 轉置矩陣

size # 元素個數

itemsize # 每個元素占用記憶體大小

nbytes # 占用記憶體大小

index array

a[d1, d2, …] # 多元通路

a[&lt;array&gt;, …] # fancy indexing

pylab. 繪圖能力 # import pylab as plt

scipy. 複雜數值處理運算能力.

The scipy package contains various toolboxes dedicated to common issues in scientific computing. Its different submodules correspond to different applications, such as interpolation, integration, optimization, image processing, statistics, special functions, etc. scipy can be compared to other standard scientific-computing libraries, such as the GSL (GNU Scientific Library for C and C++), or Matlab’s toolboxes. scipy is the core package for scientific routines in Python; it is meant to operate efficiently on numpy arrays, so that numpy and scipy work hand in hand.

<a href="http://scikit-learn.org/stable/modules/svm.html">http://scikit-learn.org/stable/modules/svm.html</a>

svm可以用來做classification, regression以及outliers detection(異常檢測).

classification有三種分類器分别是SVC, NuSVC, LinearSVC. 其中LinearSVC相同于我SVC使用'linear'核方法,差別在于SVC底層使用libsvm, 而LinearSVC則使用liblinear. 另外LinearSVC得到的結果最後也不會傳回support_(支援向量). 對于多分類問題SVC使用one-vs-one來生成分類器,也就是說需要構造C(n,2)個分類器。LinearSVC使用one-vs-rest來生成分類器,也就是構造n個分類器。LinearSVC也有比較複雜的算法隻構造一個分類器就可以進行多分類。regression有兩種回歸器分别是SVR和NuSVR. classifier和regressor都允許直接輸出機率值。用于異常檢測是OneClassSVM.

kernel函數支援 1.linear 2. polynomial 3. rbf 4. sigmoid(tanh). 對于unbalanced的問題,sklearn實作允許指定 1.class_weight 2.sample_weight. 其中class_weight表示每個class對應的權重,這個在構造classifier時候就需要設定。如果不确定的話就設定成為'auto'。sample_weight則表示每個執行個體對應的權重,這個可以在調用訓練方法fit的時候傳入。另外一個比較重要的參數是C(懲罰代價), 通常來說設定成為1.0就夠了。但是如果資料中太多噪音的話那麼最好減小一些。

在計算效率方面,SVM是通過QP來求解的。基于libsvm的實作時間複雜度在O(d * n^2) ~ O(d * n^3)之間,變化取決于如何使用cache. 是以如果我們記憶體足夠的話那麼可以調大cache_size來加快計算速度。其中d表示feature大小,如果資料集合比較稀疏的話,那麼可以認為d是non-zero的feature平均數量。libsvm處理資料集合大小最好不要超過10k. 相比之下,liblinear的效率則要好得多,可以很容易訓練million級别的資料集合。

<a></a>

<a href="http://scikit-learn.org/stable/modules/ensemble.html">http://scikit-learn.org/stable/modules/ensemble.html</a>

emsemble方法通常分為兩類:

averaging methods. 平均方法,使用不同的算法建構出幾個不同的假設然後取平均效果。算法得到的假設都比較好但是容易overfitting, 通過取平均效果降低variance. 通常算法隻是作用在部分資料上。這類方法有Bagging, Random Forest等。sklearn提供了bagging meta-estimator允許傳入base-estimator來自動做averaging. RF還提供了兩個不同版本,另外一個版本在生成決策樹選擇threshold上也做了随機。

boosting methods. 增強方法,使用同一個算法不斷地修正和疊代然後組合。算法得到的假設一般都比較弱,但是通過組合在一起得到效果比較好的假設。通常算法作用在全部資料上。這類方法有AdaBoost, Gradient Boosting等。sklearn提供的AdaBoost内部base-estimator預設是DecisionTree, 而GBDT内部base-estimator固定就是decision-tree但是允許自定義損失函數。

使用Decision Tree來做分類和回歸時另外一個好處是可以知道每個feature的重要性:位于DecisionTree越高的feature越重要。不過我的了解是這種feature重要性隻能用在DecisionTree這種訓練方式上。

#note: 從下面程式效果上看,GBDT比RF稍微差一些,并且GBDT運作時間要明顯長于RF。用iris資料集合的話兩者效果差不多。

<a href="http://scikit-learn.org/stable/modules/neighbors.html">http://scikit-learn.org/stable/modules/neighbors.html</a>

NN可以同時用來做監督和非監督學習。其中非監督學習的NN是其他一些學習方法的基礎。

在實作上sklearn提供了幾種算法來尋找最近點:1. brute-force 2. kd-tree 3. ball-tree 4. auto. 其中auto是根據數量大小自動選擇算法的。brute-force是采用暴力搜尋算法,kd-tree和ball-tree則建立了内部資料結構來加快檢索。假設資料次元是d, 資料集合大小是N的話,那麼三個算法時間複雜度分别是O(dN), O(d*logN), O(d*logN). 不過如果d過大的話kd-tree會退化稱為O(dN).

如果資料量比較小的話那麼1比2,3要好,是以在實作上kd-tree/ball-tree發現如果資料集合較小的話就會改用brute-force來做。這個門檻值稱為leaf_size. leaf_size大小會影響到 1. 建構索引時間(反比) 2. 查詢時間(合适的leaf_size可以達到最優) 3. 記憶體大小(反比). 是以盡可能地增大leaf_size但是確定不會影響查詢時間。

classifier和regressor基本上就是在這些資料結構上做了一層包裝。我們可以指定距離函數以及查找到最近點之後的合成函數. 預設距離函數是minkowski(p=2, 也就歐幾裡得距離), 合成函數包含uniform和distance(和距離成反比). KNeighborsClassifier是選擇附近k個點,而RadiusNeighborsClassifier則是選擇附近在radius範圍内的所有點。另外還有一個NearestCentroid分類器:假設y有k個classes的話,根據這些class歸納為k類并且計算出中心(centroid), 然後判斷離哪個中心近就預測哪個class.

<a href="http://scikit-learn.org/stable/modules/naive_bayes.html">http://scikit-learn.org/stable/modules/naive_bayes.html</a>

樸素貝葉斯用于分類問題,其中兩項主要工作就是計算 1.P(X|y) 2.P(y). 兩者都是通過MLE(maximum likehood estimation)來完成的。P(y)相對來說比較好計算,計算P(X|y)有下面三種辦法:

如果Xi是連續量的話,Gaussian Naive Bayes. 取y=k的所有Xi資料點,假設這個分布服從高斯分布。計算出這個高斯分布的mean和std之後,就可以計算P(X|y=k)。這個模型系數有d * k個。

如果Xi是離散量的話,Multinomial Naive Bayes. 那麼P(X=u|y=k) = P(X=u, y=k) / P(y=k). 這個模型系數有k * ∑ {Xi}個。模型裡面還有一個平滑參數。

進一步如果Xi是(0,1)的話,Bernoulli Naive Bayes. 通常我們需要提供參數binarize,這個方法用來将X轉換成為(0,1).

<a href="http://scikit-learn.org/stable/modules/cross_validation.html">http://scikit-learn.org/stable/modules/cross_validation.html</a>

使用train_test_split分開training_set和test_set.

使用k-fold等方式從training_set中分出validation_set做cross_validation.

使用cross_val_score來進行cross_validation并且計算cross_validation效果.

<a href="http://scikit-learn.org/stable/modules/grid_search.html">http://scikit-learn.org/stable/modules/grid_search.html</a>

參數空間搜尋方式大緻分為三類: 1.暴力 2.随機 3.adhoc. 其中23和特定算法相關。

代碼最後使用最優模型作用在測試資料上,然後使用classification_report列印評分結果.

<a href="http://scikit-learn.org/stable/modules/pipeline.html">http://scikit-learn.org/stable/modules/pipeline.html</a>

将多個階段串聯起來自動化

<a href="http://scikit-learn.org/stable/modules/model_evaluation.html">http://scikit-learn.org/stable/modules/model_evaluation.html</a>

There are 3 different approaches to evaluate the quality of predictions of a model: # 有3中不同方式來評價模型預測結果

Estimator score method: Estimators have a score method providing a default evaluation criterion for the problem they are designed to solve. # 模型自身内部的評價比如損失函數等

Scoring parameter: Model-evaluation tools using cross-validation (such as cross_validation.cross_val_score and grid_search.GridSearchCV) rely on an internal scoring strategy. # cv的評價,通常是數值表示. 比如'f1'.

Metric functions: The metrics module implements functions assessing prediction errors for specific purposes. # 作用在測試資料的評價,可以是數值表示,也可以是文本圖像等表示. 比如'classification_report'.

其中23是比較相關的。差别在于3作用在測試資料上是我們需要進一步分析的,是以相對來說評價方式會更多一些。而2還是在模型選擇階段是以我們更加傾向于單一數值表示。

sklearn還提供了DummyEstimator. 它隻有有限的幾種比較dummy的政策,主要是用來給出baseline.

DummyClassifier implements three such simple strategies for classification:

'stratified' generates randomly predictions by respecting the training set’s class distribution,

'most_frequent' always predicts the most frequent label in the training set,

'uniform' generates predictions uniformly at random.

'constant' always predicts a constant label that is provided by the user.

DummyRegressor also implements three simple rules of thumb for regression:

'mean' always predicts the mean of the training targets.

'median' always predicts the median of the training targests.

'constant' always predicts a constant value that is provided by the user.

<a href="http://scikit-learn.org/stable/modules/model_persistence.html">http://scikit-learn.org/stable/modules/model_persistence.html</a>

可以使用python自帶的pickle子產品,或者是sklearn的joblib子產品。joblib相對pickle能更有效地序列化到磁盤上,但缺點是不能夠像pickle一樣序列化到string上。

<a href="http://scikit-learn.org/stable/modules/learning_curve.html">http://scikit-learn.org/stable/modules/learning_curve.html</a>

Every estimator has its advantages and drawbacks. Its generalization error can be decomposed in terms of bias, variance and noise. The bias of an estimator is its average error for different training sets. The variance of an estimator indicates how sensitive it is to varying training sets. Noise is a property of the data. # bias是指模型對不同訓練資料的偏差,variance則是指模型對不同訓練資料的敏感程度,噪音則是資料自身屬性。這三個問題造成預測偏差。

#note: 這個特性應該是從0.15才有的。之前我用apt-get安裝的sklearn-0.14.1沒有learning_curve這個子產品。

validation curve

If the training score and the validation score are both low, the estimator will be underfitting. If the training score is high and the validation score is low, the estimator is overfitting and otherwise it is working very well. A low training score and a high validation score is usually not possible. All three cases can be found in the plot below where we vary the parameter gamma on the digits dataset.

可以看到gamma在5 * 10^{-4}附近cross-validation score開始下滑,但是training score還是不錯的,說明overfitting.

learning curve

第一幅圖是是用樸素貝葉斯的learning curve. 可以看到high-bias情況。第二幅圖是使用SVM(RBF kernel)的learning curve. 學習情況明顯比樸素貝葉斯要好。

【轉自】: http://dirlt.com/sklearn.html

 本文轉自羅兵部落格園部落格,原文連結:http://www.cnblogs.com/hhh5460/p/5186197.html,如需轉載請自行聯系原作者