Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
85 lines (68 loc) · 2.52 KB
/
Copy pathutils.py
File metadata and controls
85 lines (68 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from collections import defaultdict
import numpy as np
class SizeFormatError(Exception):
pass
class EmptyListError(Exception):
pass
class SampleError(Exception):
pass
class SampleError(Exception):
pass
accepted_types = ["xgb"]
def mean_array(l, ref=0):
"""
Compute the element-wise mean across a list of arrays or dicts.
- For dict inputs, missing keys in a given dict are ignored (treated as 0) rather than raising an error.
- All values are assumed to be numeric.
Parameters
----------
l : list of list, list of np.ndarray, or list of dict
Input collection to average. All elements must share the same type.
- If lists/arrays: must all be the same length and contain numeric values.
- If dicts: keys are unioned across all dicts; missing keys are treated as 0.
ref : int, optional
Index of the reference element used to determine the expected size (default 0).
Returns
-------
np.ndarray or collections.defaultdict
- If input is lists/arrays: 1D array of length N with element-wise means.
- If input is dicts: defaultdict with the mean value per key.
Raises
------
EmptyListError
If l is empty.
SizeFormatError
If any list/array has a different length than the reference element.
TypeError
If the element type is not list, np.ndarray, or dict.
"""
if l == []:
raise EmptyListError("There are no lists to apply the operations on.")
n = len(l)
N = len(l[ref])
if isinstance(l[0], list) or isinstance(l[0], np.ndarray):
for i in range(n):
if (len(l[i]) != N) :
raise SizeFormatError("One of your lists (Index: {}) appears to have a different size. (Reference: {})".format(i, ref))
res = np.zeros(N)
for i in range(N):
for j in range(n):
res[i] += l[j][i]
res[i] /= n
elif isinstance(l[0], dict):
res = defaultdict(float)
list_keys = list(map(lambda x : x.keys(), l))
sets = list(map(lambda x : set(x), list_keys))
variables = sets[0]
for ens in sets[1:]:
variables = variables.union(ens)
for key in list(variables):
for i in range(n):
try:
res[key] += l[i][key]
except KeyError:
pass
res[key] = res[key]/n
else:
raise TypeError("Unsupported type for this function.")
return res