Home > database >  How to transform a list of weights, given that they must sum to 1 and obey bounds?
How to transform a list of weights, given that they must sum to 1 and obey bounds?

Time:08-01

Suppose I have some weights [w_1,w_2,...,w_n] and I have the following conditions:

  1. a < w_i < b for each i
  2. w_1 w_2 ... w_n = 1

Is there a way to transform (squeeze) my original weights to obey these rules?

Any help would be hugely appreciated!

CodePudding user response:

Try this:

def transform_weights(weights):
    if not weights:
        return []
    weights_sum = sum(weights)
    return [x/weights_sum for x in weights]

weights = [2, 4, 1, 3, 10]

print(transform_weights(weights))

Output:

[0.1, 0.2, 0.05, 0.15, 0.5]

CodePudding user response:

The conditions may fail to be compatible, and there can be different ways to cope:

  • declare "no solution",

  • relax type 1 or type 2 constraint,

  • compute a "best fit" by assigning a penalty to a constraint that is not fulfilled.

Divide every w by the sum of all w to achieve the condition 2. Then if you are lucky, the conditions 1 may hold by chance.

  • Related