Sha256: 5067ae605964c1bd4f8d8c87bd27222d67553f8b943db1328f3cdd59fa733b48

Contents?: true

Size: 1.78 KB

Versions: 7

Compression:

Stored size: 1.78 KB

Contents

# frozen_string_literal: true

require 'rumale/base/evaluator'
require 'rumale/pairwise_metric'

module Rumale
  module EvaluationMeasure
    # DaviesBouldinScore is a class that calculates the Davies-Bouldin score.
    #
    # @example
    #   require 'rumale/evaluation_measure/davies_bouldin_score'
    #
    #   evaluator = Rumale::EvaluationMeasure::DaviesBouldinScore.new
    #   puts evaluator.score(x, predicted)
    #
    # *Reference*
    # - Davies, D L., and Bouldin, D W., "A Cluster Separation Measure," IEEE Trans. Pattern Analysis and Machine Intelligence, Vol. PAMI-1, No. 2, pp. 224--227, 1979.
    class DaviesBouldinScore
      # Calculates the Davies-Bouldin score.
      #
      # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to be used for calculating score.
      # @param y [Numo::Int32] (shape: [n_samples]) The predicted labels for each sample.
      # @return [Float] The Davies-Bouldin score.
      def score(x, y)
        labels = y.to_a.uniq.sort
        n_clusters = labels.size
        n_dimensions = x.shape[1]

        dist_cluster = Numo::DFloat.zeros(n_clusters)
        centroids = Numo::DFloat.zeros(n_clusters, n_dimensions)

        n_clusters.times do |n|
          cls_samples = x[y.eq(labels[n]), true]
          cls_centroid = cls_samples.mean(0)
          centroids[n, true] = cls_centroid
          dist_cluster[n] = Rumale::PairwiseMetric.euclidean_distance(cls_samples, cls_centroid.expand_dims(0)).mean
        end

        dist_centroid = Rumale::PairwiseMetric.euclidean_distance(centroids)
        dist_centroid[dist_centroid.eq(0)] = Float::INFINITY
        dist_mat = (dist_cluster.expand_dims(1) + dist_cluster) / dist_centroid
        dist_mat[dist_mat.diag_indices] = -Float::INFINITY
        dist_mat.max(0).mean
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
rumale-evaluation_measure-0.29.0 lib/rumale/evaluation_measure/davies_bouldin_score.rb
rumale-evaluation_measure-0.28.1 lib/rumale/evaluation_measure/davies_bouldin_score.rb
rumale-evaluation_measure-0.28.0 lib/rumale/evaluation_measure/davies_bouldin_score.rb
rumale-evaluation_measure-0.27.0 lib/rumale/evaluation_measure/davies_bouldin_score.rb
rumale-evaluation_measure-0.26.0 lib/rumale/evaluation_measure/davies_bouldin_score.rb
rumale-evaluation_measure-0.25.0 lib/rumale/evaluation_measure/davies_bouldin_score.rb
rumale-evaluation_measure-0.24.0 lib/rumale/evaluation_measure/davies_bouldin_score.rb