我把所有的过程全写入下面的代码注释中了。 主要流程有:
- 将mnist数据集的64维转化为2维矩阵向量。(利用scikit-learn库中的TSNE库)
- 将转化好的矩阵输出到二维空间中即可。
参考了官方的代码:scikit-learn/t-SNE
得到的结果如下图所示:
图1 选择Mnist数据集前100张图片
图2 用t-SNE可视化Mnist数据集前6种类
大约花了49s的时间,通过可视化发现每个样本降维后相同的类基本可以聚到一起。
代码如下:
from sklearn.datasets import load_digits
digits = load_digits(n_class=6)
X, y = digits.data, digits.target
n_samples, n_features = X.shape
n_neighbors = 30
import matplotlib.pyplot as plt
fig, axs = plt.subplots(nrows=10, ncols=10, figsize=(6, 6))
for idx, ax in enumerate(axs.ravel()):
ax.imshow(X[idx].reshape((8, 8)), cmap=plt.cm.binary)
ax.axis("off")
_ = fig.suptitle("A selection from the 64-dimensional digits dataset", fontsize=16)
fig.show()
import numpy as np
from matplotlib import offsetbox
from sklearn.preprocessing import MinMaxScaler
def plot_embedding(X, title, ax):
X = MinMaxScaler().fit_transform(X)
shown_images = np.array([[1.0, 1.0]])
for i in range(X.shape[0]):
ax.text(
X[i, 0],
X[i, 1],
str(y[i]),
color=plt.cm.Dark2(y[i]),
fontdict={"weight": "bold", "size": 9},
)
dist = np.sum((X[i] - shown_images) ** 2, 1)
if np.min(dist) < 4e-3:
continue
shown_images = np.concatenate([shown_images, [X[i]]], axis=0)
imagebox = offsetbox.AnnotationBbox(
offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i]
)
ax.add_artist(imagebox)
ax.set_title(title)
ax.axis("off")
from sklearn.manifold import TSNE
embeddings = {
"t-SNE embeedding": TSNE(
n_components=2, init='pca', learning_rate=200.0, random_state=0
),
}
from time import time
projections, timing = {}, {}
for name, transformer in embeddings.items():
if name.startswith("Linear Discriminant Analysis"):
data = X.copy()
data.flat[:: X.shape[1] + 1] += 0.01
else:
data = X
print(f"Computing {name}...")
start_time = time()
print(data.shape, type(data.shape))
data = data.astype(np.float)
y = y.astype(np.float)
projections[name] = transformer.fit_transform(data, y)
timing[name] = time() - start_time
fig, ax = plt.subplots()
ax.axis("off")
title = f"{name} (time {timing[name]:.3f}s)"
plot_embedding(projections[name], title, ax)
plt.show()
|