Class: Broadlistening::KMeans

Inherits:
Object
  • Object
show all
Defined in:
lib/broadlistening/kmeans.rb

Constant Summary collapse

DEFAULT_MAX_ITERATIONS =
100
DEFAULT_TOLERANCE =
1e-6

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(n_clusters:, max_iterations: DEFAULT_MAX_ITERATIONS, random_state: nil, tolerance: DEFAULT_TOLERANCE) ⇒ KMeans

Returns a new instance of KMeans.



10
11
12
13
14
15
16
17
18
# File 'lib/broadlistening/kmeans.rb', line 10

def initialize(n_clusters:, max_iterations: DEFAULT_MAX_ITERATIONS, random_state: nil, tolerance: DEFAULT_TOLERANCE)
  @n_clusters = n_clusters
  @max_iterations = max_iterations
  @tolerance = tolerance
  @random = random_state ? Random.new(random_state) : Random.new
  @centroids = nil
  @labels = nil
  @inertia = nil
end

Instance Attribute Details

#centroidsObject (readonly)

Returns the value of attribute centroids.



5
6
7
# File 'lib/broadlistening/kmeans.rb', line 5

def centroids
  @centroids
end

#inertiaObject (readonly)

Returns the value of attribute inertia.



5
6
7
# File 'lib/broadlistening/kmeans.rb', line 5

def inertia
  @inertia
end

#labelsObject (readonly)

Returns the value of attribute labels.



5
6
7
# File 'lib/broadlistening/kmeans.rb', line 5

def labels
  @labels
end

#n_clustersObject (readonly)

Returns the value of attribute n_clusters.



5
6
7
# File 'lib/broadlistening/kmeans.rb', line 5

def n_clusters
  @n_clusters
end

Instance Method Details

#fit(data) ⇒ Object



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

def fit(data)
  @data = to_numo_array(data)
  validate_data!

  @centroids = initialize_centroids_pp
  @labels = Array.new(@data.shape[0])

  @max_iterations.times do
    @labels = assign_labels
    new_centroids = update_centroids

    if converged?(new_centroids)
      @centroids = new_centroids
      break
    end

    @centroids = new_centroids
  end

  @inertia = compute_inertia
  self
end

#fit_predict(data) ⇒ Object



48
49
50
51
# File 'lib/broadlistening/kmeans.rb', line 48

def fit_predict(data)
  fit(data)
  @labels
end

#predict(data) ⇒ Object



43
44
45
46
# File 'lib/broadlistening/kmeans.rb', line 43

def predict(data)
  data = to_numo_array(data)
  assign_labels_for(data)
end