Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,85 +3,108 @@ import numpy as np
|
|
3 |
import torch
|
4 |
import torch.nn as nn
|
5 |
import random
|
|
|
|
|
|
|
6 |
|
7 |
-
# Define
|
8 |
-
def
|
9 |
-
|
|
|
|
|
10 |
|
11 |
-
# Define
|
12 |
class Net(nn.Module):
|
13 |
def __init__(self):
|
14 |
super(Net, self).__init__()
|
15 |
-
self.fc1 = nn.Linear(
|
16 |
-
self.fc2 = nn.Linear(
|
|
|
17 |
|
18 |
def forward(self, x):
|
19 |
x = torch.relu(self.fc1(x))
|
20 |
-
x = self.fc2(x)
|
|
|
21 |
return x
|
22 |
|
23 |
-
# Define
|
24 |
class GeneticAlgorithm:
|
25 |
def __init__(self, population_size):
|
26 |
self.population_size = population_size
|
27 |
-
self.population = [
|
28 |
|
29 |
-
def selection(self):
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
def crossover(self):
|
33 |
offspring = []
|
34 |
for _ in range(self.population_size//2):
|
35 |
parent1, parent2 = random.sample(self.population, 2)
|
36 |
-
child = (
|
|
|
|
|
|
|
37 |
offspring.append(child)
|
38 |
self.population += offspring
|
39 |
|
40 |
def mutation(self):
|
41 |
-
for
|
42 |
if random.random() < 0.1:
|
43 |
-
|
|
|
|
|
44 |
|
45 |
# Streamlit app
|
46 |
-
st.title("
|
47 |
|
48 |
# Parameters
|
49 |
st.sidebar.header("Parameters")
|
50 |
population_size = st.sidebar.slider("Population size", 10, 100, 50)
|
51 |
-
|
52 |
-
|
53 |
|
54 |
-
# Run the
|
55 |
-
if st.button("Run
|
56 |
-
# Initialize the neural network and genetic algorithm
|
57 |
-
net = Net()
|
58 |
-
criterion = nn.MSELoss()
|
59 |
-
optimizer = torch.optim.Adam(net.parameters(), lr=0.01)
|
60 |
ga = GeneticAlgorithm(population_size)
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
-
#
|
63 |
-
|
64 |
-
for
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
ga.crossover()
|
79 |
-
ga.mutation()
|
80 |
-
ga_values.append(max(map(f, ga.population)))
|
81 |
-
|
82 |
-
# Plot the results
|
83 |
-
st.line_chart({"Neural Network": nn_losses, "Genetic Algorithm": ga_values})
|
84 |
-
|
85 |
-
# Print the final values
|
86 |
-
st.write("Final neural network value:", nn_losses[-1])
|
87 |
-
st.write("Final genetic algorithm value:", ga_values[-1])
|
|
|
3 |
import torch
|
4 |
import torch.nn as nn
|
5 |
import random
|
6 |
+
from sklearn.datasets import make_classification
|
7 |
+
from sklearn.model_selection import train_test_split
|
8 |
+
from sklearn.metrics import accuracy_score
|
9 |
|
10 |
+
# Define a function to generate a dataset
|
11 |
+
def generate_dataset(task_id):
|
12 |
+
X, y = make_classification(n_samples=100, n_features=10, n_informative=5, n_redundant=3, n_repeated=2, random_state=task_id)
|
13 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=task_id)
|
14 |
+
return X_train, X_test, y_train, y_test
|
15 |
|
16 |
+
# Define a neural network class
|
17 |
class Net(nn.Module):
|
18 |
def __init__(self):
|
19 |
super(Net, self).__init__()
|
20 |
+
self.fc1 = nn.Linear(10, 20)
|
21 |
+
self.fc2 = nn.Linear(20, 10)
|
22 |
+
self.fc3 = nn.Linear(10, 2)
|
23 |
|
24 |
def forward(self, x):
|
25 |
x = torch.relu(self.fc1(x))
|
26 |
+
x = torch.relu(self.fc2(x))
|
27 |
+
x = self.fc3(x)
|
28 |
return x
|
29 |
|
30 |
+
# Define a genetic algorithm class
|
31 |
class GeneticAlgorithm:
|
32 |
def __init__(self, population_size):
|
33 |
self.population_size = population_size
|
34 |
+
self.population = [Net() for _ in range(population_size)]
|
35 |
|
36 |
+
def selection(self, task_id):
|
37 |
+
X_train, X_test, y_train, y_test = generate_dataset(task_id)
|
38 |
+
fitness = []
|
39 |
+
for net in self.population:
|
40 |
+
criterion = nn.CrossEntropyLoss()
|
41 |
+
optimizer = torch.optim.Adam(net.parameters(), lr=0.01)
|
42 |
+
for epoch in range(10):
|
43 |
+
optimizer.zero_grad()
|
44 |
+
inputs = torch.tensor(X_train, dtype=torch.float32)
|
45 |
+
labels = torch.tensor(y_train, dtype=torch.long)
|
46 |
+
outputs = net(inputs)
|
47 |
+
loss = criterion(outputs, labels)
|
48 |
+
loss.backward()
|
49 |
+
optimizer.step()
|
50 |
+
inputs = torch.tensor(X_test, dtype=torch.float32)
|
51 |
+
labels = torch.tensor(y_test, dtype=torch.long)
|
52 |
+
outputs = net(inputs)
|
53 |
+
_, predicted = torch.max(outputs, 1)
|
54 |
+
accuracy = accuracy_score(labels, predicted)
|
55 |
+
fitness.append(accuracy)
|
56 |
+
self.population = [self.population[i] for i in np.argsort(fitness)[-self.population_size//2:]]
|
57 |
|
58 |
def crossover(self):
|
59 |
offspring = []
|
60 |
for _ in range(self.population_size//2):
|
61 |
parent1, parent2 = random.sample(self.population, 2)
|
62 |
+
child = Net()
|
63 |
+
child.fc1.weight.data = (parent1.fc1.weight.data + parent2.fc1.weight.data) / 2
|
64 |
+
child.fc2.weight.data = (parent1.fc2.weight.data + parent2.fc2.weight.data) / 2
|
65 |
+
child.fc3.weight.data = (parent1.fc3.weight.data + parent2.fc3.weight.data) / 2
|
66 |
offspring.append(child)
|
67 |
self.population += offspring
|
68 |
|
69 |
def mutation(self):
|
70 |
+
for net in self.population:
|
71 |
if random.random() < 0.1:
|
72 |
+
net.fc1.weight.data += torch.randn_like(net.fc1.weight.data) * 0.1
|
73 |
+
net.fc2.weight.data += torch.randn_like(net.fc2.weight.data) * 0.1
|
74 |
+
net.fc3.weight.data += torch.randn_like(net.fc3.weight.data) * 0.1
|
75 |
|
76 |
# Streamlit app
|
77 |
+
st.title("Evolution of Sub-Models")
|
78 |
|
79 |
# Parameters
|
80 |
st.sidebar.header("Parameters")
|
81 |
population_size = st.sidebar.slider("Population size", 10, 100, 50)
|
82 |
+
num_tasks = st.sidebar.slider("Number of tasks", 1, 10, 5)
|
83 |
+
num_generations = st.sidebar.slider("Number of generations", 1, 100, 10)
|
84 |
|
85 |
+
# Run the evolution
|
86 |
+
if st.button("Run evolution"):
|
|
|
|
|
|
|
|
|
87 |
ga = GeneticAlgorithm(population_size)
|
88 |
+
for generation in range(num_generations):
|
89 |
+
for task_id in range(num_tasks):
|
90 |
+
ga.selection(task_id)
|
91 |
+
ga.crossover()
|
92 |
+
ga.mutation()
|
93 |
+
st.write(f"Generation {generation+1} complete")
|
94 |
|
95 |
+
# Evaluate the final population
|
96 |
+
final_accuracy = []
|
97 |
+
for task_id in range(num_tasks):
|
98 |
+
X_train, X_test, y_train, y_test = generate_dataset(task_id)
|
99 |
+
accuracy = []
|
100 |
+
for net in ga.population:
|
101 |
+
criterion = nn.CrossEntropyLoss()
|
102 |
+
optimizer = torch.optim.Adam(net.parameters(), lr=0.01)
|
103 |
+
for epoch in range(10):
|
104 |
+
optimizer.zero_grad()
|
105 |
+
inputs = torch.tensor(X_train, dtype=torch.float32)
|
106 |
+
labels = torch.tensor(y_train, dtype=torch.long)
|
107 |
+
outputs = net(inputs)
|
108 |
+
loss = criterion(outputs, labels)
|
109 |
+
loss.backward()
|
110 |
+
optimizer.step()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|