0

I am doing something similar to Weighted choice short and simple however, i am additionally in need of adjusting weights depending on scenarios.

I tried doing some simple arithmetics, i.e weight *= 2 but the cumulative sum has to equal 1 (obviously) and i don't see how I can adjust one weight, and have the other weights adjust too.. There must be some simplistic solution that i am overseeing.

Scenario

mylist = ['a', 'b', 'c', 'd']
myweights = [0.25, 0.25, 0.25, 0.25]

After selecting an item from mylist and running it through a function, i would like to adjust the weight associated with that item, either up or down, before selecting another item based on adjusted weights and so on.

  • Yeah, I guess it does qualify as a duplicate. I just wanna note that I probably had never found that question since I was trying the keywords "update weighting" and "weight distribution" etc, rather than "normalize". – Tobias Jørgensen Mar 21 '18 at 14:20

2 Answers2

0

how about adding this after the weights update:

s = sum(myweights)
myweights = [w/s for w in myweights]
shakedzy
  • 2,853
  • 5
  • 32
  • 62
  • I appreciate the answer, and will try to implement this and see what happens. – Tobias Jørgensen Mar 21 '18 at 13:54
  • But surely this will change the updated weight too? E.g. if you change 'c' to 0.5, this will be weighted down as well.. – jpp Mar 21 '18 at 13:55
  • I have implemented this, and will most likely be using this solution unless a better alternative comes up. The point @jpp brings up is valid, however in my use case it is fine. – Tobias Jørgensen Mar 21 '18 at 13:59
0

This is one way using numpy, assuming you want to fix your update and linearly distribute the difference to ensure sum(weights) equals 1.

import numpy as np

def weight_updater(lst, oldweights, item, new):
    newweights = oldweights.copy()
    idx = lst.index(item)
    newweights += (oldweights[idx] - new)/(len(newweights)-1)
    newweights[idx] = new
    return newweights

mylist = ['a', 'b', 'c', 'd']
myweights = np.array([0.25, 0.25, 0.25, 0.25])

res = weight_updater(mylist, myweights, 'c', 0.5)

# array([ 0.16666667,  0.16666667,  0.5       ,  0.16666667])
jpp
  • 159,742
  • 34
  • 281
  • 339