-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathks.py
64 lines (50 loc) · 1.52 KB
/
ks.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
from charles.charles import Population, Individual
from charles.search import hill_climb, sim_annealing
from copy import deepcopy
from data.ks_data import weights, values, capacity
from charles.selection import fps, tournament
from charles.mutation import binary_mutation
from charles.crossover import single_point_co
from random import random, choice
from operator import attrgetter
def evaluate(self):
fitness = 0
weight = 0
for bit in range(len(self.representation)):
if self.representation[bit] == 1:
fitness += values[bit]
weight += weights[bit]
if weight > capacity:
fitness = capacity-weight
return fitness
def get_neighbours(self):
n = [deepcopy(self.representation) for i in range(len(self.representation))]
for count, i in enumerate(n):
if i[count] == 1:
i[count] = 0
elif i[count] == 0:
i[count] = 1
n = [Individual(i) for i in n]
return n
# Monkey Patching
Individual.evaluate = evaluate
Individual.get_neighbours = get_neighbours
def create_representation(self):
sol_size = len(values)
valid_set = [0, 1]
return [choice(valid_set) for i in range(sol_size)]
Individual.create_representation = create_representation
if __name__ == '__main__':
pop = Population(
size=100, optim="max"
)
pop.evolve(
gens=100,
select= fps,
crossover= single_point_co,
mutate=binary_mutation,
co_p=0.7,
mu_p=0.2,
elitism=False
)
print('ok')