k-medians clustering technique

4 vues (au cours des 30 derniers jours)
muhammad ismat
muhammad ismat le 13 Mar 2017
please, i want matlab code of k-median clustering technique

Réponses (1)

NVSL
NVSL le 24 Jan 2025
I recently looked into whether there's a function for k-median clustering in MATLAB, or if we could tweak the existing "k-means" or "k-medoids" functions to do the job.
I couldn't find anything ready-made, but I figured out that we can use MATLAB's "median" function to create our own "kMedianClustering" function. Hope this helps!
function [centroids, idx] = kMedianClustering(X, k, maxIter)
% X: data points (n x d matrix)
% k: number of clusters
% maxIter: maximum number of iterations
% Initialize centroids randomly
[n, d] = size(X);
centroids = X(randperm(n, k), :);
idx = zeros(n, 1);
for iter = 1:maxIter
% Assign each point to the nearest centroid
for i = 1:n
distances = sum(abs(X(i, :) - centroids), 2);
[~, idx(i)] = min(distances);
end
% Update centroids
newCentroids = zeros(k, d);
for j = 1:k
clusterPoints = X(idx == j, :);
if ~isempty(clusterPoints)
newCentroids(j, :) = median(clusterPoints, 1);
else
newCentroids(j, :) = centroids(j, :);
end
end
% Check for convergence
if all(newCentroids == centroids)
break;
end
centroids = newCentroids;
end
end
% randomly generated data
data = [randn(50, 2) + 1; randn(50, 2) - 1];
% Number of clusters
k = 2;
% Maximum number of iterations
maxIter = 100;
% Perform k-median clustering
[centroids, idx] = kMedianClustering(data, k, maxIter);
% Plot the results
figure;
hold on;
colors = ['r', 'g', 'b'];
for i = 1:k
scatter(data(idx == i, 1), data(idx == i, 2), 36, colors(i), 'filled');
end
scatter(centroids(:, 1), centroids(:, 2), 100, 'kx', 'LineWidth', 3);
hold off;
title('K-Median Clustering');
  1 commentaire
Federico Maddanu
Federico Maddanu le 14 Mar 2025
I think (but I m not sure) kmeans does this when you select 'cityblock' as distance!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Cluster Analysis and Anomaly Detection dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by