Skip to content

Commit cbe3e2a

Browse files
MorvanZhouMorvan Zhou
authored andcommitted
update
1 parent 6787037 commit cbe3e2a

6 files changed

Lines changed: 660 additions & 0 deletions

File tree

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#--- parameters for the XOR-2 experiment ---#
2+
3+
[NEAT]
4+
fitness_criterion = max
5+
fitness_threshold = 3.9
6+
pop_size = 150
7+
reset_on_extinction = False
8+
9+
[DefaultGenome]
10+
# node activation options
11+
activation_default = sigmoid
12+
activation_mutate_rate = 0.0
13+
activation_options = sigmoid
14+
15+
# node aggregation options
16+
aggregation_default = sum
17+
aggregation_mutate_rate = 0.0
18+
aggregation_options = sum
19+
20+
# node bias options
21+
bias_init_mean = 0.0
22+
bias_init_stdev = 1.0
23+
bias_max_value = 30.0
24+
bias_min_value = -30.0
25+
bias_mutate_power = 0.5
26+
bias_mutate_rate = 0.7
27+
bias_replace_rate = 0.1
28+
29+
# genome compatibility options
30+
compatibility_disjoint_coefficient = 1.0
31+
compatibility_weight_coefficient = 0.5
32+
33+
# connection add/remove rates
34+
conn_add_prob = 0.5
35+
conn_delete_prob = 0.5
36+
37+
# connection enable options
38+
enabled_default = True
39+
enabled_mutate_rate = 0.01
40+
41+
feed_forward = True
42+
initial_connection = full
43+
44+
# node add/remove rates
45+
node_add_prob = 0.2
46+
node_delete_prob = 0.2
47+
48+
# network parameters
49+
num_hidden = 0
50+
num_inputs = 2
51+
num_outputs = 1
52+
53+
# node response options
54+
response_init_mean = 1.0
55+
response_init_stdev = 0.0
56+
response_max_value = 30.0
57+
response_min_value = -30.0
58+
response_mutate_power = 0.0
59+
response_mutate_rate = 0.0
60+
response_replace_rate = 0.0
61+
62+
# connection weight options
63+
weight_init_mean = 0.0
64+
weight_init_stdev = 1.0
65+
weight_max_value = 30
66+
weight_min_value = -30
67+
weight_mutate_power = 0.5
68+
weight_mutate_rate = 0.8
69+
weight_replace_rate = 0.1
70+
71+
[DefaultSpeciesSet]
72+
compatibility_threshold = 3.0
73+
74+
[DefaultStagnation]
75+
species_fitness_func = max
76+
max_stagnation = 20
77+
species_elitism = 2
78+
79+
[DefaultReproduction]
80+
elitism = 2
81+
survival_threshold = 0.2
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
from __future__ import print_function
2+
3+
import copy
4+
import warnings
5+
6+
import graphviz
7+
import matplotlib.pyplot as plt
8+
import numpy as np
9+
10+
11+
def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'):
12+
""" Plots the population's average and best fitness. """
13+
if plt is None:
14+
warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
15+
return
16+
17+
generation = range(len(statistics.most_fit_genomes))
18+
best_fitness = [c.fitness for c in statistics.most_fit_genomes]
19+
avg_fitness = np.array(statistics.get_fitness_mean())
20+
stdev_fitness = np.array(statistics.get_fitness_stdev())
21+
22+
plt.plot(generation, avg_fitness, 'b-', label="average")
23+
plt.plot(generation, avg_fitness - stdev_fitness, 'g-.', label="-1 sd")
24+
plt.plot(generation, avg_fitness + stdev_fitness, 'g-.', label="+1 sd")
25+
plt.plot(generation, best_fitness, 'r-', label="best")
26+
27+
plt.title("Population's average and best fitness")
28+
plt.xlabel("Generations")
29+
plt.ylabel("Fitness")
30+
plt.grid()
31+
plt.legend(loc="best")
32+
if ylog:
33+
plt.gca().set_yscale('symlog')
34+
35+
plt.savefig(filename)
36+
if view:
37+
plt.show()
38+
39+
plt.close()
40+
41+
42+
def plot_spikes(spikes, view=False, filename=None, title=None):
43+
""" Plots the trains for a single spiking neuron. """
44+
t_values = [t for t, I, v, u, f in spikes]
45+
v_values = [v for t, I, v, u, f in spikes]
46+
u_values = [u for t, I, v, u, f in spikes]
47+
I_values = [I for t, I, v, u, f in spikes]
48+
f_values = [f for t, I, v, u, f in spikes]
49+
50+
fig = plt.figure()
51+
plt.subplot(4, 1, 1)
52+
plt.ylabel("Potential (mv)")
53+
plt.xlabel("Time (in ms)")
54+
plt.grid()
55+
plt.plot(t_values, v_values, "g-")
56+
57+
if title is None:
58+
plt.title("Izhikevich's spiking neuron model")
59+
else:
60+
plt.title("Izhikevich's spiking neuron model ({0!s})".format(title))
61+
62+
plt.subplot(4, 1, 2)
63+
plt.ylabel("Fired")
64+
plt.xlabel("Time (in ms)")
65+
plt.grid()
66+
plt.plot(t_values, f_values, "r-")
67+
68+
plt.subplot(4, 1, 3)
69+
plt.ylabel("Recovery (u)")
70+
plt.xlabel("Time (in ms)")
71+
plt.grid()
72+
plt.plot(t_values, u_values, "r-")
73+
74+
plt.subplot(4, 1, 4)
75+
plt.ylabel("Current (I)")
76+
plt.xlabel("Time (in ms)")
77+
plt.grid()
78+
plt.plot(t_values, I_values, "r-o")
79+
80+
if filename is not None:
81+
plt.savefig(filename)
82+
83+
if view:
84+
plt.show()
85+
plt.close()
86+
fig = None
87+
88+
return fig
89+
90+
91+
def plot_species(statistics, view=False, filename='speciation.svg'):
92+
""" Visualizes speciation throughout evolution. """
93+
if plt is None:
94+
warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
95+
return
96+
97+
species_sizes = statistics.get_species_sizes()
98+
num_generations = len(species_sizes)
99+
curves = np.array(species_sizes).T
100+
101+
fig, ax = plt.subplots()
102+
ax.stackplot(range(num_generations), *curves)
103+
104+
plt.title("Speciation")
105+
plt.ylabel("Size per Species")
106+
plt.xlabel("Generations")
107+
108+
plt.savefig(filename)
109+
110+
if view:
111+
plt.show()
112+
113+
plt.close()
114+
115+
116+
def draw_net(config, genome, view=False, filename=None, node_names=None, show_disabled=True, prune_unused=False,
117+
node_colors=None, fmt='svg'):
118+
""" Receives a genome and draws a neural network with arbitrary topology. """
119+
# Attributes for network nodes.
120+
if graphviz is None:
121+
warnings.warn("This display is not available due to a missing optional dependency (graphviz)")
122+
return
123+
124+
if node_names is None:
125+
node_names = {}
126+
127+
assert type(node_names) is dict
128+
129+
if node_colors is None:
130+
node_colors = {}
131+
132+
assert type(node_colors) is dict
133+
134+
node_attrs = {
135+
'shape': 'circle',
136+
'fontsize': '9',
137+
'height': '0.2',
138+
'width': '0.2'}
139+
140+
dot = graphviz.Digraph(format=fmt, node_attr=node_attrs)
141+
142+
inputs = set()
143+
for k in config.genome_config.input_keys:
144+
inputs.add(k)
145+
name = node_names.get(k, str(k))
146+
input_attrs = {'style': 'filled',
147+
'shape': 'box'}
148+
input_attrs['fillcolor'] = node_colors.get(k, 'lightgray')
149+
dot.node(name, _attributes=input_attrs)
150+
151+
outputs = set()
152+
for k in config.genome_config.output_keys:
153+
outputs.add(k)
154+
name = node_names.get(k, str(k))
155+
node_attrs = {'style': 'filled'}
156+
node_attrs['fillcolor'] = node_colors.get(k, 'lightblue')
157+
158+
dot.node(name, _attributes=node_attrs)
159+
160+
if prune_unused:
161+
connections = set()
162+
for cg in genome.connections.values():
163+
if cg.enabled or show_disabled:
164+
connections.add((cg.in_node_id, cg.out_node_id))
165+
166+
used_nodes = copy.copy(outputs)
167+
pending = copy.copy(outputs)
168+
while pending:
169+
new_pending = set()
170+
for a, b in connections:
171+
if b in pending and a not in used_nodes:
172+
new_pending.add(a)
173+
used_nodes.add(a)
174+
pending = new_pending
175+
else:
176+
used_nodes = set(genome.nodes.keys())
177+
178+
for n in used_nodes:
179+
if n in inputs or n in outputs:
180+
continue
181+
182+
attrs = {'style': 'filled',
183+
'fillcolor': node_colors.get(n, 'white')}
184+
dot.node(str(n), _attributes=attrs)
185+
186+
for cg in genome.connections.values():
187+
if cg.enabled or show_disabled:
188+
#if cg.input not in used_nodes or cg.output not in used_nodes:
189+
# continue
190+
input, output = cg.key
191+
a = node_names.get(input, str(input))
192+
b = node_names.get(output, str(output))
193+
style = 'solid' if cg.enabled else 'dotted'
194+
color = 'green' if cg.weight > 0 else 'red'
195+
width = str(0.1 + abs(cg.weight / 5.0))
196+
dot.edge(a, b, _attributes={'style': style, 'color': color, 'penwidth': width})
197+
198+
dot.render(filename, view=view)
199+
200+
return dot

