Class: Brian::NeuralNetwork

Inherits:
Object
  • Object
show all
Defined in:
lib/brian/hash.rb,
lib/brian/neural_network.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeNeuralNetwork

Returns a new instance of NeuralNetwork.



16
17
18
19
# File 'lib/brian/neural_network.rb', line 16

def initialize
	@learning_rate = 0.3
	@momentum = 0.1
end

Class Method Details

.activation_function(sum) ⇒ Object



12
13
14
# File 'lib/brian/neural_network.rb', line 12

def self.activation_function(sum)
	1.0 / (1.0 + Math.exp(-sum))
end

.mse(errors) ⇒ Object



8
9
10
# File 'lib/brian/neural_network.rb', line 8

def self.mse(errors)
	errors.map {|e| e**2}.inject(:+)/errors.length
end

.new_with_hash(hash) ⇒ Object



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
# File 'lib/brian/hash.rb', line 38

def self.new_with_hash(hash)
	net = NeuralNetwork.new

	net.instance_eval do
		size = hash[:layers].count
		@output_layer = size -1

		@sizes = Array.new(size)
		@weights = Array.new(size)
		@biases = Array.new(size)
		@outputs = Array.new(size)

		hash[:layers].each_with_index do |layer, i|
			if i == 0 and layer[0].nil?
				@input_lookup = Brian::Lookup.lookup_from_hash(layer)
			end

			if i == @output_layer and layer[0].nil?
				@output_lookup = Brian::Lookup.lookup_from_hash(layer)
			end

			nodes = layer.keys

			@sizes[i] = nodes.count
			@weights[i] = []
			@biases[i] = []
			@outputs[i] = []

			nodes.each_with_index do |node, j|
				@biases[i][j] = layer[node][:bias]
				@weights[i][j] = layer[node][:weights].nil? ? nil : layer[node][:weights].values
			end
		end

	end
	return net
end

.random_weightObject



4
5
6
# File 'lib/brian/neural_network.rb', line 4

def self.random_weight
	rand()*0.4 - 0.2
end

Instance Method Details

#adjust_weightsObject



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/brian/neural_network.rb', line 199

def adjust_weights
	@sizes.count.times do |layer|
		next if layer == 0
		incoming = @outputs[layer-1]

		@sizes[layer].times do |node|
			delta = @deltas[layer][node]

			incoming.each_with_index do |i,k|
				change = @changes[layer][node][k]

				change *= @momentum
				change += @learning_rate * delta * i

				@changes[layer][node][k] = change
				@weights[layer][node][k] += change
			end

			@biases[layer][node] += @learning_rate * delta
		end
	end
end

#calculate_deltas(target) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/brian/neural_network.rb', line 177

def calculate_deltas(target)
	@sizes.length.times do |layer|
		layer = -(layer+1)
		@sizes[layer].times do |node|
			output = @outputs[layer][node]
			error = 0

			if layer == -1 #Output layer
				error = (target[node] - output).to_f
			else
				deltas = @deltas[layer+1]
				deltas.each_with_index do |d,k|
					error += d * @weights[layer+1][k][node]
				end
			end

			@errors[layer][node] = error
			@deltas[layer][node] = error*output*(1.0-output)
		end
	end
end

#format_data(data) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/brian/neural_network.rb', line 87

def format_data(data)
	if not data[0][:input].is_a?(Array)
		if @input_lookup.nil?
			inputs = data.map {|d| d[:input]}
			@input_lookup = Brian::Lookup.build_lookup(inputs)
		end

		data.each do |d|
			d[:input] = Brian::Lookup.to_array(@input_lookup,d[:input])
		end
	end

	if not data[0][:output].is_a?(Array)
		if @output_lookup.nil?
			inputs = data.map {|d| d[:output]}
			@output_lookup = Brian::Lookup.build_lookup(inputs)
		end

		data.each do |d|
			d[:output] = Brian::Lookup.to_array(@output_lookup,d[:output])
		end
	end

	return data
end

#initialize_layers(sizes) ⇒ Object



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
# File 'lib/brian/neural_network.rb', line 22

