gpt4 book ai didi

r - 加快 R 中的概率加权采样

转载 作者:行者123 更新时间:2023-12-02 08:36:04 29 4
gpt4 key购买 nike

<分区>

如何在 R 中加快概率加权采样。

# Let's assume we are considering following example:
w <- sample(1:4000,size=2e6, replace=T)

# "w" will be integer, so we are going to convert it to numeric.
w <- as.numeric(w)

# Actually the sampling process have to be repeated many times.
M <- matrix(NA, 10, 2000)
system.time(
for (r in 1:10){
ix <- sample(1:2e6,size=2000,prob=w/sum(w))
M[r,] <- ix
})
# It's worth it to mention that without "prob=w/sum(w)" sampling is considerably faster.
# The main goal is to speed up sampling with probability weights!
system.time(ix <- sample(1:2e6,size=2000,prob=w/sum(w)))

加权采样需要 9.84 秒,正常采样需要 0.01 秒。如果您对如何加快加权采样有任何想法,欢迎回答。

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