-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxor.rb
64 lines (45 loc) · 1.04 KB
/
xor.rb
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
#!/usr/bin/env ruby
require 'brains'
# Build a 3 layer network: 4 input neurons, 4 hidden neurons, 3 output neurons
# Bias neurons are automatically added to input + hidden layers; no need to specify these
# 5 = 4 in one hidden layer + 1 output neuron (input neurons not counted)
nn = Brains::Net.create(2, 1, 1, { neurons_per_layer: 4 })
nn.randomize_weights
# A B A XOR B
# 1 1 0
# 1 0 1
# 0 1 1
# 0 0 0
training_data = [
[[0.9, 0.9], [0.1]],
[[0.9, 0.1], [0.9]],
[[0.1, 0.9], [0.9]],
[[0.1, 0.1], [0.1]],
]
# test on untrained data
test_data = [
[0.9, 0.9],
[0.9, 0.1],
[0.1, 0.9],
[0.1, 0.1]
]
results = test_data.collect { |item|
nn.feed(item)
}
p results
result = nn.optimize(training_data, 0.01, 1_000_000 ) { |i, error|
puts "#{i} #{error}"
}
puts "after training"
results = test_data.collect { |item|
nn.feed(item)
}
p results
state = nn.to_json
puts state
nn2 = Brains::Net.load(state)
results2 = test_data.collect { |item|
nn2.feed(item)
}
puts "use saved state"
p results2