I have a numpy array P
with size (N,M)
, where each row is a discrete probability distribution over 0, ..., M -1
(i.e. each row sums to one and all elements are non-negative). I also have an array x
with length K
containing elements in 0, ..., N-1
. For each x[k]
, my goal is to generate one sample according to distribution P[x[k], :]
and store them in array y
with length K
.
I have written a code for this task with a loop
y = np.zeros(K)
for i, k in enumerate(K):
y[i] = np.random.choice(np.arange(M), p = P[x[k],:])
Is it possible to compute y
without using a loop?
question from:
https://stackoverflow.com/questions/65909780/sampling-from-a-matrix-of-discrete-probability-distributions-in-python-without-a 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…