Centroid Calculation in K-Means
In K-Means clustering, a centroid represents the multi-dimensional geometric center of a cluster. It acts as the minimal-distance point (the representative average) for all data points assigned to that specific cluster.
1. The Mathematical Formulation
Let be a subset of high-dimensional vectors assigned to cluster :
Where each vector lies in a -dimensional real vector space :
The centroid is defined as the coordinate-wise arithmetic mean of these vectors:
For each individual dimension , the coordinate of the centroid is calculated as:
2. A 2D Concrete Example
Let's calculate the centroid for points in a 2D space ():
Step 1: Calculate the Mean of Dimension 1 (-coordinate)
Step 2: Calculate the Mean of Dimension 2 (-coordinate)
Step 3: Define the Centroid Vector
The new centroid is:
3. Interactive Implementation (Python & TS)
Since this is MDX, you can easily import this into your React dashboard or use these code snippets directly in your pipeline.
Python (NumPy)
python
import numpy as np
def calculate_centroid(points: np.ndarray) -> np.ndarray:
"""
Calculates the centroid of a set of D-dimensional points.
:param points: A NumPy array of shape (n, D)
:return: A NumPy array of shape (D,) representing the centroid
"""
return np.mean(points, axis=0)
# Example execution matching our math
points = np.array([[2, 4], [3, 8], [5, 2], [6, 6]])
centroid = calculate_centroid(points)
print(f"Centroid: {centroid}") # Output: [4. 5.]TypeScript
typescript
interface Point {
coordinates: number[];
}
function calculateCentroid(points: Point[]): number[] {
if (points.length === 0) return [];
const numDimensions = points[0].coordinates.length;
const numPoints = points.length;
const centroid = new Array(numDimensions).fill(0);
for (let d = 0; d < numDimensions; d++) {
let sum = 0;
for (let i = 0; i < numPoints; i++) {
sum += points[i].coordinates[d];
}
centroid[d] = sum / numPoints;
}
return centroid;
}
// Example Execution
const pointsList = [
{ coordinates: [2, 4] },
{ coordinates: [3, 8] },
{ coordinates: [5, 2] },
{ coordinates: [6, 6] },
];
console.log(calculateCentroid(pointsList)); // Output: [4, 5]Related reads
- K-Means Clustering: 2D Vector Example — the full algorithm centroids power
- SPFresh — centroids kept fresh incrementally as data changes