翻譯:Tacey Wong
統計學習
:
隨着科學實驗數據的迅速增長,機器學習成了一種越來越重要的技術。問題從構建一個預測函數將不同的觀察數據聯系起來,到將觀測數據分類,或者從未標記數據中學習到一些結構。
本教程將探索機器學習中統計推理的統計學習的使用:將手中的數據做出結論
Scikit-learn
是一個緊密結合Python科學計算庫(Numpy、Scipy、matplotlib),集成經典機器學習算法的Python模塊。
一、統計學習:scikit-learn中的設置與評估函數對象
(1)數據集
scikit-learn 從二維數組描述的數據中學習信息。他們可以被理解成多維觀測數據的列表。如(n,m),n表示樣例軸,y表示特征軸。
使用scikit-learn裝載一個簡單的樣例:iris數據集
>>from sklearn import datasets >>iris = datasets.load_iris() >>data = iris.data >>data.shape
(150, 4)
它有150個iris觀測數據構成,每一個樣例被四個特征所描述:他們的萼片、花瓣長度、花瓣寬度,具體的信息可以通過iris》DESCR查看。
當數據初始時不是(`n樣例,n特征`)樣式時,需要將其預處理以被scikit-learn使用。
> 通過數字數據集講述數據變形
數字數據集由1797個8x8手寫數字圖片組成
```python
>>>digits = datasets.load_digits()
>>>digits.images.shape
(1797, 8, 8)
>>> import pylab as pl
>>>pl.imshow(digits.images[-1], cmap=pl.cm.gray_r)
<matplotlib.image.AxesImage object at ...>
在scikit-learn中使用這個數據集,我們需要將其每一個8x8圖片轉換成長64的特征向量
python
>>>data = digits.images.reshape((digits.images.shape[0],-1))
(2)估計函數對象
擬合數據
:scikit-learn實現的主要API是估計函數。估計函數是用以從數據中學習的對象。它可能是分類、回歸、聚類算法,或者提取過濾數據特征的轉換器。
一個估計函數帶有一個fit
方法,以dataset作為參數(一般是個二維數組)
>>>estimator.fit(data)
估計函數對象的參數
:每一個估測器對象在實例化或者修改其相應的屬性,其參數都會被設置。
>>>estimator = Estimator(param1=1, param2=2)
>>>estimator.param1
1
估測后的參數
:
>>>estimator.estimated_param_
二、有監督學習:從高維觀察數據預測輸出變量
有監督學習解決的問題
有監督學習主要是學習將兩個數據集聯系起來:觀察數據x和我們要嘗試預測的外置變量y,y通常也被稱作目標、標簽。多數情況下,y是一個和n個觀測樣例對應的一維數組。
scikit-learn中實現的所有有監督學習評估對象,都有fit(X,Y)方法來擬合模型,predict(X)方法根據未加標簽的觀測數據X
返回預測的標簽y。
詞匯:分類和回歸
如果預測任務是將觀測數據分類到一個有限的類別集中,換句話說,給觀測對象命名,那么這個任務被稱作分類任務。另一方面,如果任務的目標是預測測目標是一個連續性變量,那么這個任務成為回歸任務。
用scikit-learn解決分類問題時,y是一個整數或字符串組成的向量
注意:查看[]快速了解用scikit-learn解決機器學習問題過程中的基礎詞匯。
(1)近鄰和高維災難
iris分類
:
iris分類是根據花瓣、萼片長度、萼片寬度來識別三種不同類型的iris的分類任務:>> import numpy as np >> from sklearn import datasets >> iris = datasets.load_iris() >> iris_X = iris.data >> iris_y = iris.target >> np.unique(iris_y)
array([0, 1, 2])
`最近鄰分類器`:
近鄰也許是最簡的分類器:得到一個新的觀測數據X-test,從訓練集的觀測數據中尋找特征最相近的向量。(【】)
>
`訓練集和測試集`:
當嘗試任何學習算法的時候,評估一個學習算法 的預測精度是很重要的。所以在做機器學習相關的問題的時候,通常將數據集分成訓練集和測試集。
**KNN(最近鄰)分類示例**:
```python
# Split iris data in train and test data
# A random permutation, to split the data randomly
np.random.seed(0)
indices = np.random.permutation(len(iris_X))
iris_X_train = iris_X[indices[:-10]]
iris_y_train = iris_y[indices[:-10]]
iris_X_test = iris_X[indices[-10:]]
iris_y_test = iris_y[indices[-10:]]
# Create and fit a nearest-neighbor classifier
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(iris_X_train, iris_y_train)
knn.predict(iris_X_test)
iris_y_test
高維災難:
對於一個有效的學習算法,你需要最近n個點之間的距離d(依賴於具體的問題)。在一維空間中,需要平局n1/d各點,在上文中提到的K-NN例子中,如果數據只是有一個0-1之間的特征和n個訓練觀測數據所表述的畫,那么新數據將不會超過1/n。因此,最近鄰決策規則非常高效,因為與類間特征變化的范圍相比,1/n小的多。
如果特征數是P,你就需要n 1/d^p個點。也就是說,如果我們在一維度情況下需要10個點,在P維度情況下需要10^p個點。當P變大的時候,為獲得一個好的預測函數需要的點數將急劇增長。
這被稱為高維災難(指數級增長),也是機器學習領域的一個核心問題。
(2)線性模型:從回歸到稀疏性
Diabets數據集(糖尿病數據集)
糖尿病數據集包含442個患者的10個生理特征(年齡,性別、體重、血壓)和一年以后疾病級數指標。
diabetes = datasets.load_diabetes()
diabetes_X_train = diabetes.data[:-20]
diabetes_X_test = diabetes.data[-20:]
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
手上的任務是從生理特征預測疾病級數
線性回歸:
【線性回歸】的最簡單形式給數據集擬合一個線性模型,主要是通過調整一系列的參以使得模型的殘差平方和盡量小。
線性模型:y = βX+b
X:數據
y:目標變量
β:回歸系數
b:觀測噪聲(bias,偏差)
from sklearn import linear_model
regr = linear_model.LinearRegression()
regr.fit(diabetes_X_train, diabetes_y_train)
print(regr.coef_)
# The mean square error
np.mean((regr.predict(diabetes_X_test)-diabetes_y_test)**2)
# Explained variance score: 1 is perfect prediction
# and 0 means that there is no linear relationship
# between X and Y.
regr.score(diabetes_X_test, diabetes_y_test)
收縮(Shrinkage):
如果每一維的數據點很少,噪聲將會造成很大的偏差影響:
X = np.c_[ .5, 1].T
y = [.5, 1]
test = np.c_[ 0, 2].T
regr = linear_model.LinearRegression()
import pylab as pl
pl.figure()
np.random.seed(0)
for _ in range(6):
this_X = .1*np.random.normal(size=(2, 1)) + X
regr.fit(this_X, y)
pl.plot(test, regr.predict(test))
pl.scatter(this_X, y, s=3)
高維統計學習的一個解決方案是將回歸系數縮小到0:觀測數據中隨機選擇的兩個數據集近似不相關。這被稱為嶺回歸(Ridge Regression):
regr = linear_model.Ridge(alpha=.1)
pl.figure()
np.random.seed(0)
for _ in range(6):
this_X = .1*np.random.normal(size=(2, 1)) + X
regr.fit(this_X, y)
pl.plot(test, regr.predict(test))
pl.scatter(this_X, y, s=3)
這是一個偏差/方差(bias/variance)的權衡:嶺α參數越大,偏差(bias)越大,方差(variance)越小
我們可以選擇α以最小化排除錯誤,這里使用糖尿病數據集而不是人為制造的數據:
alphas = np.logspace(-4, -1, 6)
from __future__ import print_function
print([regr.set_params(alpha=alpha
).fit(diabetes_X_train, diabetes_y_train,
).score(diabetes_X_test, diabetes_y_test) for alpha in alphas])
【注意】撲捉擬合參數的噪聲使得模型不能推廣到新的數據被稱為過擬合。嶺回歸造成的偏差被稱為正則化(歸整化,regularization)
稀疏性:
只擬合特征1和特征2:
【注意】整個糖尿病數據包含11維數據(10個特征維,一個目標變量
),很難對這樣的數據直觀地表現出來,但是記住那是一個很空的空間也許是有用的。
我們可以看到,盡管特征2在整個模型中占據很大的系數,但是和特征1相比,對結果y造成的影響很小。
為了提升問題的狀況(考慮到高維災難),只選擇信息含量較大的(對結果y造成的影響較大的)的特征,不選擇信息含量較小的特征會很有趣,如把特征2的系數調到0.嶺回歸將會減少信息含量較小的系數的值,而不是把它們設置為0.另一種抑制措施——Lasso(最小絕對收縮和選擇算子)可以使得一些參數為0.這些方法被稱作稀疏方法。系數操作可以看作是奧卡姆的剃刀:模型越簡單越好。
regr = linear_model.Lasso()
scores = [regr.set_params(alpha=alpha
).fit(diabetes_X_train, diabetes_y_train
).score(diabetes_X_test, diabetes_y_test)
for alpha in alphas]
best_alpha = alphas[scores.index(max(scores))]
regr.alpha = best_alpha
regr.fit(diabetes_X_train, diabetes_y_train)
print(regr.coef_)
針對相同問題的不同算法:
不同的算法可以被用來解決相同的數學問題。例如scikit-learn中的Lasso對象使用coordinate decent方法解決lasso回歸問題,在大數據集上是很有效的。然而,scikit-learn也使用LARS算法提供了LassoLars對象,對於處理權重向量非常稀疏的數據非常有效(數據的觀測實例非常少)。
- 分類:
對於分類問題,比如iris標定任務,線性回歸不是正確的方法。因為它會給數據得出大量遠離決策邊界的權重。一個線性方法是你和一個sigmoid函數或者logistic函數:
logistic = linear_model.LogisticRegression(C=1e5)
logistic.fit(iris_X_train, iris_y_train)
這就是有名的logistic回歸。
- 多分類:
如果你有多個類別需要預測,一個可行的方法是 “一對多”分類,接着根據投票決定最終的決策。
通過Logistic回歸進行收縮和稀疏:
在LogisticRegression對象中C參數控制着正則化的數量:C越大,正則化數目越少。penalty= "12" 提供收縮(非稀疏化系數),penalty="11"提供稀疏化。
練習:
嘗試使用近鄰算法和線性模型對數字數據集進行分類。留出最后的10%作為測試集用來測試預測的精確度。
from sklearn import datasets, neighbors, linear_model
digits = datasets.load_digits()
X_digits = digits.data
y_digits = digits.target
【完整代碼】
from sklearn import datasets, neighbors, linear_model
digits = datasets.load_digits()
X_digits = digits.data
y_digits = digits.target
n_samples = len(X_digits)
X_train = X_digits[:.9 * n_samples]
y_train = y_digits[:.9 * n_samples]
X_test = X_digits[.9 * n_samples:]
y_test = y_digits[.9 * n_samples:]
knn = neighbors.KNeighborsClassifier()
logistic = linear_model.LogisticRegression()
print('KNN score: %f' % knn.fit(X_train, y_train).score(X_test, y_test))
print('LogisticRegression score: %f'
% logistic.fit(X_train, y_train).score(X_test, y_test))
(3)支持向量機(SVMs)
線性SVNs:
支持向量機屬於判別模型家族:它們嘗試尋找樣例的一個組合,構建一個兩類之間的最大邊緣平面。通過C參數進行正則化:一個較小的C意味着邊緣是通過分割線周圍的所有觀測樣例進行計算得到的(更規整化,正則化);一個較大的C意味着邊緣是通過鄰近分割線的觀測樣例計算得到的(更少的規整化,正則化):
-
非正則化SVN:
-
正則化 SVM(默認):
樣例:Plot different SVM分類器 iris數據集
SVMs能夠被用於回歸——SVR(支持向量回歸)—用於分類——SVC(支持向量分類)
from sklearn import svm
svc = svm.SVC(kernel='linear')
svc.fit(iris_X_train, iris_y_train)
【警告】:規格化數據
對於大多數的估測模型,包括SVMs,處理好單位標准偏差對於獲得一個好的預測是很重要的。
使用核函數:
在特征空間中類別不經常是線性可分的。解決方案是構建一個非線性但能用多項式代替的決策函數。這要通過核技巧實現:使用核可以被看作通過設置核在觀測樣例上創建決策力量。
-
線性核:
-
多項式核:
-
徑向基函數核(RBF,Radial Basis Function):
svc = svm.SVC(kernel='rbf')
交互式樣例:
參照SVM GUI,下載svm_gui.py;通過鼠標左右鍵設置兩類數據點,擬合模型並改變參數和數據。
練習:
嘗試使用SVMs根據iris數據集前兩個特征將其分成兩類。留出每一類的10%作為測試樣例。
【警告】數據集中的數據是按照分類順序排列的,不要留出最后的10%作為測試樣例,要不然你只能測試一種類別。(獲取訓練集和測試集是注意要進行混淆)
提示:你可以在一個網格上使用decision_function方法獲得直觀的呈現。
iris = datasets.load_iris()
X = iris.data
y = iris.target
X = X[y != 0, :2]
y = y[y != 0]
完整代碼:
"""
================================
SVM Exercise
================================
A tutorial exercise for using different SVM kernels.
This exercise is used in the :ref:`using_kernels_tut` part of the
:ref:`supervised_learning_tut` section of the :ref:`stat_learn_tut_index`.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, svm
iris = datasets.load_iris()
X = iris.data
y = iris.target
X = X[y != 0, :2]
y = y[y != 0]
n_sample = len(X)
np.random.seed(0)
order = np.random.permutation(n_sample)
X = X[order]
y = y[order].astype(np.float)
X_train = X[:.9 * n_sample]
y_train = y[:.9 * n_sample]
X_test = X[.9 * n_sample:]
y_test = y[.9 * n_sample:]
# fit the model
for fig_num, kernel in enumerate(('linear', 'rbf', 'poly')):
clf = svm.SVC(kernel=kernel, gamma=10)
clf.fit(X_train, y_train)
plt.figure(fig_num)
plt.clf()
plt.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap=plt.cm.Paired)
# Circle out the test data
plt.scatter(X_test[:, 0], X_test[:, 1], s=80, facecolors='none', zorder=10)
plt.axis('tight')
x_min = X[:, 0].min()
x_max = X[:, 0].max()
y_min = X[:, 1].min()
y_max = X[:, 1].max()
XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])
# Put the result into a color plot
Z = Z.reshape(XX.shape)
plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired)
plt.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'],
levels=[-.5, 0, .5])
plt.title(kernel)
plt.show()
三、模型選擇:選擇模型和他們的參數
(1)分數,和交叉驗證分數
眾所周知,每一個模型會得出一個score方法用於裁決模型在新的數據上擬合的質量。其值越大越好。
from sklearn import datasets, svm
digits = datasets.load_digits()
X_digits = digits.data
y_digits = digits.target
svc = svm.SVC(C=1, kernel='linear')
svc.fit(X_digits[:-100], y_digits[:-100]).score(X_digits[-100:], y_digits[-100:])
為了獲得一個更好的預測精確度度量,我們可以把我們使用的數據折疊交錯地分成訓練集和測試集:
import numpy as np
X_folds = np.array_split(X_digits, 3)
y_folds = np.array_split(y_digits, 3)
scores = list()
for k in range(3):
# We use 'list' to copy, in order to 'pop' later on
X_train = list(X_folds)
X_test = X_train.pop(k)
X_train = np.concatenate(X_train)
y_train = list(y_folds)
y_test = y_train.pop(k)
y_train = np.concatenate(y_train)
scores.append(svc.fit(X_train, y_train).score(X_test, y_test))
print(scores)
這被稱為KFold交叉驗證
(2)交叉驗證生成器
上面將數據划分為訓練集和測試集的代碼寫起來很是沉悶乏味。scikit-learn為此自帶了交叉驗證生成器以生成目錄列表:
from sklearn import cross_validation
k_fold = cross_validation.KFold(n=6, n_folds=3)
for train_indices, test_indices in k_fold:
print('Train: %s | test: %s' % (train_indices, test_indices))
接着交叉驗證就可以很容易實現了:
kfold = cross_validation.KFold(len(X_digits), n_folds=3)
[svc.fit(X_digits[train], y_digits[train]).score(X_digits[test], y_digits[test])
for train, test in kfold]
為了計算一個模型的score,scikit-learn自帶了一個幫助函數:
cross_validation.cross_val_score(svc, X_digits, y_digits, cv=kfold, n_jobs=-1)
n_jobs=-1
意味着將計算任務分派個計算機的所有CPU.
交叉驗證生成器:
KFold(n,k)
交叉分割,K-1上進行訓練,生於數據樣例用於測試
StratifiedKFold(y,K)
保存每一個fold的類比率/標簽分布
leaveOneOut(n)
至預留一個觀測樣例
leaveOneLabelOut(labels)
采用一個標簽數組把觀測樣例分組
練習:
使用digits數據集,繪制使用線性核的SVC進行交叉驗證的分數(使用對數坐標軸,1——10)
import numpy as np
from sklearn import cross_validation, datasets, svm
digits = datasets.load_digits()
X = digits.data
y = digits.target
svc = svm.SVC(kernel='linear')
C_s = np.logspace(-10, 0, 10)
完整代碼:
(3)網格搜索和交叉驗證模型
網格搜索:
scikit-learn提供一個對象,他得到數據可以在采用一個參數的模型擬合過程中選擇使得交叉驗證分數最高的參數。該對象的構造函數需要一個模型作為參數:
from sklearn.grid_search import GridSearchCV
Cs = np.logspace(-6, -1, 10)
clf = GridSearchCV(estimator=svc, param_grid=dict(C=Cs),
n_jobs=-1)
clf.fit(X_digits[:1000], y_digits[:1000])
clf.best_score_
clf.best_estimator_.C
# Prediction performance on test set is not as good as on train set
clf.score(X_digits[1000:], y_digits[1000:])
默認情況下,GridSearchCV
使用3-fold
交叉驗證。然而,當他探測到是一個分類器而不是回歸量,將會采用分層的3-fold
。
嵌套 交叉驗證
cross_validation.cross_val_score(clf, X_digits, y_digits)
兩個交叉驗證循環是並行執行的:一個GridSearchCV
模型設置gamma
,另一個使用cross_val_score
度量模型的預測表現。結果分數是在新數據預測分數的無偏差估測。
【警告】你不能在並行計算時嵌套對象(n_jobs
不同於1)
交叉驗證估測:
在算法by算法的基礎上使用交叉驗證去設置參數更高效。這也是為什么對於一個特定的模型/估測器引入Cross-validation
:評估估測器表現模型去自動的通過交叉驗證設置參數。
from sklearn import linear_model, datasets
lasso = linear_model.LassoCV()
diabetes = datasets.load_diabetes()
X_diabetes = diabetes.data
y_diabetes = diabetes.target
lasso.fit(X_diabetes, y_diabetes)
# The estimator chose automatically its lambda:
lasso.alpha_
這些模型的稱呼和他們的對應模型很相似,只是在他們模型名字的后面加上了'CV
'.
練習:
使用糖尿病數據集,尋找最佳的正則化參數α
- 附加:你對選擇的α值信任度有多高?
from sklearn import cross_validation, datasets, linear_model
diabetes = datasets.load_diabetes()
X = diabetes.data[:150]
y = diabetes.target[:150]
lasso = linear_model.Lasso()
alphas = np.logspace(-4, -.5, 30)
完整代碼:
四、無監督學習:尋找數據的代表
(1)聚類:將觀測樣例聚集到一起
聚類解決的問題:
比如對於iris數據集,如果我們知道我們知道有三種iris,但是我們沒有標簽標定他們:我們可以嘗試聚類任務:將觀測樣例分成分離的族群中,這些族群可以被稱為簇。
- K-mean聚類(K均值聚類)
注意存在很多不同的聚類標准和關聯算法。最簡的聚類算法是——K均值(K-means)
from sklearn import cluster, datasets
iris = datasets.load_iris()
X_iris = iris.data
y_iris = iris.target
k_means = cluster.KMeans(n_clusters=3)
k_means.fit(X_iris)
print(k_means.labels_[::10])
print(y_iris[::10])
注意:沒有絕對的保證能夠恢復真實的分類。首先,盡管scikit-learn使用很多技巧來緩和問題的難度,但選擇簇的個數還是是很困難的,初始狀態下算法是很敏感的,可能會陷入局部最小。
不好的初始狀態:
8個簇:
真實情況:
不要“過解釋”聚類結果
應用實例:矢量化
K-means和一般的聚類,可以看作是選擇少量的示例壓縮信息的方式。這個問題被稱之為矢量化。例如,這可以被用於分離一個圖像:
import scipy as sp
try:
lena = sp.lena()
except AttributeError:
from scipy import misc
lena = misc.lena()
X = lena.reshape((-1, 1)) # We need an (n_sample, n_feature) array
k_means = cluster.KMeans(n_clusters=5, n_init=1)
k_means.fit(X)
values = k_means.cluster_centers_.squeeze()
labels = k_means.labels_
lena_compressed = np.choose(labels, values)
lena_compressed.shape = lena.shape
原始圖像:
K-means矢量化:
等段:(Equal bins)
圖像直方圖:
-
分層凝聚聚類:Ward
分層聚類方法是一種針對構建一個簇的分層的簇分析。通常它的實現方式有以下兩種:- 凝聚:自下而上的方法:每一個觀測樣例開始於他自己的簇,以一種最小連接標准迭代合並。這種方法在觀測樣例較少的情況下非常有效(有趣)。當簇的數量變大時,計算效率比K-means高的多。
- 分裂:自上而下的方法:所有的觀測樣例開始於同一個簇。迭代的進行分層。對於預計簇很多的情況,這種方法既慢(由於所有的觀測樣例作為一個簇開始的,是遞歸進行分離的)又有統計學行的病態。
-
連同-驅使聚類(Conectivity-constrained clustering)
使用凝聚聚類,通過一個連通圖可以指定某些樣例能被聚集在一起。scikit-learn中的圖通過鄰接矩陣來表示,且通常是一個稀疏矩陣。例如,在聚類一張圖片時檢索連通區域(有時也被稱作連同單元、部件):
from sklearn.feature_extraction.image import grid_to_graph
from sklearn.cluster import AgglomerativeClustering
###############################################################################
# Generate data
lena = sp.misc.lena()
# Downsample the image by a factor of 4
lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + lena[1::2, 1::2]
X = np.reshape(lena, (-1, 1))
###############################################################################
# Define the structure A of the data. Pixels connected to their neighbors.
connectivity = grid_to_graph(*lena.shape)
###############################################################################
# Compute clustering
print("Compute structured hierarchical clustering...")
st = time.time()
n_clusters = 15 # number of regions
ward = AgglomerativeClustering(n_clusters=n_clusters,
linkage='ward', connectivity=connectivity).fit(X)
label = np.reshape(ward.labels_, lena.shape)
print("Elapsed time: ", time.time() - st)
print("Number of pixels: ", label.size)
print("Number of clusters: ", np.unique(label).size)
特征凝聚:
我們已經知道稀疏性可以緩和高維災難。i.e相對於特征數量觀測樣例數量不足的情況。另一種方法是合並相似的特征:特征凝聚。這種方法通過在特征方向上進行聚類實現。在特征方向上聚類也可以理解為聚合轉置的數據。
digits = datasets.load_digits()
images = digits.images
X = np.reshape(images, (len(images), -1))
connectivity = grid_to_graph(*images[0].shape)
agglo = cluster.FeatureAgglomeration(connectivity=connectivity,
n_clusters=32)
agglo.fit(X)
X_reduced = agglo.transform(X)
X_approx = agglo.inverse_transform(X_reduced)
images_approx = np.reshape(X_approx, images.shape)
transeform
和invers_transeform
方法
有些模型帶有轉置方法。例如用來降低數據集的維度
(2)分解:從一個信號到成分和加載
成分及其加載:
如果X是我們的多變量數據,那么我們要要嘗試解決的問題就是在不同的觀測樣例上復寫寫它:我們想要學習加載L和其它一系列的成分C,如X = LC。存在不同的標准和條件去選擇成分。
- 主成分分析:PCA
主成分分析(PCA)選擇在信號上解釋極大方差的連續成分。
上面觀測樣例的點分布在一個方向上是非常平坦的:三個特征單變量的一個甚至可以有其他兩個准確的計算出來。PCA用來發現數據在哪個方向上是不平坦的。
當被用來轉換數據的時候,PCA可以通過投射到一個主子空間來降低數據的維度。:
# Create a signal with only 2 useful dimensions
x1 = np.random.normal(size=100)
x2 = np.random.normal(size=100)
x3 = x1 + x2
X = np.c_[x1, x2, x3]
from sklearn import decomposition
pca = decomposition.PCA()
pca.fit(X)
print(pca.explained_variance_)
# As we can see, only the 2 first components are useful
pca.n_components = 2
X_reduced = pca.fit_transform(X)
X_reduced.shape
- 獨立成分分析:ICA
獨立成分分析(ICA)選擇合適的成分使得他們的分布載有最大的獨立信息量。可以恢復非高斯獨立信號:
# Generate sample data
time = np.linspace(0, 10, 2000)
s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal
s2 = np.sign(np.sin(3 * time)) # Signal 2 : square signal
S = np.c_[s1, s2]
S += 0.2 * np.random.normal(size=S.shape) # Add noise
S /= S.std(axis=0) # Standardize data
# Mix data
A = np.array([[1, 1], [0.5, 2]]) # Mixing matrix
X = np.dot(S, A.T) # Generate observations
# Compute ICA
ica = decomposition.FastICA()
S_ = ica.fit_transform(X) # Get the estimated sources
A_ = ica.mixing_.T
np.allclose(X, np.dot(S_, A_) + ica.mean_)
五、聯合起來
(1)管道(流水線)
我們已經知道了一些估測器(模型)能夠轉換數據,一些可以預測變量。我們也能夠將其結合到一起:
from sklearn import linear_model, decomposition, datasets
from sklearn.pipeline import Pipeline
from sklearn.grid_search import GridSearchCV
logistic = linear_model.LogisticRegression()
pca = decomposition.PCA()
pipe = Pipeline(steps=[('pca', pca), ('logistic', logistic)])
digits = datasets.load_digits()
X_digits = digits.data
y_digits = digits.target
###############################################################################
# Plot the PCA spectrum
pca.fit(X_digits)
plt.figure(1, figsize=(4, 3))
plt.clf()
plt.axes([.2, .2, .7, .7])
plt.plot(pca.explained_variance_, linewidth=2)
plt.axis('tight')
plt.xlabel('n_components')
plt.ylabel('explained_variance_')
###############################################################################
# Prediction
n_components = [20, 40, 64]
Cs = np.logspace(-4, 4, 3)
#Parameters of pipelines can be set using ‘__’ separated parameter names:
estimator = GridSearchCV(pipe,
dict(pca__n_components=n_components,
logistic__C=Cs))
estimator.fit(X_digits, y_digits)
plt.axvline(estimator.best_estimator_.named_steps['pca'].n_components,
linestyle=':', label='n_components chosen')
plt.legend(prop=dict(size=12))
(2)使用特征聯進行人臉識別
該實例使用的數據集是從“Labeled Faces in the Wild”節選預處理得到的。更為熟知的名字是LFW。
http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz(233 MB)
"""
===================================================
Faces recognition example using eigenfaces and SVMs
===================================================
The dataset used in this example is a preprocessed excerpt of the
"Labeled Faces in the Wild", aka LFW_:
http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz (233MB)
.. _LFW: http://vis-www.cs.umass.edu/lfw/
Expected results for the top 5 most represented people in the dataset::
precision recall f1-score support
Gerhard_Schroeder 0.91 0.75 0.82 28
Donald_Rumsfeld 0.84 0.82 0.83 33
Tony_Blair 0.65 0.82 0.73 34
Colin_Powell 0.78 0.88 0.83 58
George_W_Bush 0.93 0.86 0.90 129
avg / total 0.86 0.84 0.85 282
"""
from __future__ import print_function
from time import time
import logging
import matplotlib.pyplot as plt
from sklearn.cross_validation import train_test_split
from sklearn.datasets import fetch_lfw_people
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import RandomizedPCA
from sklearn.svm import SVC
print(__doc__)
# Display progress logs on stdout
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
###############################################################################
# Download the data, if not already on disk and load it as numpy arrays
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
# introspect the images arrays to find the shapes (for plotting)
n_samples, h, w = lfw_people.images.shape
# for machine learning we use the 2 data directly (as relative pixel
# positions info is ignored by this model)
X = lfw_people.data
n_features = X.shape[1]
# the label to predict is the id of the person
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]
print("Total dataset size:")
print("n_samples: %d" % n_samples)
print("n_features: %d" % n_features)
print("n_classes: %d" % n_classes)
###############################################################################
# Split into a training set and a test set using a stratified k fold
# split into a training and testing set
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25)
###############################################################################
# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
# dataset): unsupervised feature extraction / dimensionality reduction
n_components = 150
print("Extracting the top %d eigenfaces from %d faces"
% (n_components, X_train.shape[0]))
t0 = time()
pca = RandomizedPCA(n_components=n_components, whiten=True).fit(X_train)
print("done in %0.3fs" % (time() - t0))
eigenfaces = pca.components_.reshape((n_components, h, w))
print("Projecting the input data on the eigenfaces orthonormal basis")
t0 = time()
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print("done in %0.3fs" % (time() - t0))
###############################################################################
# Train a SVM classification model
print("Fitting the classifier to the training set")
t0 = time()
param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
clf = GridSearchCV(SVC(kernel='rbf', class_weight='auto'), param_grid)
clf = clf.fit(X_train_pca, y_train)
print("done in %0.3fs" % (time() - t0))
print("Best estimator found by grid search:")
print(clf.best_estimator_)
###############################################################################
# Quantitative evaluation of the model quality on the test set
print("Predicting people's names on the test set")
t0 = time()
y_pred = clf.predict(X_test_pca)
print("done in %0.3fs" % (time() - t0))
print(classification_report(y_test, y_pred, target_names=target_names))
print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))
###############################################################################
# Qualitative evaluation of the predictions using matplotlib
def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
"""Helper function to plot a gallery of portraits"""
plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))
plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
for i in range(n_row * n_col):
plt.subplot(n_row, n_col, i + 1)
plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
plt.title(titles[i], size=12)
plt.xticks(())
plt.yticks(())
# plot the result of the prediction on a portion of the test set
def title(y_pred, y_test, target_names, i):
pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
return 'predicted: %s\ntrue: %s' % (pred_name, true_name)
prediction_titles = [title(y_pred, y_test, target_names, i)
for i in range(y_pred.shape[0])]
plot_gallery(X_test, prediction_titles, h, w)
# plot the gallery of the most significative eigenfaces
eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
plot_gallery(eigenfaces, eigenface_titles, h, w)
plt.show()
預測:
特征臉:
數據集中最有代表性的五個人臉的期望結果:
precision recall f1-score support
Gerhard_Schroeder 0.91 0.75 0.82 28
Donald_Rumsfeld 0.84 0.82 0.83 33
Tony_Blair 0.65 0.82 0.73 34
Colin_Powell 0.78 0.88 0.83 58
George_W_Bush 0.93 0.86 0.90 129
avg / total 0.86 0.84 0.85 282
(3)開放性問題:股票市場結構
我們是否可以根據給定的時間幀預測股票的價格變化。
[學習一個圖結構]
六、尋求幫助
(1)項目郵件列表
如果你碰到scikit-learn的BUG或者文檔中需要澄清聲明的部分,請放心大膽的在郵件列表里詢問[maillist]
(2)問答(Q&A)機器學習從業者參與的社區
-
Metaoptimize/QA:
一個 機器學習、自然語言處理和其他數據分析方面討論的論壇(類似針對開發者的Stackoverflow):http://metaoptimize.com/qa一個比較容易開始參與的討論:good freely available textbooks on machine learning(機器學習方面優秀的免費電子書)
-
Quora.com:
Quora 有一個關於機器學習相關的問題主題,也有很多有趣的討論:http://quora.com/Machine-learning瀏覽一下最佳問題的部分,例如:What are some good resources for learning about machine learning(關於機器學習的優秀資源有哪些)
-
---斯坦福的 Andrew Ng教授 教授的 關於機器學習的優秀在線免費課程
{網易公開課有,搜一下機器學習就可以了} -
---一個更傾向於人工智能(AI)的優秀在線課程:
http://www.udacity.com/overview/Course/cs271/CourseRev/1