How to optimize a nested for loop in Python

前端 未结 3 817
轻奢々
轻奢々 2021-02-08 10:34

So I am trying to write a python function to return a metric called the Mielke-Berry R value. The metric is calculated like so:

The current code I have written works, b

3条回答
  •  佛祖请我去吃肉
    2021-02-08 10:58

    Here's one vectorized way to leverage broadcasting to get total -

    np.abs(forecasted_array[:,None] - observed_array).sum()
    

    To accept both lists and arrays alike, we can use NumPy builtin for the outer subtraction, like so -

    np.abs(np.subtract.outer(forecasted_array, observed_array)).sum()
    

    We can also make use of numexpr module for faster absolute computations and perform summation-reductions in one single numexpr evaluate call and as such would be much more memory efficient, like so -

    import numexpr as ne
    
    forecasted_array2D = forecasted_array[:,None]
    total = ne.evaluate('sum(abs(forecasted_array2D - observed_array))')
    

提交回复
热议问题