r - 将新数据呈现给适合的自组织映射并将行分配给集群

标签 r

我正在使用此代码,它适用于自组织映射 (SOM),然后对生成的原型(prototype)向量进行聚类以定义聚类边界:

library(dplyr)
library(kohonen)

setwd('C:\\Users\\Bla\\Source\\Repos\\SomeExcitingRepo')

OrginalData <- read.table("IrisData.txt",
                   header = TRUE, sep = "\t")

SubsetData <- subset(OrginalData, select = c("SepalLength", "SepalWidth", "PetalLength", "PetalWidth"))
TrainingMatrix <- as.matrix(scale(SubsetData))

GridDefinition <- somgrid(xdim = 4, ydim = 4, topo = "hexagonal")

SomModel <- kohonen::supersom(data = TrainingMatrix, grid = GridDefinition, rlen = 1000, alpha = c(0.05, 0.01),
             keep.data = TRUE)
groups = 3
iris.hc = cutree(hclust(dist(SomModel$codes[[1]])), groups)

plot(SomModel, type = "codes", bgcol = rainbow(groups)[iris.hc])
add.cluster.boundaries(SomModel, iris.hc)

数据是 iris 数据集,但这只是一个例子。数据集格式如下:

Uid SepalLength SepalWidth  PetalLength PetalWidth  Species
1   5.1 3.5 1.4 0.2 setosa

现在让我们假设这是一个看不见的数据集。我想对其进行规范化并将其呈现给 SOM,然后向每一行添加额外的列,指示 SOM 集群编号(1、2、3 见上例)和获胜节点的 x 和 y 坐标。示例:

Uid SepalLength SepalWidth PetalLength PetalWidth Species Cluster X Y
1 5.1 3.5 1.4 0.2 setosa 3 3 4

最佳答案

您可以使用unit.classif 来索引集群或网格点:

result <- OrginalData
result$Cluster <- iris.hc[SomModel$unit.classif]
result$X <- SomModel$grid$pts[SomModel$unit.classif,"x"]
result$Y <- SomModel$grid$pts[SomModel$unit.classif,"y"]

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species Cluster   X         Y
1          5.1         3.5          1.4         0.2  setosa       1 1.5 2.5980762
2          4.9         3.0          1.4         0.2  setosa       1 1.0 3.4641016
3          4.7         3.2          1.3         0.2  setosa       1 1.0 3.4641016
4          4.6         3.1          1.5         0.2  setosa       1 1.0 3.4641016
5          5.0         3.6          1.4         0.2  setosa       1 1.0 1.7320508
6          5.4         3.9          1.7         0.4  setosa       1 1.5 0.8660254

虽然看起来不太好:

points(jitter(result$X), jitter(result$Y), col=result$Species)
legend(5,0, legend=unique(result$Species), col=unique(result$Species), pch=1)

enter image description here

关于r - 将新数据呈现给适合的自组织映射并将行分配给集群,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43988425/

相关文章:

r - 开发sliderInput的最小值/最大值的 react 性变化

r - Dplyr : How can i calculate proportional means?

r - 如何在 ggtree 中绘制彩色提示标签而不将其作为图例的一部分?

r - 在 R 上运行 CellNet 时未加载 dyld

r - 使用 R 为多个文件自动执行任务以重新排列 R 工作目录中的源数据文件

r - 如何将表格添加到我的 ggplot2 输出?

r - R `+` 运算符如何知道根据类的不同表现不同?

r - Magrittr 函数 - 如何打包它们?

r - 具有各种 IF 的矢量,加法和减法

r - 在ggplot2中仅绘制stat_smooth的边界