Coverage for src/ensae_teaching_cs/ml/gini.py: 100%

18 statements  

« prev     ^ index     » next       coverage.py v7.1.0, created at 2023-01-27 05:44 +0100

1""" 

2@file 

3@brief Functions about the `Gini coefficient <https://en.wikipedia.org/wiki/Gini_coefficient>`_. 

4""" 

5import numpy 

6 

7 

8def gini(Y, X=None): 

9 """ 

10 Computes the 

11 `Gini coefficients <https://en.wikipedia.org/wiki/Gini_coefficient>`_. 

12 

13 @param Y Y values (or revenues) 

14 @param X None for a uniform population or not None for already order value. 

15 @return a curve ``(x, Gini(x))`` 

16 """ 

17 n = len(Y) 

18 couples = numpy.empty((n, 2)) 

19 if X is None: 

20 couples[:, 0] = 1 

21 else: 

22 couples[:, 0] = X 

23 couples[:, 1] = Y 

24 couples = numpy.cumsum(couples, axis=0) 

25 couples[:, 0] /= max(couples[n - 1, 0], 1e-7) 

26 couples[:, 1] /= max(couples[n - 1, 1], 1e-7) 

27 

28 g = 0. 

29 n = couples.shape[0] 

30 

31 for i in range(0, n): 

32 dx = couples[i, 0] - couples[i - 1, 0] 

33 y = couples[i - 1, 1] + couples[i, 1] 

34 g += dx * y 

35 

36 return (1. - g) / 2