R语言 如何制作t-SNE图

R语言 如何制作t-SNE图

tSNE 是t-Distributed Neighbor Embedding的首字母缩写,是一种统计方法,主要用于可视化高维数据。在R编程中,tSNE图可以用Rtsne和ggplot2包来绘制。

语法: Rtsne(x, dims, theta, pca, verbose, perplexity)

其中。

  • x-需要绘制的数据矩阵在此指定。
  • dims- 用于指定绘图的尺寸
  • theta – 绘图的速度/准确度交易(默认为-0.5)
  • pca – 在这里指定PCA设置(默认为TRUE)。
  • verbose – 要打印更新的进度,需要将此设置为TRUE
  • perplexity – 数据之间的混淆状态(应小于3)。

在R中绘制tSNE图的步骤是

  1. 首先,我们需要安装并加载所有需要的软件包。
  2. 加载默认的数据集iris来绘制tSNE。
  3. 从数据集中删除所有重复的数据
  4. 计算数据集中的关系
  5. 绘制tSNE图

安装模块

在本文中, Rtsneggplot2 是需要的模块。

# Install all the required packages
install.packages("Rtsne")
install.packages("ggplot2")
 
# Load the required packages
library(Rtsne)
library(ggplot2)

加载数据集

我们将使用虹膜数据集。

# Load the default dataset
data(iris)

从数据集中删除重复的数据

我们需要从数据集中删除所有重复的数据,否则Rtsne()函数会产生错误,因为它在后端使用t分布,不允许有重复的数据,需要将数据框转换为矩阵,以传递给Rtsne()函数。

# Remove Duplicate data present in iris
# data set(Otherwise Error will be generated)
remove_iris_dup <- unique(iris)
 
# Forming the matrix for the first four columns
# of iris dataset because fifth column is of string type(Species)
iris_matrix <- as.matrix(remove_iris_dup[,1:4])

计算数据集的关系

使用Rtsne()函数,我们将计算虹膜数据集的数据之间的相似性和差异。

# Calculate tSNE using Rtsne(0 function)
tsne_out <- Rtsne(iris_matrix)

绘制tSNE()图

最后,我们将使用ggplot()函数绘制tSNE图,但ggplot函数只接受数据框架作为输入,我们需要将从Rtsne函数中获得的矩阵转换为(即tnse_out)

# Conversion of matrix to dataframe
tsne_plot <- data.frame(x = tsne_outY[,1],
                        y = tsne_outY[,2])
 
# Plotting the plot using ggplot() function
ggplot2::ggplot(tsne_plot,label=Species)
                + geom_point(aes(x=x,y=y))

输出

如何在R中制作t-SNE图

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程