elbow_method

Function elbow_method 

Source
pub fn elbow_method<F, S>(
    x: &ArrayBase<S, Ix2>,
    k_range: RangeInclusive<usize>,
    kmeans_fn: impl Fn(&ArrayBase<S, Ix2>, usize) -> F,
) -> Result<Vec<F>>
where F: Float + NumCast + Debug, S: Data<Elem = F>,
Expand description

Implements the elbow method to determine the optimal number of clusters

The elbow method computes the sum of squared distances for a range of k values and helps identify where the rate of decrease sharply changes (the “elbow”).

§Arguments

  • x - Data matrix, shape (n_samples, n_features)
  • k_range - Range of k values to evaluate
  • kmeans_fn - Function that runs k-means clustering and returns (centroids, labels, inertia)

§Returns

  • Vector of inertia values for each k in k_range

§Examples

use scirs2_core::ndarray::{Array1, Array2};
use scirs2_metrics::clustering::elbow_method;

// Create a dataset
let x = Array2::<f64>::zeros((100, 2));

// Define a function that runs k-means
let kmeans_fn = |data: &Array2<f64>, k: usize| {
    // In a real example, you would call your actual k-means implementation
    // This is just a placeholder
    let inertia = k as f64; // Placeholder value
    inertia
};

// Run elbow method for k from 1 to 10
let inertias = elbow_method(&x, 1..=10, kmeans_fn).unwrap();

// Now you can plot inertias against k to find the "elbow"