forked from EC-KitY/EC-KitY
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cos_sim_switch_cond.py
39 lines (28 loc) · 1.17 KB
/
cos_sim_switch_cond.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
from approx_ml_pop_eval import ApproxMLPopulationEvaluator
import numpy as np
import utils
class CosSimSwitchCondition:
def __init__(self, threshold=0.5, switch_once=False):
super().__init__()
self.threshold = threshold
self.switch_once = switch_once
if switch_once:
self.switched = False
def should_approximate(self, evaluator: ApproxMLPopulationEvaluator):
# If switch_once is enabled and the switch already occured,
# always approximate
if self.switch_once and self.switched:
return True
individuals = evaluator.gen_population.sub_populations[0].individuals
# Get the evaluator dataset with all the gens except the current one
df = evaluator.df[evaluator.df['gen'] < evaluator.gen]
genotypes = df.iloc[:, :-2]
scores = [
genotypes.apply(lambda row: utils.cosine_similarity(ind.vector, row), axis=1, raw=True).max()
for ind in individuals
]
avg_score = np.mean(scores)
result = avg_score >= self.threshold
if self.switch_once:
self.switched = result
return result