0

I have an array: [1,1.2,1.4,1.5.....] with 1000 elements. I would like to randomly pick a value from these choices using a weighted gaussian probability with a given mean. For example, I have set mean value of 25. So the weight of choices is a gaussian function which has mean around 25, i.e the most of the numbers picked are around 25.

Duplicate of this question but using python instead of javascript. Probability curve is something like this: Probability Curve

Background Info I am trying to fit a curve on some data which has asymmetric error bars and I cannot find any python module to do such fitting. So I am doing a Monte-Carlo simulation where I randomly pick x and y data points from the error range with data values as mean and repeat it some (let's say) 1000 times and optimize the mean square error.

This is how my data looks like:

data

Aryan Bansal
  • 79
  • 2
  • 9

3 Answers3

0

Couldn't you use take advantage of the numpy random sample method?

numpy.random.sample(array, probabilities)

Where your probabilities might be defined:

probabilities = [scipy.stats.norm(your_mean, your_stdev).pdf(i) for i in array]

Obviously not a ground up solution, but takes advantage of a few convenient libraries.

  • Thanks! Ya, maybe this could also work, but I ended up using np.random.triangular which although doesn't give gaussian PD, still works for me here. – Aryan Bansal Jun 04 '21 at 21:47
0

Just build a weight array that stores the weight for each number, then pass it to random.choices.

import random

def weight_func(x):
  # Calculate the weight for x here.
  pass

# List of choices
choices=[1,2,3,4,5,6]
# List of weights.  Note that the weights need not sum to 1.
weights=[weight_func(x) for x in choices]
# Do a weighted sample (the 1000 here is the sample size and is arbitrary)
print(random.choices(choices, k=1000, weights=weights))
Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • This can work only if k=1000, all had same weight_func. But in my case, to fit the data, all the values in '[choices]' are keeps changing for each k iteration. Moreover, the most probable value is different in each of the 1000 k's. Still, thanks a lot. Also, np.random.triangular worked for me. – Aryan Bansal Jun 04 '21 at 21:45
  • The 1000 here is arbitrary; you can use any other sample size. – Peter O. Jun 04 '21 at 21:50
  • No, i meant that weight function is changing for each data sample. So I need to set multiple (49 in my case) different weight functions. This case would be only valid for one set of choices and weight function. – Aryan Bansal Jun 05 '21 at 15:41
  • You didn't state that detail clearly enough in your question. – Peter O. Jun 06 '21 at 21:24
0

numpy's random.triangular module worked for me:

np.random.triangular(left, mode, right, size=None)

left = lowest value

right = highest value

mode = value with highest probability

size = size of samples to be picked

Aryan Bansal
  • 79
  • 2
  • 9