Sephfox commited on
Commit
bd712f3
1 Parent(s): 9ee1933

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -0
app.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn as nn
5
+ import random
6
+
7
+ # Define the function to optimize
8
+ def f(x):
9
+ return x**2
10
+
11
+ # Define the neural network
12
+ class Net(nn.Module):
13
+ def __init__(self):
14
+ super(Net, self).__init__()
15
+ self.fc1 = nn.Linear(1, 10)
16
+ self.fc2 = nn.Linear(10, 1)
17
+
18
+ def forward(self, x):
19
+ x = torch.relu(self.fc1(x))
20
+ x = self.fc2(x)
21
+ return x
22
+
23
+ # Define the genetic algorithm
24
+ class GeneticAlgorithm:
25
+ def __init__(self, population_size):
26
+ self.population_size = population_size
27
+ self.population = [random.uniform(-10, 10) for _ in range(population_size)]
28
+
29
+ def selection(self):
30
+ self.population = sorted(self.population, key=lambda x: f(x), reverse=True)[:self.population_size//2]
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 = (parent1 + parent2) / 2
37
+ offspring.append(child)
38
+ self.population += offspring
39
+
40
+ def mutation(self):
41
+ for i in range(self.population_size):
42
+ if random.random() < 0.1:
43
+ self.population[i] += random.uniform(-1, 1)
44
+
45
+ # Streamlit app
46
+ st.title("Neural Network vs Genetic Algorithm")
47
+
48
+ # Parameters
49
+ st.sidebar.header("Parameters")
50
+ population_size = st.sidebar.slider("Population size", 10, 100, 50)
51
+ nn_iterations = st.sidebar.slider("Neural network iterations", 10, 1000, 100)
52
+ ga_iterations = st.sidebar.slider("Genetic algorithm iterations", 10, 100, 50)
53
+
54
+ # Run the experiment
55
+ if st.button("Run experiment"):
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
+ # Train the neural network
63
+ nn_losses = []
64
+ for i in range(nn_iterations):
65
+ x = torch.randn(1, 1)
66
+ y = f(x)
67
+ y_pred = net(x)
68
+ loss = criterion(y_pred, y)
69
+ optimizer.zero_grad()
70
+ loss.backward()
71
+ optimizer.step()
72
+ nn_losses.append(loss.item())
73
+
74
+ # Run the genetic algorithm
75
+ ga_values = []
76
+ for i in range(ga_iterations):
77
+ ga.selection()
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])