比PCA降維更高級——(R/Python)t-SNE聚類算法實踐指南
首發地址:https://yq.aliyun.com/articles/70733
作者介紹:Saurabh.jaju2
攻讀信息和數據科學碩士學位,熱衷於開發基於數據科學的智能資源管理係統。
Github: https://github.com/saurabhjaju2
許多數據科學家經常麵對的問題之一:假設有一個包含數百個特征(變量)的數據集,且對數據所屬的域沒有任何了解,需要對該數據集識別其隱藏狀態、探索並分析。本文將介紹一種非常強大的方法來解決該問題。
PCA
1 什麼是t-SNE?
2 什麼是降維?
R語言
Python語言
9 應用方麵
10 常見錯誤
1
2
3 t-SNE
常用的降維算法有:
1 PCA(線性)
——
PCA
線性降維算法的一個主要問題是不相似的數據點放置在較低維度表示為相距甚遠。但為了在低維度用非線性流形表示高維數據,相似數據點必須表示為非常靠近,這不是線性降維算法所能做的。
4 t-SNE
4.1
1
SNExi、xj之間的條件概率pj|i由下式給出:
σi是以數據點xi為中心的高斯方差。
2
xi和xj的低維對應點yi和yjqj|i
3
SNE
4
4.2
5 t-SNE
t-SNE非線性降維算法通過基於具有多個特征的數據點的相似性識別觀察到的簇來在數據中找到模式。本質上是一種降維和可視化技術。另外t-SNE的輸出可以作為其他分類算法的輸入特征。
6
t-SNE幾乎可用於所有高維數據集,廣泛應用於圖像處理,自然語言處理,基因組數據和語音處理。實例有:麵部表情識別[2]、識別腫瘤亞群[3][4]等。
7 t-SNE
,能夠提供更好的結果。這是因為算法定義了數據的局部和全局結構之間的軟邊界。
8
MNIST
“”
## calling the installed package
train<‐ read.csv(file.choose()) ## Choose the train.csv file downloaded from the link above
library(Rtsne)
## Curating the database for analysis with both t‐SNE and PCA
Labels<‐train$label
train$label<‐as.factor(train$label)
## for plotting
colors = rainbow(length(unique(train$label)))
names(colors) = unique(train$label)
## Executing the algorithm on curated data
tsne <‐ Rtsne(train[,‐1], dims = 2, perplexity=30, verbose=TRUE, max_iter = 500)
exeTimeTsne<‐ system.time(Rtsne(train[,‐1], dims = 2, perplexity=30, verbose=TRUE, max_iter = 50
0))
## Plotting
plot(tsne$Y, t='n', main="tsne")
text(tsne$Y, labels=train$label, col=colors[train$label])
2 Python
以下代碼來自sklearn網站上的sklearn示例。
1
## importing the required packages
from time import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import offsetbox
from sklearn import (manifold, datasets, decomposition, ensemble,
discriminant_analysis, random_projection)
## Loading and curating the data
digits = datasets.load_digits(n_class=10)
X = digits.data
y = digits.target
n_samples, n_features = X.shape
n_neighbors = 30
## Function to Scale and visualize the embedding vectors
def plot_embedding(X, title=None):
x_min, x_max = np.min(X, 0), np.max(X, 0)
X = (X ‐ x_min) / (x_max ‐ x_min)
plt.figure()
ax = plt.subplot(111)
for i in range(X.shape[0]):
plt.text(X[i, 0], X[i, 1], str(digits.target[i]),
color=plt.cm.Set1(y[i] / 10.),
fontdict={'weight': 'bold', 'size': 9})
if hasattr(offsetbox, 'AnnotationBbox'):
## only print thumbnails with matplotlib > 1.0
shown_images = np.array([[1., 1.]]) # just something big
for i in range(digits.data.shape[0]):
dist = np.sum((X[i] ‐ shown_images) ** 2, 1)
if np.min(dist) < 4e‐3:
## don't show points that are too close
continue
shown_images = np.r_[shown_images, [X[i]]]
imagebox = offsetbox.AnnotationBbox(
offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r),
X[i])
ax.add_artist(imagebox)
plt.xticks([]), plt.yticks([])
if title is not None:
plt.title(title)
#‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
## Plot images of the digits
n_img_per_row = 20
img = np.zeros((10 * n_img_per_row, 10 * n_img_per_row))
for i in range(n_img_per_row):
ix = 10 * i + 1
for j in range(n_img_per_row):
iy = 10 * j + 1
img[ix:ix + 8, iy:iy + 8] = X[i * n_img_per_row + j].reshape((8, 8))
plt.imshow(img, cmap=plt.cm.binary)
plt.xticks([])
plt.yticks([])
plt.title('A selection from the 64‐dimensional digits dataset')
## Computing PCA
print("Computing PCA projection")
t0 = time()
X_pca = decomposition.TruncatedSVD(n_components=2).fit_transform(X)
plot_embedding(X_pca,
"Principal Components projection of the digits (time %.2fs)" %
(time() ‐ t0))
## Computing t‐SNE
print("Computing t‐SNE embedding")
tsne = manifold.TSNE(n_components=2, init='pca', random_state=0)
t0 = time()
X_tsne = tsne.fit_transform(X)
plot_embedding(X_tsne,
"t‐SNE embedding of the digits (time %.2fs)" %
(time() ‐ t0))
plt.show()
9
9.1
9.2
9.3
NLP
10
t-SNE1
2
3
4
5
6 困惑水平可以觀察到不同的簇形狀。
7
本文由北郵@愛可可-愛生活老師推薦,阿裏雲雲棲社區組織翻譯。
Comprehensive Guide on t-SNE algorithm with implementation in R & Python
最後更新:2017-07-12 22:10:36