I have a pre specified mean [0.5, 0.5, 0]
. This is a probability array which sum up to 1.
I want to generate several, say 10 random probability arrays (each sums up to 1) whose mean is [0.5, 0.5, 0]
, for example
out = [[1.41439945e-01 8.58560055e-01 0.00000000e+00]
[9.99967956e-01 3.20439716e-05 0.00000000e+00]
[9.42136832e-01 5.78631675e-02 0.00000000e+00]
[4.40349524e-01 5.59650476e-01 0.00000000e+00]
[7.44887609e-01 2.55112391e-01 0.00000000e+00]
[2.02038298e-01 7.97961702e-01 0.00000000e+00]
[2.87313048e-02 9.71268695e-01 0.00000000e+00]
[4.49155118e-01 5.50844882e-01 0.00000000e+00]
[9.99805466e-01 1.94534222e-04 0.00000000e+00]
[5.14967660e-02 9.48503234e-01 0.00000000e+00]]
np.mean(out, axis=0) # [0.5, 0.5, 0]
I first generate arrays using arrays = np.random.dirichlet((0.3,0.3,0.3), size=10)
, such that each row has a sum of 1, but how can I match with the mean?
Your example shows the third column as being all zeros, so I assume that is desired. This leaves each row with two nonzero elements that must sum to 1.0
. Consequently, only one element of each row is independent. So we generate a random column 0
, shift elements such that its mean equals 0.5
, and set the elements of column 1
to ensure that the row sums to 1.0
. If any of the elements are outside the unit interval, repeat.
import numpy as np
out = np.zeros((10, 3))
rng = np.random.default_rng()
col0 = rng.random(size=10)
col0 += 0.5 - np.mean(col0)
out[:, 0] = col0
out[:, 1] = 1 - col0
assert np.all(out <= 1) # if this fails, repeat
print(np.mean(out, axis=0)) # [0.5 0.5 0. ]
print(np.sum(out, axis=1)) # [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
print(out)
# [[0.72632279 0.27367721 0. ]
# [0.27206719 0.72793281 0. ]
# [0.45643418 0.54356582 0. ]
# [0.22431209 0.77568791 0. ]
# [0.43686874 0.56313126 0. ]
# [0.59509627 0.40490373 0. ]
# [0.75482776 0.24517224 0. ]
# [0.34134661 0.65865339 0. ]
# [0.31351313 0.68648687 0. ]
# [0.87921125 0.12078875 0. ]]
This answers your question as stated. If there are other constraints, please state them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With