【问题标题】:Return multiple lists with foreach使用 foreach 返回多个列表
【发布时间】:2021-03-26 14:45:08
【问题描述】:

我正在做一些 kmeans 聚类分析。示例:

library(tidyverse)
library(foreach)

my_diamonds <- diamonds %>% select_if(is.numeric) %>% scale %>% as.data.frame
try_centers <- seq(from = 3, to = 12, by = 1)

wss_list <- foreach(k = try_centers) %do% { # forget parallel processing with this size of data not enough ram
  print(k) # progress bar
  hw = kmeans(my_diamonds, centers = k, iter.max = 20, nstart = 3, algorithm = 'Hartigan-Wong') 
}

wss <- lapply(wss_list, function(i) i$tot.withinss) %>% unlist()
plot(try_centers, wss)

这将返回平方和内方差图:

但我想与其他两种 kmeans 算法进行比较。试过了:

wss_list <- foreach(k = try_centers) %do% { # forget parallel processing with this size of data not enough ram
  print(k) # progress bar
  hw = kmeans(my_diamonds, centers = k, iter.max = 20, nstart = 3, algorithm = 'Hartigan-Wong') 
  lloyd = kmeans(my_diamonds, centers = k, iter.max = 20, nstart = 3, algorithm = 'Lloyd')
  mac = kmeans(my_diamonds, centers = k, iter.max = 20, nstart = 3, algorithm = 'MacQueen')
}

wss <- lapply(wss_list, function(i) i$tot.withinss) %>% unlist()
plot(try_centers, wss)

这确实返回了一个情节,但我在看哪一个?!马皇后?劳埃德?

我如何构造它以在每次迭代中使用三种算法运行 kmeans,然后在 3 种算法中的每一种上绘制一个图表?

【问题讨论】:

  • 您需要返回一个list(hw, lloyd, mac)

标签: r


【解决方案1】:

如果我们不指定return,它将只返回最后创建的对象。我们可以在return 中拥有list 的对象

wss_list <- foreach(k = try_centers) %do% { # forget parallel processing with this size of data not enough ram
  print(k) # progress bar
  hw = kmeans(my_diamonds, centers = k, iter.max = 20, nstart = 3, algorithm = 'Hartigan-Wong') 
  lloyd = kmeans(my_diamonds, centers = k, iter.max = 20, nstart = 3, algorithm = 'Lloyd')
  mac = kmeans(my_diamonds, centers = k, iter.max = 20, nstart = 3, algorithm = 'MacQueen')
  
  return(dplyr::lst(hw, lloyd, mac))
}

然后,我们可以提取每个组件

library(purrr)
hw <- map(wss_list, ~ .x$hw)
lloyd <- map(wss_list, ~ .x$lloyd)
mac <- map(wss_list, ~ .x$mac)

transposelist 创建三个list

wss_list1 <- wss_list %>%
              transpose 
names(wss_list1)
#[1] "hw"    "lloyd" "mac"  

现在,我们plot作为

wss <- lapply(wss_list1$hw, function(i) i$tot.withinss) %>% 
       unlist()
plot(try_centers, wss)

同样的方法,我们用其他组件来做

wss2 <- lapply(wss_list1$lloyd, function(i) i$tot.withinss) %>% 
      unlist()
plot(try_centers, wss2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多