forked from jzhuo/genetic-sgd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_genetic_algorithm.py
86 lines (76 loc) · 2.82 KB
/
test_genetic_algorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import unittest
import numpy as np
from genetic_algorithm import GeneticAlgorithm
class TestGeneticAlgorithm(unittest.TestCase):
def setUp(self):
# initializing variables for self.ga
self.expected_input_size = 2
self.expected_hidden_size = 5
self.expected_output_size = 1
self.population_size = 10
self.selection_size = 2
self.learning_rate = 1e-3
self.epochs = 5
self.generations = 2
self.ga = GeneticAlgorithm(
False,
self.expected_input_size,
self.expected_hidden_size,
self.expected_output_size,
self.population_size,
self.selection_size,
self.learning_rate,
self.epochs,
self.generations,
)
self.hga = GeneticAlgorithm(
True,
self.expected_input_size,
self.expected_hidden_size,
self.expected_output_size,
self.population_size,
self.selection_size,
self.learning_rate,
self.epochs,
self.generations,
)
pass
def test_population_init(self):
"""Verify ga.population is initialized properly."""
self.assertEqual(self.population_size, len(self.ga.population))
pass
def test_lexicase_selection(self):
"""Verify lexicase selection on cases occurs properly."""
self.ga.select()
self.assertEqual(self.selection_size, len(self.ga.population))
pass
def test_mutation(self):
"""Verify that mutation changes weights."""
for index in range(len(self.ga.population)):
prev_weights = self.ga.population[index].get_weights()
self.ga.mutate()
self.assertNotEqual(
prev_weights, self.ga.population[index].get_weights
)
pass
def test_recombination(self):
"""Verify recombination occurs at proper split points."""
self.assertEqual(self.selection_size, len(self.ga.population))
# sum of weights calculated from first
weight_sum = 0
for pop in range(len(self.ga.population)):
weight_sum += np.sum(self.ga.population[pop].get_weights())
self.ga.recombine()
# tests for population size
self.assertEqual(self.population_size, len(self.ga.population))
# tests for sum of weights post recombination
for index in range(len(self.ga.population) / 2):
new_weight_sum = np.sum(
self.ga.population[index].get_weights()
) + np.sum(self.ga.population[index + 1].get_weights())
self.assertEqual(weight_sum, new_weight_sum)
pass
# TODO add sklearn BaseEstimator test
# (see if it conforms to the duck-typing)
if __name__ == "__main__":
unittest.main()