gpt4 book ai didi

R : function to generate a mixture distribution

转载 作者:行者123 更新时间:2023-12-01 23:30:58 26 4
gpt4 key购买 nike

我需要从混合分布生成样本

  • 40% 样本来自高斯分布(mean=2,sd=8)

  • 20% 的样本来自 Cauchy(location=25,scale=2)

  • 40% 的样本来自高斯分布(平均值 = 10,sd=6)

为此,我编写了以下函数:

dmix <- function(x){
prob <- (0.4 * dnorm(x,mean=2,sd=8)) + (0.2 * dcauchy(x,location=25,scale=2)) + (0.4 * dnorm(x,mean=10,sd=6))
return (prob)
}

然后测试:

foo = seq(-5,5,by = 0.01)
vector = NULL
for (i in 1:1000){
vector[i] <- dmix(foo[i])
}
hist(vector)

我得到了这样的直方图(我知道这是错误的)- histogram of the supposed distribution

我做错了什么?请问有人可以指点一下吗?

最佳答案

当然还有其他方法可以做到这一点,但是 distr 包使它变得非常简单。 ( See also this answer 是另一个示例以及有关 distr 和 friend 的更多详细信息)。

library(distr)

## Construct the distribution object.
myMix <- UnivarMixingDistribution(Norm(mean=2, sd=8),
Cauchy(location=25, scale=2),
Norm(mean=10, sd=6),
mixCoeff=c(0.4, 0.2, 0.4))
## ... and then a function for sampling random variates from it
rmyMix <- r(myMix)

## Sample a million random variates, and plot (part of) their histogram
x <- rmyMix(1e6)
hist(x[x>-100 & x<100], breaks=100, col="grey", main="")

enter image description here

如果您想直接查看混合分布的 pdf,请执行以下操作:

plot(myMix, to.draw.arg="d") 

enter image description here

关于R : function to generate a mixture distribution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23480529/

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