tSNE算法的原理和Python代码实现详解
T分布随机邻域嵌入(t-SNE),是一种用于可视化的无监督机器学习算法,使用非线性降维技术,根据数据点与特征的相似性,试图最小化高维和低维空间中这些条件概率(或相似性)之间的差异,以在低维空间中完美表示数据点。
因此,t-SNE擅长在二维或三维的低维空间中嵌入高维数据以进行可视化。需要注意的是,t-SNE使用重尾分布来计算低维空间中两点之间的相似度,而不是高斯分布,这有助于解决拥挤和优化问题。而且离群值不影响t-SNE。
t-SNE算法步骤
1.找出高维空间中相邻点之间的成对相似性。
2.根据高维空间中点的成对相似性,将高维空间中的每个点映射到低维映射。
3.使用基于Kullback-Leibler散度(KL散度)的梯度下降找到最小化条件概率分布之间的不匹配的低维数据表示。
4.使用Student-t分布计算低维空间中两点之间的相似度。
MNIST数据集上实现t-SNE的Python代码
导入模块
# Importing Necessary Modules. import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.manifold import TSNE from sklearn.preprocessing import StandardScaler登录后复制
# Reading the data using pandas df = pd.read_csv('mnist_train.csv') 1. print first five rows of df print(df.head(4)) 1. save the labels into a variable l. l = df['label'] 1. Drop the label feature and store the pixel data in d. d = df.drop("label", axis = 1)登录后复制
# Data-preprocessing: Standardizing the data from sklearn.preprocessing import StandardScaler standardized_data = StandardScaler().fit_transform(data) print(standardized_data.shape)登录后复制
# TSNE 1. Picking the top 1000 points as TSNE 1. takes a lot of time for 15K points data_1000 = standardized_data[0:1000, :] labels_1000 = labels[0:1000] model = TSNE(n_components = 2, random_state = 0) 1. configuring the parameters 1. the number of components = 2 1. default perplexity = 30 1. default learning rate = 200 1. default Maximum number of iterations 1. for the optimization = 1000 tsne_data = model.fit_transform(data_1000) 1. creating a new data frame which 1. help us in plotting the result data tsne_data = np.vstack((tsne_data.T, labels_1000)).T tsne_df = pd.DataFrame(data = tsne_data, columns =("Dim_1", "Dim_2", "label")) 1. Plotting the result of tsne sn.FacetGrid(tsne_df, hue ="label", size = 6).map( plt.scatter, 'Dim_1', 'Dim_2').add_legend() plt.show()登录后复制
以上就是t-SNE算法的原理和Python代码实现详解的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!