gpt4 book ai didi

r - 如何处理 K-means 函数中的 "empty cluster"警告?

转载 作者:行者123 更新时间:2023-12-03 07:43:13 30 4
gpt4 key购买 nike

我正在从 amap 包的 Kmeans 函数中寻找处理警告消息的解决方案。警告信息如下:

空簇:尝试一组更好的初始中心

有没有办法让我得到一个信号,这样我就可以知道什么时候抛出这个错误信息,然后处理这个问题? (例如:运行算法直到返回没有空簇)

很难为我制作一个很好的可重现示例。但是,我带来了这个丑陋但实用的东西:

library(amap)

numberK = 20
ts.len = 7

time.series <- rep(sample(1:8000, numberK, replace = TRUE),ts.len)
time.series <- rep(rbind(time.series, time.series), 30)
time.series <- matrix(time.series, ncol = ts.len)

centers <- matrix( sample(1:3000, numberK*ts.len), ncol = ts.len)

Kmeans((time.series), centers = centers, iter.max = 99)

如果您在终端上运行它,它可能会向您发送我正在谈论的警告消息。

注意: 我解决这个问题的想法是捕捉警告信号,然后执行解决方案。但是,我不知道我怎么可能那样做

最佳答案

来自 ?options(向下滚动很长一段路找到 warn...):

sets the handling of warning messages. If warn is negative all warnings are ignored. If warn is zero (the default) warnings are stored until the top–level function returns. If 10 or fewer warnings were signalled they will be printed otherwise a message saying how many were signalled. An object called last.warning is created and can be printed through the function warnings. If warn is one, warnings are printed as they occur. If warn is two or larger all warnings are turned into errors.

因此,使用 tryCatch,您可以指定一个 warning 处理函数,以在捕获到警告时执行操作:

> tryCatch(expr = {Kmeans((time.series), centers = centers, iter.max = 99)},
warning = function(e) "Caught warning")
[1] "Caught warning"

或者您可以通过以下方式将所有警告升级为错误:

options(warn = 2)

如文档中所述。然后,

> tryCatch(expr = {Kmeans((time.series), centers = centers, iter.max = 99)},
error = function(e) "Caught error")
[1] "Caught error"

虽然很多人似乎更喜欢tryCatch,但我经常喜欢try的明确性,如果我想做一些if,这对我来说感觉更容易...else 运行表达式后 block :

options(warn = 2)
attempt <- try(expr = {Kmeans((time.series), centers = centers, iter.max = 99)},silent = TRUE)
> class(attempt)
[1] "try-error"

那么您可以在 if 语句中检查 class(attempt) (首选方法是检查 inherits(attempt,"try-error") ) 并做相应的事情。

关于r - 如何处理 K-means 函数中的 "empty cluster"警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47685121/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com