最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Sampling from joint probability mass function in python - Stack Overflow

matteradmin5PV0评论

I have a non-negative normalized vector p. I would like to sample an index from the index set of the vector. The probability getting sample k is p[k]. Using np.random.choice function, I can write the following code.

p = [0.2, 0.3, 0.1, 0.3, 0.1]
indices = np.arange(len(p))
k = np.random.choice(indices, p=p)

My question is, how can I generalize this code for multi-dimensional arrays? For example, given three dimensional non-negative normalized IxJxK tensor p = np.random.rand(I,J,K) how can I sample the index (i,j,k) with the probability p[i,j,k]?

I have a non-negative normalized vector p. I would like to sample an index from the index set of the vector. The probability getting sample k is p[k]. Using np.random.choice function, I can write the following code.

p = [0.2, 0.3, 0.1, 0.3, 0.1]
indices = np.arange(len(p))
k = np.random.choice(indices, p=p)

My question is, how can I generalize this code for multi-dimensional arrays? For example, given three dimensional non-negative normalized IxJxK tensor p = np.random.rand(I,J,K) how can I sample the index (i,j,k) with the probability p[i,j,k]?

Share Improve this question edited Nov 17, 2024 at 6:19 Robert Dodier 17.6k2 gold badges34 silver badges54 bronze badges asked Nov 16, 2024 at 2:52 Sakurai.JJSakurai.JJ 6944 silver badges13 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

Suppose that x is a probability matrix:

x = np.random.random((3, 4, 5))
x /= np.sum(x)

You can use flatten(x) and np.random.choice() to get values in the range 0..3x4x5 with the associated probabilities:

flat = x.flatten()
temp = np.random.choice(np.arange(len(flat)), 10, p=flat)
print(temp)

You can now convert the indices in temp into indices in the original array:

np.unravel_index(temp, x.shape))

Note that this will return a tuple of three numpy arrays, with the first array being the first index, the second element being the second index, and so on.

Post a comment

comment list (0)

  1. No comments so far