Error: Mean Distance Between Objects Zero

Error: Mean Distance Between Objects Zero

我正在尝试了解 R 中的“kohonen”包。特别是,有一个名为“supersom()”的函数(https://www.rdocumentation.org/packages/kohonen/versions/3.0.10/topics/supersom,对应于所使用的 SOM(自组织映射)算法在无监督机器学习中),我正在尝试将其应用于某些数据。

下面,(来自上一个问题:)我学习了如何将“supersom()”函数应用于一些人工创建的具有“因子”和“数字”变量的数据。

#the following code works

#load libraries 
    library(kohonen)
    library(dplyr)
    
#create and format data

a =rnorm(1000,10,10)
b = rnorm(1000,10,5)
c = rnorm(1000,5,5)
d = rnorm(1000,5,10)
e <- sample( LETTERS[1:4], 100 , replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
f <- sample( LETTERS[1:5], 100 , replace=TRUE, prob=c(0.2, 0.2, 0.2, 0.2, 0.2) )
g <- sample( LETTERS[1:2], 100 , replace=TRUE, prob=c(0.5, 0.5) )

data = data.frame(a,b,c,d,e,f,g)
data$e = as.factor(data$e)
data$f = as.factor(data$f)
data$g = as.factor(data$g)

cols <- 1:4
data[cols] <- scale(data[cols])

#som model
som <- supersom(data= as.list(data), grid = somgrid(10,10, "hexagonal"), 
                dist.fct = "euclidean", keep.data = TRUE)

一切正常 - 问题是,当我尝试对“更真实和更大的数据”应用“supersom()”函数时,出现以下错误:

"Error: Non-informative layers present : mean distances between objects zero"

当我查看此函数 (https://rdrr.io/cran/kohonen/src/R/supersom.R) 的源代码时,我注意到了相同错误的引用:

  if (any(sapply(meanDistances, mean) < .Machine$double.eps))
        stop("Non-informative layers present: mean distance between objects zero")
      

有人可以告诉我如何解决这个错误,即让“supersom()”函数处理因子和数值数据吗?

我想也许删除重复的行和 NA 可能会解决这个问题:

data <- na.omit(data)
data <- unique(data)

然而,同样的错误(“存在非信息层:对象之间的平均距离为零”)仍然存在。

谁能帮我弄清楚是什么原因导致了这个错误?注意:当我删除“因素”变量时,一切正常。

来源:

https://cran.r-project.org/web/packages/kohonen/kohonen.pdf

https://www.rdocumentation.org/packages/kohonen/versions/2.0.5/topics/supersom

https://rdrr.io/cran/kohonen/src/R/supersom.R

如果您的某些数字列的平均值为 0,则会发生错误。您可以通过将任何 1 列变为 0 来重现该错误。

data$a <- 0
som <- supersom(data= as.list(data), grid = somgrid(10,10, "hexagonal"), 
                dist.fct = "euclidean", keep.data = TRUE)

Error in supersom(data = as.list(data), grid = somgrid(10, 10, "hexagonal"), : Non-informative layers present: mean distance between objects zero

也许您可以调查为什么这些列的均值为 0 或从数据中删除均值为 0 的列。

library(kohonen)
library(dplyr)

data <- data %>% select(where(~(is.numeric(.) && mean(.) > 0) | !is.numeric(.)))
#som model
som <- supersom(data= as.list(data), grid = somgrid(10,10, "hexagonal"), 
                dist.fct = "euclidean", keep.data = TRUE)