# 無監督學習: 尋求數據表示
校驗者:
[@片刻](https://github.com/apachecn/scikit-learn-doc-zh)
翻譯者:
[@X](https://github.com/apachecn/scikit-learn-doc-zh)
## 聚類: 對樣本數據進行分組
可以利用聚類解決的問題
對于 iris 數據集來說,我們知道所有樣本有 3 種不同的類型,但是并不知道每一個樣本是那種類型:此時我們可以嘗試一個 **clustering task(聚類任務)** 聚類算法: 將樣本進行分組,相似的樣本被聚在一起,而不同組別之間的樣本是有明顯區別的,這樣的分組方式就是 *clusters(聚類)*
### K-means 聚類算法
關于聚類有很多不同的聚類標準和相關算法,其中最簡便的算法是 [K-means](../../modules/clustering.html#k-means) 。
[](../../auto_examples/cluster/plot_cluster_iris.html)
```
>>> 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)
KMeans(algorithm='auto', copy_x=True, init='k-means++', ...
>>> print(k_means.labels_[::10])
[1 1 1 1 1 0 0 0 0 0 2 2 2 2 2]
>>> print(y_iris[::10])
[0 0 0 0 0 1 1 1 1 1 2 2 2 2 2]
```
Warning
k\_means 算法無法保證聚類結果完全絕對真實的反應實際情況。首先,選擇正確合適的聚類數量不是一件容易的事情,第二,該算法對初始值的設置敏感,容易陷入局部最優。盡管 scikit-learn 采取了不同的方式來緩解以上問題,目前仍沒有完美的解決方案。
[](../../auto_examples/cluster/plot_cluster_iris.html)[](../../auto_examples/cluster/plot_cluster_iris.html)[](../../auto_examples/cluster/plot_cluster_iris.html)**Bad initialization****8 clusters****Ground truth****Don’t over-interpret clustering results(不要過分解讀聚類結果)**
**Application example: vector quantization(應用案例:向量量化(vector quantization))**
一般來說聚類,特別是 K\_means 聚類可以作為一種用少量樣本來壓縮信息的方式。這種方式就是 [vector quantization](https://en.wikipedia.org/wiki/Vector_quantization) 。例如,K\_means 算法可以用于對一張圖片進行色調分離:
```
>>> import scipy as sp
>>> try:
... face = sp.face(gray=True)
... except AttributeError:
... from scipy import misc
... face = misc.face(gray=True)
>>> X = face.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)
KMeans(algorithm='auto', copy_x=True, init='k-means++', ...
>>> values = k_means.cluster_centers_.squeeze()
>>> labels = k_means.labels_
>>> face_compressed = np.choose(labels, values)
>>> face_compressed.shape = face.shape
```
[](../../auto_examples/cluster/plot_face_compress.html)[](../../auto_examples/cluster/plot_face_compress.html)[](../../auto_examples/cluster/plot_face_compress.html)[](../../auto_examples/cluster/plot_face_compress.html)Raw imageK-means quantizationEqual binsImage histogram
### 分層聚類算法: 謹慎使用
[層次聚類](../../modules/clustering.html#hierarchical-clustering) (分層聚類算法)是一種旨在構建聚類層次結構的分析方法,一般來說,實現該算法的大多數方法有以下兩種:- **Agglomerative(聚合)** - 自底向上的方法: 初始階段,每一個樣本將自己作為單獨的一個簇,聚類的簇以最小
化距離的標準進行迭代聚合。當感興趣的簇只有少量的樣本時,該方法是很合適的。如果需要聚類的 簇數量很大,該方法比K\_means算法的計算效率也更高。 \* **Divisive(分裂)** - 自頂向下的方法: 初始階段,所有的樣本是一個簇,當一個簇下移時,它被迭代的進 行分裂。當估計聚類簇數量較大的數據時,該算法不僅效率低(由于樣本始于一個簇,需要被遞歸的進行 分裂),而且從統計學的角度來講也是不合適的。
#### 連接約束聚類
對于逐次聚合聚類,通過連接圖可以指定哪些樣本可以被聚合在一個簇。在 scikit 中,圖由鄰接矩陣來表示,通常該矩陣是一個稀疏矩陣。這種表示方法是非常有用的,例如在聚類圖像時檢索連接區域(有時也被稱為連接要素):
[](../../auto_examples/cluster/plot_face_ward_segmentation.html)
```
import matplotlib.pyplot as plt
from sklearn.feature_extraction.image import grid_to_graph
from sklearn.cluster import AgglomerativeClustering
# #############################################################################
# Generate data
try: # SciPy >= 0.16 have face in misc
from scipy.misc import face
face = face(gray=True)
except ImportError:
face = sp.face(gray=True)
# Resize it to 10% of the original size to speed up the processing
face = sp.misc.imresize(face, 0.10) / 255.
X = np.reshape(face, (-1, 1))
# #############################################################################
# Define the structure A of the data. Pixels connected to their neighbors.
connectivity = grid_to_graph(*face.shape)
# #############################################################################
```
#### 特征聚集
我們已經知道,稀疏性可以緩解特征維度帶來的問題,*i.e* 即與特征數量相比,樣本數量太少。 另一個解決該問題的方式是合并相似的維度:**feature agglomeration(特征聚集)**。該方法可以通過對特征聚類來實現。換 句話說,就是對樣本數據轉置后進行聚類。
[](../../auto_examples/cluster/plot_digits_agglomeration.html)
```
>>> 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)
FeatureAgglomeration(affinity='euclidean', compute_full_tree='auto',...
>>> X_reduced = agglo.transform(X)
>>> X_approx = agglo.inverse_transform(X_reduced)
>>> images_approx = np.reshape(X_approx, images.shape)
```
`transform` and `inverse_transform` methods
Some estimators expose a `transform` method, for instance to reduce the dimensionality of the dataset.
## 分解: 將一個信號轉換成多個成份并且加載
**Components and loadings(成分和載荷)**
如果 X 是多維數據,那么我們試圖解決的問題是在不同的觀察基礎上對數據進行重寫。我們希望學習得到載荷 L 和成分 C 使得 *X = L C* 。提取成分 C 有多種不同的方法。
### 主成份分析: PCA
[主成分分析(PCA)](../../modules/decomposition.html#pca) 將能夠解釋數據信息最大方差的的連續成分提取出來
[](../../auto_examples/decomposition/plot_pca_3d.html) [](../../auto_examples/decomposition/plot_pca_3d.html)
上圖中樣本點的分布在一個方向上是非常平坦的:即三個單變量特征中的任何一個都可以有另外兩個特征來表示。主成分分析法(PCA)可以找到使得數據分布不 *flat* 的矢量方向(可以反映數據主要信息的特征)。
當用主成分分析(PCA)來 *transform(轉換)* 數據時,可以通過在子空間上投影來降低數據的維數。
```
>>> # 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)
PCA(copy=True, iterated_power='auto', n_components=None, random_state=None,
svd_solver='auto', tol=0.0, whiten=False)
>>> print(pca.explained_variance_)
[ 2.18565811e+00 1.19346747e+00 8.43026679e-32]
>>> # As we can see, only the 2 first components are useful
>>> pca.n_components = 2
>>> X_reduced = pca.fit_transform(X)
>>> X_reduced.shape
(100, 2)
```
### 獨立成分分析: ICA
[獨立成分分析(ICA)](../../modules/decomposition.html#ica) 可以提取數據信息中的獨立成分,這些成分載荷的分布包含了最多的 的獨立信息。該方法能夠恢復 **non-Gaussian(非高斯)** 獨立信號:
[](../../auto_examples/decomposition/plot_ica_blind_source_separation.html)
```
>>> # Generate sample data
>>> import numpy as np
>>> from scipy import signal
>>> 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
>>> s3 = signal.sawtooth(2 * np.pi * time) # Signal 3: saw tooth signal
>>> S = np.c_[s1, s2, s3]
>>> 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, 1], [0.5, 2, 1], [1.5, 1, 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_)
True
```
- scikit-learn 0.19 中文文檔
- 用戶指南
- 1. 監督學習
- 1.1. 廣義線性模型
- 1.2. 線性和二次判別分析
- 1.3. 內核嶺回歸
- 1.4. 支持向量機
- 1.5. 隨機梯度下降
- 1.6. 最近鄰
- 1.7. 高斯過程
- 1.8. 交叉分解
- 1.9. 樸素貝葉斯
- 1.10. 決策樹
- 1.11. 集成方法
- 1.12. 多類和多標簽算法
- 1.13. 特征選擇
- 1.14. 半監督學習
- 1.15. 等式回歸
- 1.16. 概率校準
- 1.17. 神經網絡模型(有監督)
- 2. 無監督學習
- 2.1. 高斯混合模型
- 2.2. 流形學習
- 2.3. 聚類
- 2.4. 雙聚類
- 2.5. 分解成分中的信號(矩陣分解問題)
- 2.6. 協方差估計
- 2.7. 經驗協方差
- 2.8. 收斂協方差
- 2.9. 稀疏逆協方差
- 2.10. Robust 協方差估計
- 2.11. 新奇和異常值檢測
- 2.12. 密度估計
- 2.13. 神經網絡模型(無監督)
- 3. 模型選擇和評估
- 3.1. 交叉驗證:評估估算器的表現
- 3.2. 調整估計器的超參數
- 3.3. 模型評估: 量化預測的質量
- 3.4. 模型持久化
- 3.5. 驗證曲線: 繪制分數以評估模型
- 4. 數據集轉換
- 4.1. Pipeline(管道)和 FeatureUnion(特征聯合): 合并的評估器
- 4.2. 特征提取
- 4.3. 預處理數據
- 4.4. 無監督降維
- 4.5. 隨機投影
- 4.6. 內核近似
- 4.7. 成對的矩陣, 類別和核函數
- 4.8. 預測目標 (y) 的轉換
- 5. 數據集加載工具
- 6. 大規模計算的策略: 更大量的數據
- 7. 計算性能
- 教程
- 使用 scikit-learn 介紹機器學習
- 關于科學數據處理的統計學習教程
- 機器學習: scikit-learn 中的設置以及預估對象
- 監督學習:從高維觀察預測輸出變量
- 模型選擇:選擇估計量及其參數
- 無監督學習: 尋求數據表示
- 把它們放在一起
- 尋求幫助
- 處理文本數據
- 選擇正確的評估器(estimator)
- 外部資源,視頻和談話