Class: TLearn::K_Means::Cluster

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

Overview

cluster cluster has id, vec, and v_list

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, vec = nil, v_list = nil, dim = 1) ⇒ Cluster

Returns a new instance of Cluster.



70
71
72
73
74
75
76
# File 'lib/t_learn/k_means.rb', line 70

def initialize(id, vec=nil, v_list=nil, dim=1)
  @id = id
  @v_list= v_list
  @vec = dim.times.map{0.0} if vec == nil
  @dim = dim
  calc_center()
end

Instance Attribute Details

#idObject

Returns the value of attribute id.



68
69
70
# File 'lib/t_learn/k_means.rb', line 68

def id
  @id
end

#last_vecObject

Returns the value of attribute last_vec.



68
69
70
# File 'lib/t_learn/k_means.rb', line 68

def last_vec
  @last_vec
end

#v_listObject

Returns the value of attribute v_list.



68
69
70
# File 'lib/t_learn/k_means.rb', line 68

def v_list
  @v_list
end

#vecObject

Returns the value of attribute vec.



68
69
70
# File 'lib/t_learn/k_means.rb', line 68

def vec
  @vec
end

Instance Method Details

#add_v(v) ⇒ Object



90
91
92
# File 'lib/t_learn/k_means.rb', line 90

def add_v(v)
  @v_list.push(v)
end

#calc_centerObject



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/t_learn/k_means.rb', line 78

def calc_center() 
  @last_vec = Marshal.load(Marshal.dump(@vec))
  vec_sum = Array.new
  @v_list.each { |v|
    v.each_with_index { |v_x, i| 
      vec_sum[i] ||= 0.0
      vec_sum[i] += v_x 
    } 
  }
  vec_sum.each_with_index { |new_vec, i| @vec[i] = new_vec/@v_list.size.to_f } 
end

#change_center?Boolean

Returns:

  • (Boolean)


98
99
100
101
102
103
# File 'lib/t_learn/k_means.rb', line 98

def change_center?
  @dim.times { |i|
    return true if @vec[i] != @last_vec[i]
  }
  return false
end

#format_hashObject



105
106
107
108
109
110
111
# File 'lib/t_learn/k_means.rb', line 105

def format_hash()
  cluster_hash = {}
  cluster_hash[:id] = @id
  cluster_hash[:vec] = @vec
  cluster_hash[:v_list] = @v_list
  return cluster_hash
end

#reset_v_listObject



94
95
96
# File 'lib/t_learn/k_means.rb', line 94

def reset_v_list()
  @v_list = []
end