Skip to content

Commit

Permalink
add pole balancing example
Browse files Browse the repository at this point in the history
  • Loading branch information
bhark committed Jun 3, 2024
1 parent f1ae194 commit f943de7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
7 changes: 7 additions & 0 deletions examples/pole_balancing/config.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[NeuralNetwork]
num_inputs = 4
num_outputs = 2

[Evolution]
max_fitness = 500
max_generations = 20
39 changes: 39 additions & 0 deletions examples/pole_balancing/pole_balancing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import gymnasium as gym
import sys
import os
import numpy as np

sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))

from sneat import evolve

def fitness(genome, render=False):
env = gym.make('CartPole-v1', render_mode='human' if render else 'rgb_array')

fitnesses = []
for _ in range(20):
fitness = 0

obs, info = env.reset()
while True:
obs = list(obs)
action = genome.activate(obs)
action = np.argmax(action)
obs, reward, terminated, truncated, info = env.step(action)

fitness += reward

if terminated or truncated:
break

fitnesses.append(fitness)

env.close()
return np.mean(fitnesses)

def main():
winner = evolve(fitness)
fitness(winner, render=True)

if __name__ == '__main__':
main()

0 comments on commit f943de7

Please sign in to comment.