samedi 12 janvier 2019

Selecting two numbers from a list in python with a probability that decays as the relative distance between them

I am trying to take a list, and from it choose randomly an a number i randomly. Following which I want to select a second element j, however the probability of choosing a j decays as 1/|i-j. For example, the relative probability of it choosing a j four steps away from my initial i is 1/4, the probability of selecting a j immediately next to my i.

So far what I have been trying to do is populate my list, choose my i, first then calculate weights using |i-j| for all the other elements in the list.

import numpy as np
import random as random
list = [1,2,3,4,5,6,7,8,9,10]
a = 1
n1 = random.choice(range(len(list)))
n1_coord = (n1, list[n1])
print(n1_coord)
prob_weights = []
for i in range(0, n1):
    wt = 1/((np.absolute(n1-i)))
    #print(wt)
    prob_weights.append(wt)
for i in range(n1+1,len(list)):
    wt = 1/((np.absolute(n1-i)))
    prob_weights.append(wt)

Is there a function built in python that I can feed these weights into which will choose a j with this probability distribution. Can I feed my array of weights in to:

numpy.random.choice(a, size=None, replace=True, p=None)

I suppose I will let p=prob_weights in my code?

 import numpy as np
    import random as random
    list = [1,2,3,4,5,6,7,8,9,10]
    a = 1
    n1 = random.choice(range(len(list)))
    n1_coord = (n1, list[n1])
    print(n1_coord)
    prob_weights = []
    for i in range(0, n1):
        wt = 1/((np.absolute(n1-i)))
        #print(wt)
        prob_weights.append(wt)
    for i in range(n1+1,len(list)):
        wt = 1/((np.absolute(n1-i)))
        prob_weights.append(wt)
    n2 = np.random.choice(list, p=prob_weights)
    n2_coord = (n2, list[n2])

Running this above with np.random.choice gives me an error. I am not even sure if this is doing what I want it do in the first place. Is there an alternate way to do this?




Aucun commentaire:

Enregistrer un commentaire