More efficient weighted Gini coefficient in Python

Per https://stackoverflow.com/a/2755891/ is a weighted Gini coefficient implementation in Python:

import numpy as np def gini(x, weights=None): if weights is None: weights = np.ones_like(x) # Calculate mean absolute deviation in two steps, for weights. count = np.multiply.outer(weights, weights) mad = np.abs(np.subtract.outer(x, x) * count).sum() / count.sum() rmad = mad / np.average(x, weights=weights) # Gini equals half the relative mean absolute deviation. return 0.5 * rmad 

This is clean and works well for medium arrays, but as said in his original sentence ( https://stackoverflow.com/a/166609/12 ), O (n 2 ). On my computer, this means that it breaks after the lines ~ 20k:

 n = 20000 # Works, 30000 fails. gini(np.random.rand(n), np.random.rand(n)) 

Can I configure it to work with large data sets? The mine is ~ 150 thousand lines.

+7
source share
2 answers

Here is a version that is much faster than the one you provided above, and also uses a simplified formula for the case without weight, to get even faster results in this case.

 def gini(x, w=None): # The rest of the code requires numpy arrays. x = np.asarray(x) if w is not None: w = np.asarray(w) sorted_indices = np.argsort(x) sorted_x = x[sorted_indices] sorted_w = w[sorted_indices] # Force float dtype to avoid overflows cumw = np.cumsum(sorted_w, dtype=float) cumxw = np.cumsum(sorted_x * sorted_w, dtype=float) return (np.sum(cumxw[1:] * cumw[:-1] - cumxw[:-1] * cumw[1:]) / (cumxw[-1] * cumw[-1])) else: sorted_x = np.sort(x) n = len(x) cumx = np.cumsum(sorted_x, dtype=float) # The above formula, with all weights equal to 1 simplifies to: return (n + 1 - 2 * np.sum(cumx) / cumx[-1]) / n 

Here is some test code to verify that we get (basically) the same results:

 >>> x = np.random.rand(1000000) >>> w = np.random.rand(1000000) >>> gini_max_ghenis(x, w) 0.33376310938610521 >>> gini(x, w) 0.33376310938610382 

But the speed is completely different

 %timeit gini(x, w) 203 ms Β± 3.68 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each) %timeit gini_max_ghenis(x, w) 55.6 s Β± 3.35 s per loop (mean Β± std. dev. of 7 runs, 1 loop each) 

If you remove the pandas functions from the function, it is already much faster:

 %timeit gini_max_ghenis_no_pandas_ops(x, w) 1.62 s Β± 75 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each) 

If you want to get the latest performance degradation, you can use numba or cython, but this will only bring a few percent, because most of the time is spent sorting.

 %timeit ind = np.argsort(x); sx = x[ind]; sw = w[ind] 180 ms Β± 4.82 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each) 

edit : gini_max_ghenis - code used in Max Genis answer

+7
source

An adaptation of the StatsGini R function from here :

 import numpy as np import pandas as pd def gini(x, w=None): # Array indexing requires reset indexes. x = pd.Series(x).reset_index(drop=True) if w is None: w = np.ones_like(x) w = pd.Series(w).reset_index(drop=True) n = x.size wxsum = sum(w * x) wsum = sum(w) sxw = np.argsort(x) sx = x[sxw] * w[sxw] sw = w[sxw] pxi = np.cumsum(sx) / wxsum pci = np.cumsum(sw) / wsum g = 0.0 for i in np.arange(1, n): g = g + pxi.iloc[i] * pci.iloc[i - 1] - pci.iloc[i] * pxi.iloc[i - 1] return g 

This works for large vectors, at least up to 10M lines:

 n = 1e7 gini(np.random.rand(n), np.random.rand(n)) # Takes ~15s. 

It also gives the same result as the function asked in the question, for example, giving 0.2553 for this example:

 gini(np.array([3, 1, 6, 2, 1]), np.array([4, 2, 2, 10, 1])) 
+2
source

Source: https://habr.com/ru/post/1275588/


All Articles