‎tutorial-contents/NEAT/xor.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
2-input XOR example -- this is most likely the simplest possible example.
3+
"""
4+
5+
import os
6+
import neat
7+
import visualize
8+
9+
# 2-input XOR inputs and expected outputs.
10+
xor_inputs = [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0)]
11+
xor_outputs = [ (0.0,), (1.0,), (1.0,), (0.0,)]
12+
13+
14+
def eval_genomes(genomes, config):
15+
for genome_id, genome in genomes: # for each individual
16+
genome.fitness = 4.0 # 4 xor evaluations
17+
net = neat.nn.FeedForwardNetwork.create(genome, config)
18+
for xi, xo in zip(xor_inputs, xor_outputs):
19+
output = net.activate(xi)
20+
genome.fitness -= (output[0] - xo[0]) ** 2
21+
22+
23+
def run(config_file):
24+
# Load configuration.
25+
config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
26+
neat.DefaultSpeciesSet, neat.DefaultStagnation,
27+
config_file)
28+
29+
# Create the population, which is the top-level object for a NEAT run.
30+
p = neat.Population(config)
31+
32+
# Add a stdout reporter to show progress in the terminal.
33+
p.add_reporter(neat.StdOutReporter(True))
34+
stats = neat.StatisticsReporter()
35+
p.add_reporter(stats)
36+
p.add_reporter(neat.Checkpointer(50))
37+
38+
# Run for up to 300 generations.
39+
winner = p.run(eval_genomes, 300)
40+
41+
# Display the winning genome.
42+
print('\nBest genome:\n{!s}'.format(winner))
43+
44+
# Show output of the most fit genome against training data.
45+
print('\nOutput:')
46+
winner_net = neat.nn.FeedForwardNetwork.create(winner, config)
47+
for xi, xo in zip(xor_inputs, xor_outputs):
48+
output = winner_net.activate(xi)
49+
print("input {!r}, expected output {!r}, got {!r}".format(xi, xo, output))
50+
51+
node_names = {-1:'A', -2: 'B', 0:'A XOR B'}
52+
visualize.draw_net(config, winner, True, node_names=node_names)
53+
visualize.plot_stats(stats, ylog=False, view=True)
54+
visualize.plot_species(stats, view=True)
55+
56+
p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-49')
57+
p.run(eval_genomes, 10)
58+
59+
60+
if __name__ == '__main__':
61+
# Determine path to configuration file. This path manipulation is
62+
# here so that the script will run successfully regardless of the
63+
# current working directory.
64+
local_dir = os.path.dirname(__file__)
65+
config_path = os.path.join(local_dir, 'config-feedforward')
66+
run(config_path)

0 commit comments

Comments
 (0)