-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathk_fold_split.py
172 lines (137 loc) · 4.94 KB
/
k_fold_split.py
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import numpy as np
from numpy.random import default_rng
from numba import njit
from typing import Set, Tuple
def generate_problem(num_groups: int,
num_classes: int,
min_group_size: int,
max_group_size: int,
class_percent: np.array) -> np.ndarray:
problem = np.zeros((num_groups, num_classes), dtype=int)
rng = default_rng()
group_sizes = rng.integers(low=min_group_size,
high=max_group_size,
size=num_groups)
for i in range(num_groups):
# Calculate the
proportions = np.random.normal(class_percent, class_percent / 10)
problem[i, :] = proportions * group_sizes[i]
return problem
@njit
def calculate_cost(problem: np.ndarray,
solution: np.ndarray,
k: int) -> float:
cost = 0.0
total = np.sum(problem)
class_sums = np.sum(problem, axis=0)
num_classes = problem.shape[1]
for i in range(k):
idx = solution == i
fold_sum = np.sum(problem[idx, :])
# Start by calculating the fold imbalance cost
cost += (fold_sum / total - 1.0 / k) ** 2
# Now calculate the cost associated with the class imbalances
for j in range(num_classes):
cost += (np.sum(problem[idx, j]) / fold_sum - class_sums[j] / total) ** 2
return cost
@njit
def generate_search_space(problem: np.ndarray,
solution: np.ndarray,
k: int) -> np.ndarray:
num_groups = problem.shape[0]
space = np.zeros((num_groups, k))
sol = solution.copy()
for i in range(num_groups):
for j in range(k):
if solution[i] == j:
space[i,j] = np.infty
else:
sol[i] = j
space[i, j] = calculate_cost(problem, sol, k)
sol[i] = solution[i]
return space
@njit
def solution_to_str(solution: np.ndarray) -> str:
return "".join([str(n) for n in solution])
def generate_initial_solution(problem: np.ndarray,
k: int,
algo: str="k-bound") -> np.ndarray:
num_groups = problem.shape[0]
if algo == "k-bound":
rng = default_rng()
total = np.sum(problem)
indices = rng.permutation(problem.shape[0])
solution = np.zeros(num_groups, dtype=int)
c = 0
fold_total = 0
for i in indices:
group = np.sum(problem[i, :])
if fold_total + group < total / k:
fold_total += group
else:
c = (c + 1) % k
fold_total = group
solution[i] = c
elif algo == "random":
rng = default_rng()
solution = rng.integers(low=0, high=k, size=num_groups)
elif algo == "zeros":
solution = np.zeros(num_groups, dtype=int)
else:
raise Exception("Invalid algorithm name")
return solution
def solve(problem: np.ndarray,
k=5,
min_cost=1e-5,
max_retry=100,
verbose=False) -> np.ndarray:
hist = set()
retry = 0
solution = generate_initial_solution(problem, k)
incumbent = solution.copy()
low_cost = calculate_cost(problem, solution, k)
cost = 1.0
while retry < max_retry and cost > min_cost:
decision = generate_search_space(problem, solution, k=5)
grp, cls = select_move(decision, solution, hist)
if grp != -1:
solution[grp] = cls
cost = calculate_cost(problem, solution, k=5)
if cost < low_cost:
low_cost = cost
incumbent = solution.copy()
retry = 0
if verbose:
print(cost)
else:
retry += 1
hist.add(solution_to_str(solution))
return incumbent
def select_move(decision: np.ndarray,
solution: np.ndarray,
history: Set) -> Tuple:
candidates = np.argsort(decision, axis=None)
for c in candidates:
p = np.unravel_index(c, decision.shape)
s = solution.copy()
s[p[0]] = p[1]
sol_str = solution_to_str(s)
if sol_str not in history:
return p
return -1, -1 # No move found!
def main():
problem = generate_problem(num_groups=500,
num_classes=4,
min_group_size=400,
max_group_size=2000,
class_percent=np.array([0.4, 0.3, 0.2, 0.1]))
solution = solve(problem, k=5, verbose=True)
print(np.sum(problem, axis=0) / np.sum(problem))
print()
folds = [problem[solution == i] for i in range(5)]
fold_percents = np.array([np.sum(folds[i], axis=0) / np.sum(folds[i]) for i in range(5)])
print(fold_percents)
print()
print([np.sum(folds[i]) / np.sum(problem) for i in range(5)])
if __name__ == "__main__":
main()