80

特定の比率で乱数のゼロと1を生成する効率的な(おそらくMatlabの用語でベクトル化された)方法は何ですか? 特に Numpy では?

私の場合は特別なので1/3、私のコードは次のとおりです。

import numpy as np 
a=np.mod(np.multiply(np.random.randomintegers(0,2,size)),3)

しかし、少なくともK/NK と N が自然数である状況で、これをより効率的に処理できる組み込み関数はありますか?

4

6 に答える 6

18

使用できますnumpy.random.binomial。たとえばfrac、1 の割合を次のように仮定します。

In [50]: frac = 0.15

In [51]: sample = np.random.binomial(1, frac, size=10000)

In [52]: sample.sum()
Out[52]: 1567
于 2013-10-25T19:07:30.127 に答える
1

1 と 0 の正確な数を取得する別の方法は、 を使用して置換せずにインデックスをサンプリングすることnp.random.choiceです。

arr_len = 30
num_ones = 8

arr = np.zeros(arr_len, dtype=int)
idx = np.random.choice(range(arr_len), num_ones, replace=False)
arr[idx] = 1

外:

arr

array([0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1,
       0, 0, 0, 0, 0, 1, 0, 0])
于 2019-03-27T16:14:02.287 に答える