r - 从 paramHankel.scaled() 函数(mixComp 包)中检索 values

paramHankel.scaled() 是 mixComp 包中的一个函数,用于确定有限混合模型的分量。例如,下面的一段代码显示了如何使用该函数:

library("mixComp")

set.seed(0)

# construct a Mix object:
    normLocMix <- Mix("norm", discrete = FALSE, w = c(0.3, 0.4, 0.3), mean = c(10, 13, 17), sd = 
    c(1, 1, 1))

# generate random samples:
    normLocRMix <- rMix(1000, obj = normLocMix)
# plot the histograms of the random samples:
    plot(normLocRMix, main = "Three component normal mixture", cex.main = 0.9)

# define the function for computing the moments:
    mom.std.norm <- function(j){
       ifelse(j %% 2 == 0, prod(seq(1, j - 1, by = 2)), 0)
    }

    MLE.norm.mean <- function(dat) mean(dat)
    MLE.norm.sd <- function(dat){
       sqrt((length(dat) - 1) / length(dat)) * sd(dat)
    } 
    MLE.norm.list <- list("MLE.norm.mean" = MLE.norm.mean, "MLE.norm.sd" = MLE.norm.sd)

# define the range for parameter values:
    norm.bound.list <- list("mean" = c(-Inf, Inf), "sd" = c(0, Inf))

# create datMix objects:
    normLoc.dM <- RtoDat(normLocRMix, theta.bound.list = norm.bound.list,
                     MLE.function = MLE.norm.list, Hankel.method = "translation",
                     Hankel.function = mom.std.norm)

# define the penalty function:
    pen <- function(j, n){
       j * log(n)
    }

# apply papamHankel.scaled to datMix objects:
    norm_sca_pen <- paramHankel.scaled(normLoc.dM)

# plot the results for both mixtures:
    par(mar=c(5, 5, 1, 1))
    plot(norm_sca_pen)

在我们使用的最后几行中

norm_sca_pen <- paramHankel.scaled(normLoc.dM)

2个组分的混合模型的参数是:

Parameter estimation for a 2 component 'norm' mixture model:
Function value: 2392.6800

                    w     mean     sd
Component 1:  0.74923 11.88077 2.0151
Component 2:  0.25077 17.14082 0.9251
Converged in 3 iterations.

如何从 norm_sca_pen 检索 2 个组件模型的权重 (w)、均值和 sd 的 values?

回答1

您可以使用变通方法来获取这些 values。这将创建一个包含三个组件中的每一个以及 wmeansd 的数据框。

您需要添加 tidyverse。 (这使用 dplyrpurrr,但 tidyverse 会同时调用两者。)

如果超过三个,这仍然有效。

# apply papamHankel.scaled to datMix objects:
norm_sca_pen <- paramHankel.scaled(normLoc.dM)
op <- capture.output(.Last.value)
df1 <- data.frame(Components = as.character(), w = as.numeric(), 
                  mean = as.numeric(), sd = as.numeric())
map(2:length(op),
        function(k) {
          x = strsplit(op[k], ": ")
          y = gsub("  ", " ", x[[1]][2])
          z = strsplit(y, " ")
          df1[nrow(df1) + 1, ] <<- c(x[[1]][1], z[[1]][2], z[[1]][3], z[[1]][4])
        }
)

相似文章

随机推荐

最新文章