KMedoids<T>

Models & Types · AiDotNet.Clustering.Partitioning

K-Medoids (PAM - Partitioning Around Medoids) clustering implementation.

Inheritance: ClusteringBase<T> → KMedoids<T>

For Beginners

K-Medoids is K-Means with real data points as centers.

Key benefits:

  • More robust to outliers than K-Means
  • Works with any distance metric
  • Cluster centers are interpretable (they’re real data points)

Example use case:

  • Clustering customers: The medoid is a “typical” customer
  • You can examine this customer directly
  • With K-Means, the center might not represent any real customer

How It Works

K-Medoids clusters data into k groups using medoids (actual data points) as cluster centers. It minimizes the sum of dissimilarities between points and their assigned medoids.

Algorithm (PAM):

  1. Initialize k medoids (randomly or using BUILD)
  2. Assign each point to nearest medoid
  3. For each (medoid, non-medoid) pair:
  • Compute cost of swapping them
  • If cost decreases, perform swap
  1. Repeat until no improvement

Example

using AiDotNet;
using AiDotNet.Data.Loaders;
using AiDotNet.Clustering.Partitioning;
using AiDotNet.Tensors.LinearAlgebra;

var data = new Matrix<double>(6, 2);
double[][] rows = { new[] { 1.0, 1.0 }, new[] { 1.2, 0.9 }, new[] { 1.1, 1.1 },
                    new[] { 8.0, 8.0 }, new[] { 8.2, 7.9 }, new[] { 7.9, 8.1 } };
for (int i = 0; i < 6; i++) { data[i, 0] = rows[i][0]; data[i, 1] = rows[i][1]; }

var result = await new AiModelBuilder<double, Matrix<double>, Vector<double>>()
    .ConfigureModel(new KMedoids<double>())
    .ConfigureDataLoader(DataLoaders.FromMatrix(data))
    .BuildAsync();

var labels = result.Predict(data);
Console.WriteLine($"KMedoids: clustered {labels.Length} points.");

Constructors

Constructor Summary
KMedoids(KMedoidsOptions<T> options) Initializes a new KMedoids instance.

Properties

Property Summary
int[] MedoidIndices { get; } Gets the indices of medoid points in the original data.

Methods

Method Summary
IFullModel<T, Matrix<T>, Vector<T>> WithParameters(Vector<T> parameters)
Matrix<T> GetMedoids(Matrix<T> originalData) Gets the medoid points as a matrix.
ModelOptions GetOptions()
Vector<T> FitPredict(Matrix<T> x)
Vector<T> Predict(Matrix<T> x)
void Train(Matrix<T> x, Vector<T> y)