Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -36,28 +36,29 @@ class GeneticAlgorithm:
|
|
| 36 |
def selection(self):
|
| 37 |
X_train, X_test, y_train, y_test = generate_dataset(self.task_id)
|
| 38 |
fitness = []
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
| 46 |
def crossover(self):
|
| 47 |
offspring = []
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
|
| 62 |
def mutation(self):
|
| 63 |
for net in self.population:
|
|
@@ -65,7 +66,6 @@ class GeneticAlgorithm:
|
|
| 65 |
weights = net.get_weights()
|
| 66 |
new_weights = [np.array(w) + np.random.randn(*w.shape) * 0.1 for w in weights]
|
| 67 |
net.set_weights(new_weights)
|
| 68 |
-
|
| 69 |
# Streamlit app
|
| 70 |
st.title("Evolution of Sub-Models")
|
| 71 |
|
|
|
|
| 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)[-self.population_size//2:]]
|
| 46 |
+
|
| 47 |
def crossover(self):
|
| 48 |
offspring = []
|
| 49 |
+
for _ in range(self.population_size//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 |
+
# Average the weights of the two parents
|
| 58 |
+
child_weights = [(np.array(w1) + np.array(w2)) / 2 for w1, w2 in zip(parent1_weights, parent2_weights)]
|
| 59 |
+
child.set_weights(child_weights)
|
| 60 |
+
offspring.append(child)
|
| 61 |
+
self.population += offspring
|
| 62 |
|
| 63 |
def mutation(self):
|
| 64 |
for net in self.population:
|
|
|
|
| 66 |
weights = net.get_weights()
|
| 67 |
new_weights = [np.array(w) + np.random.randn(*w.shape) * 0.1 for w in weights]
|
| 68 |
net.set_weights(new_weights)
|
|
|
|
| 69 |
# Streamlit app
|
| 70 |
st.title("Evolution of Sub-Models")
|
| 71 |
|