Broadcasting with multiple parameters in grid search

Viewed 26

I have a list of arrays that looks something like this:

list_of_arrays = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]

At the same time I have weights for each int in each array, which I need to calculate the weighted average, e.g:

weights = [1, 20, 100, 10]

Now I wish to compute the weighted average like:

numpy.average(list_of_arrays, weights=weights, axis=1)

The results for this will be:

[2.90839695 3.90839695 4.90839695]

Which is just the weighted average for each array.

However, my issue is that my weights are actually not just a list. In reality it looks something like:

weights_true = [[1, 2, 3, 4], [5, 10, 15, 20], [50, 100, 150, 200], [5, 10, 15, 20]]

So instead of getting just one list of values for one particular set of weights, I need a list of values for each combination of weights that can be created from weights_true.

Can that be achieved in some way ?

1 Answers

You can compute the weighted averages manually using broadcasting:

(list_of_arrays*weights_true[:,None]).sum(2)/weights_true[:,None].sum(2)

with a simpler form using an intermediate reshaped weights array:

W = weights_true[:,None]
(list_of_arrays*W).sum(2)/W.sum(2)

output:

array([[3., 4., 5.],
       [3., 4., 5.],
       [3., 4., 5.],
       [3., 4., 5.]])
Related