【问题标题】:Coloring clusters着色簇
【发布时间】:2021-06-03 16:19:49
【问题描述】:

我正在使用以下代码执行 SOM(自组织图,也称为 Kohonen 网络)机器学习算法来可视化一些数据。然后,我在可视化上使用了一个聚类算法(我选择了 8 个聚类):

#load library
library(tidyverse)
library(kohonen)
library(GGally)
library(purrr)
library(tidyr)
library(dplyr)
library(mlr)

#load data
data(flea)
fleaTib <- as_tibble(flea)

#define SOM grid
somGrid <- somgrid(xdim = 5, ydim = 5, topo = "hexagonal",
neighbourhood.fct = "bubble", toroidal = FALSE)

#format data
fleaScaled <- fleaTib %>%
select(-species) %>%
scale()

#perform som
fleaSom <- som(fleaScaled, grid = somGrid, rlen = 5000,
alpha = c(0.05, 0.01))

par(mfrow = c(2, 3))
plotTypes <- c("codes", "changes", "counts", "quality",
"dist.neighbours", "mapping")
walk(plotTypes, ~plot(fleaSom, type = ., shape = "straight"))

getCodes(fleaSom) %>%
as_tibble() %>%
iwalk(~plot(fleaSom, type = "property", property = .,
main = .y, shape = "straight"))

# listing flea species on SOM

par(mfrow = c(1, 2))
nodeCols <- c("cyan3", "yellow", "purple", "red", "blue", "green", "white", "pink")
plot(fleaSom, type = "mapping", pch = 21,
bg = nodeCols[as.numeric(fleaTib$species)],
shape = "straight", bgcol = "lightgrey")

# CLUSTER AND ADD TO SOM MAP ---- (8 clusters)
clusters <- cutree(hclust(dist(fleaSom$codes[[1]], 
                               method = "manhattan")), 8)

somClusters <- map_dbl(clusters, ~{
    if(. == 1) 3
    else if(. == 2) 2
    else 1
}
)


plot(fleaSom, type = "mapping", pch = 21, 
     bg = nodeCols[as.numeric(fleaTib$species)],
     shape = "straight",
     bgcol = nodeCols[as.integer(somClusters)])

add.cluster.boundaries(fleaSom, somClusters)

但在上图中,只显示了 3 种颜色而不是 8 种。

谁能告诉我我做错了什么?

【问题讨论】:

    标签: r machine-learning colors data-visualization cluster-analysis


    【解决方案1】:

    在最后一个图中背景颜色的定义中将somClusters 替换为clusters。主要问题是您将 somClusters 定义为具有三个值,而不是 8。如果您使用它来索引颜色向量,它将只有三种颜色。

    plot(fleaSom, type = "mapping", pch = 21, 
         bg = nodeCols[as.numeric(fleaTib$species)],
         shape = "straight",
         bgcol = nodeCols[as.integer(clusters)])
    
    add.cluster.boundaries(fleaSom, somClusters)
    

    【讨论】:

    • 非常感谢您的回答!只是一个问题:是否可以跳过这行代码 "nodeCols
    • 您需要以某种方式提供颜色。如果您愿意,您可以使用RColorBrewer 调色板,甚至可以使用rainbow(8)[as.integer(clusters)]。这是一个基本的 R 图,所以它不像 ggplot 那样你可以告诉它是什么变量定义了颜色,它会为你挑选它们。
    • 感谢您的回复!你的意思是这样的:nodeCols
    • 不,您可以将bgcol = nodeCols[as.integer(clusters)]) 替换为bgcol = rainbow(8)[as.integer(clusters)]
    猜你喜欢
    • 1970-01-01
    • 2020-06-04
    • 2021-02-17
    • 2023-03-12
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2013-09-17
    相关资源
    最近更新 更多