Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 78 lines (65 sloc) 1.705 kb
b2d8731 Olav Bjorkoy initial commit
olav authored
1 class SOM
2 attr_reader :neurons
3
4 def initialize(n)
5 @neurons = Array.new(n).map { Neuron.new }
6 end
7
8 def train(c, d, a)
9 neuron = closest(c)
10 neuron.update!(c,a)
11 ns = neighbors(neuron, d.ceil)
12 ns.each do |n|
13 a -= a / (ns.size.to_f + 1.0)
14 n[0].update!(c,a)
15 n[1].update!(c,a)
16 end
17 end
18
19 def current_path(norm, iteration)
20 map = Array.new(@neurons.size, [])
21 norm.each_with_index do |city_coords, city_index|
22 nearest = nil
23 dist = nil
24 @neurons.each_with_index do |neuron, neuron_index|
25 d = Math.rel_distance(city_coords, neuron.w)
26 if nearest.nil? or d < dist
27 nearest = neuron_index
28 dist = d
29 end
30 end
31 map[nearest] += [city_index]
32 end
33
34 if Settings::AddNeurons.include?(iteration)
35 map.each_with_index do |cities, neuron_index|
36 next if cities.size <= 1
37 neuron = Neuron.new
38 neuron.move_close_to(@neurons[neuron_index])
39 @neurons.insert(neuron_index, neuron)
40 end
41 puts " New neuron count: #{@neurons.size}"
42 end
43
44 map.flatten
45 end
46
47
48 private
49
50 def closest(city)
51 closest = nil
52 closest_dist = nil
53 @neurons.each do |n|
54 d = Math.rel_distance(city, n.w)
55
56 #d = Math.dot_product(
57 # Math.normalize_2d_vector(city),
58 # Math.normalize_2d_vector(n.w))
59
60 if closest.nil? or d < closest_dist
61 closest = n
62 closest_dist = d
63 end
64 end
65 closest
66 end
67
68 def neighbors(i,n=1)
69 i = @neurons.index(i) if i.is_a?(Neuron)
70 s = @neurons.size
71 (1..n).map do |x|
72 [@neurons[(i+x) % s],
73 @neurons[(i-x) % s]]
74 end
75 end
76
77 end
Something went wrong with that request. Please try again.