def initialize_layers(sizes)
	@sizes = sizes
	@output_layer = @sizes.length - 1

	@biases = []
	@weights = []
	@outputs = []

	@deltas = []
	@changes = []
	@errors = []

	@sizes.length.times do |layer|
		size = @sizes[layer]

		@deltas[layer] = Array.new(size) {0}
		@errors[layer] = Array.new(size) {0}
		@outputs[layer] = Array.new(size) {0}

		next if layer == 0

		@biases[layer] = Array.new(size) {NeuralNetwork.random_weight}
		@weights[layer] = Array.new(size)
		@changes[layer] = Array.new(size)

		size.times do |node|
			prev_size = @sizes[layer - 1]
			@weights[layer][node] = Array.new(prev_size) {NeuralNetwork.random_weight}
			@changes[layer][node] = Array.new(prev_size) {0}

		end
	end
end

#run(input) ⇒ Object



56
57
58
59
60
61
62
63
64
# File 'lib/brian/neural_network.rb', line 56

def run(input)
	input = Brian::Lookup.to_array(@input_lookup, input) if @input_lookup

	output = self.run_input(input)

	output = Brian::Lookup.to_hash(@output_lookup, output) if @output_lookup

	return output
end

#run_input(input) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/brian/neural_network.rb', line 66

def run_input(input)
	@outputs[0] = input

	@sizes.count.times do |layer|
		next if layer == 0
		@sizes[layer].times do |node|
			weights = @weights[layer][node]
			sum = @biases[layer][node]

			weights.each_with_index {|w,k| sum += w*input[k]}
			
			@outputs[layer][node] = NeuralNetwork.activation_function(sum)
		end

		input = @outputs[layer]
	end


	return @outputs[@output_layer]
end

#to_hashObject



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
# File 'lib/brian/hash.rb', line 4

def to_hash
	layers = []
	@sizes.count.times do |layer|
		layers[layer] = {}

		if layer == 0 and @input_lookup
			nodes = @input_lookup.keys
		elsif (layer == @output_layer) and @output_lookup
			nodes = @output_lookup.keys
		else
			nodes = (0..@sizes[layer]-1).to_a
		end


		nodes.each_with_index do |node,j|
			layers[layer][node] = {}

			next if layer == 0
			layers[layer][node][:bias] = @biases[layer][j]

			layers[layer][node][:weights] = {}

			layers[layer-1].keys.each do |k|
				index = k
				index = @input_lookup[k] if (layer == 1) and @input_lookup
				
				layers[layer][node][:weights][k] = @weights[layer][j][index]	
			end
		end
	end

	return {layers:layers}
end

#train(data, options = {}) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/brian/neural_network.rb', line 113

def train(data, options = {})
	data = self.format_data(data)

	options = ({
		iterations:20000,
		error_thresh:0.005,
		log:false,
		log_period:10,
		callback_period:10
	}).merge(options)

	input_size = data[0][:input].size
	output_size = data[0][:output].size
	
	hidden_sizes = @hidden_sizes

	if hidden_sizes.nil?
		hidden_sizes = [[3,(input_size.to_f/2).floor].max]
	end

	sizes = [input_size,hidden_sizes,output_size].flatten
	self.initialize_layers(sizes)

	error = 1

	iterations = 0
	options[:iterations].times do |i|
		sum = 0
		iterations = i
		data.each do |d|
			err = self.train_pattern(d[:input],d[:output])
			sum += err
		end

		error = sum/data.count

		if options[:log] and (i % options[:log_period] == 0)
			puts "iterations:#{i} training_error #{error}"
		end

		if options[:callback] and (i % options[:callback_period] == 0)
			options[:callback].call({error:error, iterations:i})
		end

		break if error <= options[:error_thresh]
	end

	return {error:error, iterations:iterations}
end

#train_pattern(input, target) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/brian/neural_network.rb', line 164

def train_pattern(input, target)
	#Forward propogate
	self.run_input(input)

	#Back propogate
	self.calculate_deltas(target)
	self.adjust_weights()

	error = Brian::NeuralNetwork.mse(@errors[@output_layer])

	return error
end