Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -35,45 +35,36 @@ class GeneticAlgorithm:
|
|
35 |
|
36 |
def selection(self):
|
37 |
X_train, X_test, y_train, y_test = generate_dataset(self.task_id)
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
|
47 |
def crossover(self):
|
48 |
offspring = []
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
# Get the weights of the parent networks
|
70 |
-
parent1_weights = parent1.get_weights()
|
71 |
-
parent2_weights = parent2.get_weights()
|
72 |
-
# Average the weights of the two parents
|
73 |
-
child_weights = [(np.array(w1) + np.array(w2)) / 2 for w1, w2 in zip(parent1_weights, parent2_weights)]
|
74 |
-
child.set_weights(child_weights)
|
75 |
-
offspring.append(child)
|
76 |
-
self.population += offspring
|
77 |
|
78 |
def mutation(self):
|
79 |
for net in self.population:
|
|
|
35 |
|
36 |
def selection(self):
|
37 |
X_train, X_test, y_train, y_test = generate_dataset(self.task_id)
|
38 |
+
fitness = []
|
39 |
+
for i, net in enumerate(self.population):
|
40 |
+
net.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
|
41 |
+
net.fit(X_train, y_train, epochs=10, verbose=0)
|
42 |
+
loss, accuracy = net.evaluate(X_test, y_test, verbose=0)
|
43 |
+
fitness.append(accuracy)
|
44 |
+
if len(fitness) > 0:
|
45 |
+
self.population = [self.population[i] for i in np.argsort(fitness)[-len(self.population)//2:]]
|
46 |
|
47 |
def crossover(self):
|
48 |
offspring = []
|
49 |
+
for _ in range(len(self.population)//2):
|
50 |
+
parent1, parent2 = random.sample(self.population, 2)
|
51 |
+
child = Net()
|
52 |
+
child.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
|
53 |
+
|
54 |
+
# Get the weights of the parent networks
|
55 |
+
parent1_weights = parent1.get_weights()
|
56 |
+
parent2_weights = parent2.get_weights()
|
57 |
+
|
58 |
+
# Average the weights of the two parents
|
59 |
+
child_weights = []
|
60 |
+
for w1, w2 in zip(parent1_weights, parent2_weights):
|
61 |
+
child_weights.append((w1 + w2) / 2)
|
62 |
+
|
63 |
+
# Set the weights of the child network
|
64 |
+
child.set_weights(child_weights)
|
65 |
+
|
66 |
+
offspring.append(child)
|
67 |
+
self.population += offspring
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
def mutation(self):
|
70 |
for net in self.population:
|