I am running the following code where the function weighted_values
returns a sequence of random values with probabilities as specified. I am using this function from this answer Generating discrete random variables with weights
The following is my code:
def weighted_values(values, probabilities, size):
bins = np.add.accumulate(probabilities)
return np.array(values[np.digitize(random_sample(size), bins)])
def weak_softmax(a):
b=np.exp(a)
return b/(1+sum(b))
elements=np.array([1,2,3])
prob=np.array([0.2,0.5,0.3])
system_index=0;
T=10;M=2;
for t in np.arange(T):
prob=weak_softmax(np.random.uniform(0,1,M+1));
system_index=weighted_values(np.arange(M+1),prob,1)[0]
print(system_index)
However when I run this code, sometimes I get this error that
Traceback (most recent call last):
File "gradient_checking.py", line 75, in <module>
system_index=weighted_values(np.arange(M+1),prob,1)[0]
File "gradient_checking.py", line 57, in weighted_values
return np.array(values[np.digitize(random_sample(size), bins)])
IndexError: index 3 is out of bounds for axis 1 with size 3
Can anyone suggest what I am doing wrong and how to modify it?