Python中随机向量的再生

2024-09-29 21:30:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试生成并重新生成随机法线的向量

我希望能够通过生成大小为100x3的随机法线矩阵和平均值为0和sd 1的随机法线来实现以下目标:

seed1 = '123'
seed2 = 'asd'
randMatrixrows = 100
randMatrixcols = 3
mu = 0
sd = 1

normRand1 = rekina_normRandomGenerator( seed1, randMatrixrows, randMatrixcols, mu, sd ) #normRand1 is of size 100x3
normRand2 = rekina_normRandomGenerator( seed2, randMatrixrows, randMatrixcols, mu, sd )
normRand3 = rekina_normRandomGenerator( seed1, randMatrixrows, randMatrixcols, mu, sd )
normRand4 = rekina_normRandomGenerator( seed2, randMatrixrows, randMatrixcols, mu, sd )

err1 = normRand1 - normRand3
err2 = normRand2 - normRand4

err1和err2的每个元素都应为0

我也尝试过阅读,但是作为Python的新手,我对实现完全失去了兴趣。我希望有一个简单的实现来展示如何使用CBRNG。在


Tags: sdmu法线err1err2randmatrixrowsnormrand1rekina
1条回答
网友
1楼 · 发布于 2024-09-29 21:30:14

您最初假设必须使用^{}是正确的。它似乎提供了大量的sources of pseudo randomness(基于基于计数器的rng)和distributions,这可能会令人困惑。它还提供shortcuts来创建具有给定分布的随机数生成器。在

from reikna.core import Type
from reikna.cbrng import CBRNG
from reikna.cluda import any_api
import numpy as np

# Get any supported API for this system, or an exception    
_api = any_api()
# The global CLUDA Thread, wrapping context, shared by all
# reikna_norm_rng's
_thr = _api.Thread.create()


def reikna_norm_rng(seed, rows, cols, mean, std,
                    dtype=np.float32,
                    generators_dim=1):
    """
    A do-all generator function for creating a new Computation
    returning a stream of pseudorandom number arrays.
    """
    # The Type of the output array
    randoms_arr = Type(dtype, (rows, cols))
    # Shortcut for creating a Sampler for normally distributed
    # random numbers
    rng = CBRNG.normal_bm(randoms_arr=randoms_arr,
                          generators_dim=generators_dim,
                          sampler_kwds=dict(mean=mean, std=std),
                          # Reikna expects a positive integer. This is a 
                          # quick and *dirty* solution.
                          seed=abs(hash(seed)))
    compiled_comp = rng.compile(_thr)
    # RNG "state"
    counters = _thr.to_device(rng.create_counters())
    # Output array
    randoms = _thr.empty_like(compiled_comp.parameter.randoms)

    while True:
        compiled_comp(counters, randoms)
        yield randoms.get()

要想看到它的实际效果,请添加:

^{pr2}$

I also want to make sure that randoms generated using the two different seeds have no correlation.

这取决于执行的质量。下面是两组带有种子01的数字的绘制方法:

rng1 = reikna_norm_rng(0, 100, 10000, 0, 1)
rng2 = reikna_norm_rng(1, 100, 10000, 0, 1)
A = next(rng1)
B = next(rng2)
A_r = A.ravel()
B_r = B.ravel()
for i in range(0, A_r.size, 1000):
    plot(A_r[i:i+1000], B_r[i:i+1000], 'b.')

plot(A, B)

免责声明

这是我第一次和雷克纳见面。上述代码可能无法及时释放资源和/或像筛子一样泄漏。它使用全局^{},这可能不是您在更大的应用程序中想要的。在

PS

np.random.seed(seed)
np.random.normal(0, 1, (100, 3))

也生成形状为(100,3)的正态分布随机数数组,尽管它不使用GPU。在

相关问题 更多 >

    热门问题