Advertisement
Guest User

gmmROKI

a guest
Jul 20th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.53 KB | None | 0 0
  1. %% Load data
  2. clc;
  3. clearvars;
  4. close all;
  5. load('dataGMM.mat');
  6. %% Preprocess data
  7. m = size(Data,2);
  8. n = size(Data,1);
  9. PIfunc = @(idx, c) length(idx(idx==c))/length(idx);
  10. % meanfunc = @(x,n,theta) 1;
  11. covfunc = @(x,mean) ((x-mean')*(x-mean')')/(length(x)-1);
  12. covfuncMATLAB = @(x,mean) cov((x-mean')');
  13. GaussDist = @(x,meanfunc,covfunc) 1;
  14. loglklhd = @(PI,Mu,SIGMA) 1;
  15.  
  16. % plot data
  17. X = Data;
  18. figure(1);
  19. plot(X(1,:),X(2,:),'k*','MarkerSize',5); hold on;
  20. title 'Data';
  21. xlabel 'X1';
  22. ylabel 'X2';
  23. K = 4; % num of clusters
  24. %% Init parameters
  25. [idx, MU] = kmeans(X', K);
  26. % calc PI
  27. PI =  zeros(K,1);
  28. for c=1:K
  29.     PI(c) = PIfunc(idx,c);
  30. end
  31. SIGMA = zeros(2,2,4);
  32. for i=1:K
  33. %     SIGMA(:,:,i) = covfuncMATLAB(X(idx==i),MU(i,:))
  34.     SIGMA(:,:,i) = cov((X(:,idx==i))');
  35. end
  36.  
  37. %%
  38. %Evaluate the pdf of the normal distribution at the grid points.
  39. for k=1:K
  40.     mu = MU(k,:);
  41.     sigma = SIGMA(:,:,k);
  42.     % Create a grid of 100x100 evenly spaced points in two-dimensional space.
  43.     dim_grid = 100;
  44.     x1 = linspace(-0.1,0.1,dim_grid);
  45.     x2 = linspace(-0.1,0.1,dim_grid);
  46.     [X1,X2] = meshgrid(x1',x2'); % grid 100x100
  47.     X = [X1(:) X2(:)];
  48.     % Evaluate the cdf of the normal distribution at the grid points.
  49.     p = PI(k)*mvnpdf(X,mu,sigma);
  50.     % Plot the cdf values.
  51.     Z = reshape(p,dim_grid,dim_grid);
  52.     figure(2);
  53.     surf(X1,X2,Z);
  54.     caxis([min(Z(:))-0.5*range(Z(:)),max(Z(:))]); hold on;
  55.     scatter(mu(1), mu(2),50,'r'); hold on;
  56. end
  57. view(0,90);
  58. xlabel('x1')
  59. ylabel('x2')
  60. zlabel('Probability Density');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement