比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