COPKMeans<T>

Models & Types · AiDotNet.Clustering.SemiSupervised

COP-KMeans (Constrained K-Means) implementation with must-link and cannot-link constraints.

Inheritance: ClusteringBase<T> → COPKMeans<T>

For Beginners

This is K-Means with rules about what can/cannot be together.

Think of seating people at wedding tables:

  • Some couples must sit together (must-link)
  • Some feuding relatives must be separated (cannot-link)

COP-KMeans finds the best clustering that respects ALL constraints. If constraints are contradictory, the algorithm will fail.

Use cases:

  • User feedback: “These items are the same”
  • Domain knowledge: “These categories are mutually exclusive”
  • Data linkage: “These records refer to the same entity”

How It Works

COP-KMeans extends K-Means by enforcing pairwise constraints:

  • Must-link: Specified pairs must belong to the same cluster
  • Cannot-link: Specified pairs must belong to different clusters

Algorithm:

  1. Initialize cluster centers
  2. Assign points to nearest cluster that doesn’t violate constraints
  3. If no valid assignment exists, return failure
  4. Update centers and repeat until convergence

Example

using AiDotNet;
using AiDotNet.Data.Loaders;
using AiDotNet.Clustering.SemiSupervised;
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 COPKMeans<double>())
    .ConfigureDataLoader(DataLoaders.FromMatrix(data))
    .BuildAsync();

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

Constructors

Constructor Summary
COPKMeans(COPKMeansOptions<T> options) Initializes a new COP-KMeans instance.

Properties

Property Summary
bool ConstraintsSatisfied { get; set; } Gets whether all constraints were satisfied.
int ConstraintViolations { get; set; } Gets the number of constraint violations (if any).

Methods

Method Summary
IFullModel<T, Matrix<T>, Vector<T>> WithParameters(Vector<T> parameters)
ModelOptions GetOptions()
Vector<T> FitPredict(Matrix<T> x)
Vector<T> Predict(Matrix<T> x)
void Train(Matrix<T> x, Vector<T> y)