Class: Node

Inherits:
Object show all
Defined in:
lib/k_means/node.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(position, similarity_measure) ⇒ Node

Returns a new instance of Node.



15
16
17
18
# File 'lib/k_means/node.rb', line 15

def initialize(position, similarity_measure)
  @position = position
  @similarity_measure = similarity_measure
end

Instance Attribute Details

#best_distanceObject

Returns the value of attribute best_distance.



13
14
15
# File 'lib/k_means/node.rb', line 13

def best_distance
  @best_distance
end

#closest_centroidObject

Returns the value of attribute closest_centroid.



13
14
15
# File 'lib/k_means/node.rb', line 13

def closest_centroid
  @closest_centroid
end

#positionObject

Returns the value of attribute position.



13
14
15
# File 'lib/k_means/node.rb', line 13

def position
  @position
end

Class Method Details

.create_nodes(data, similarity_measure) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/k_means/node.rb', line 4

def create_nodes(data, similarity_measure)
  nodes = []
  data.each do |position|
    nodes << new(position, similarity_measure)
  end
  nodes
end

Instance Method Details

#reset!Object



42
43
44
45
# File 'lib/k_means/node.rb', line 42

def reset!
  @closest_centroid = nil
  @best_distance    = nil
end

#update_closest_centroid(centroids) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/k_means/node.rb', line 20

def update_closest_centroid(centroids)
  # If we haven't processed this node we need to give it an initial centroid
  # so that we have something to compare distances against
  calculate_initial_centroid(centroids.first) unless @closest_centroid

  updated = false
  centroids.each do |centroid|
    # Check if they are in the same position
    if centroid.position == @position
      updated = update_attributes(centroid, 0.0)
      break
    end

    distance = calculate_distance(centroid)
    if distance < best_distance
      updated = update_attributes(centroid, distance)
    end
  end

  updated == true ? 1 : 0
end