How to color each cluster of Expectation maximization EM for my data which is (5000,2). I chose the number of cluster is 15

조회 수: 6 (최근 30일)
I have dataset (X) composed of (5000,2) I used Expectation maximization for clustering the data into 15 clusters. I got the Probabilities matrix which is composed of (5000,15) as the number of clusters is 15 thean each single input will have 15 probabilities to which cluster it belongs. and the means matrix is (15,2)
I used this code to plot the result where (X) is the input Dataset
plot(X(:,1),X(:,2),'.')
hold on
plot(means(:,1),means(:,2),'rd')
Now How can I color each cluster with different color..
thanks

답변 (1개)

Ayush Aniket
Ayush Aniket 2025년 5월 7일
For plotting each cluster with a unique color, you should plot them individually using scatter function in a loop. Refer the example below where I have used random data to fit a GMM and then plot the clusters with unique colors:
% Generate example data: 5000 points, 3 true clusters
rng(1); % For reproducibility
X = [mvnrnd([2 2], eye(2), 1667);
mvnrnd([7 7], eye(2), 1666);
mvnrnd([2 7], eye(2), 1667)];
% Fit a Gaussian Mixture Model with 3 clusters (use 15 for your case)
numClusters = 3;
gmm = fitgmdist(X, numClusters);
% Get posterior probabilities and means
probabilities = posterior(gmm, X); % (5000,3)
means = gmm.mu; % (3,2)
% Assign each point to the cluster with highest probability
[~, clusterIdx] = max(probabilities, [], 2);
The lines function returns the lines colormap as a three-column array with the same number of rows as the colormap for the current figure.You can read more about the function here: https://www.mathworks.com/help/matlab/ref/lines.html
% Define colors
colors = lines(numClusters);
Now, the clusters are plotted iteratively with unique colors:
% Plot clusters
figure
hold on
for k = 1:numClusters
idx = (clusterIdx == k);
scatter(X(idx,1), X(idx,2), 15, colors(k,:), 'filled');
end
% Plot cluster means
plot(means(:,1), means(:,2), 'rd', 'MarkerSize',10, 'LineWidth',2)
hold off
xlabel('X1');
ylabel('X2');
title('EM Clustering Results');
legend('Clusters','Cluster Centers');

카테고리

Help CenterFile Exchange에서 Statistics and Machine Learning Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by