Skip to content

Instantly share code, notes, and snippets.

@idsharif
Last active April 8, 2017 19:47
Show Gist options
  • Save idsharif/d8b4aadbd8a86d4a36921706a52a574c to your computer and use it in GitHub Desktop.
Save idsharif/d8b4aadbd8a86d4a36921706a52a574c to your computer and use it in GitHub Desktop.
PSC
% Author: Sharif Shahadat
% Email: sshahada@uno.edu
% Website: http://sharifshahadat.com
% The following code is inspired by the following paper:
% S.C.M. Cohen ; L.N. de Castro., "Data Clustering with Particle Swarms"
% Evolutionary Computation, 2006. CEC 2006. IEEE Congress on, pp.1792-1798, 16-21 July 2006
% doi: 10.1109/CEC.2006.1688524
% URL: http://ieeexplore.ieee.org/document/1688524/
clc; clear; close;
%% Initialization
data_set=[unifrnd(0, 1, [2, 100]), unifrnd(3, 4, [2, 100])]';
max_it=150;
vmax=0.01;
n_particles=3;
w=0.95;
n_cluster_per_particle=3;
global Y
phi1=0; % 1.1;
phi2=0; % 0.8;
phi3=0.005; % 0.3;
phi4=0.06;
Y = [data_set(:,1)/max(data_set(:,1)) data_set(:,2)/max(data_set(:,2))];
N=max(size(data_set));
x=rand(n_cluster_per_particle*n_particles,2); % usually every particle xi initialized at random
c = reshape(x,1, []);
v=vmax*(2*rand(n_particles*n_cluster_per_particle,2)-1); % at random, vi in [-vmax,vmax]
distYX=linspace(1e99,1e99,n_part);
pI=[0 0];
pG=[0 0];
win_counter=zeros(max(size(x)),1);
t=1;
%% Particle Swarm Clustering
while t < max_it
win_counter=zeros(n_particles*n_cluster_per_particle,1);
for i = 1 : N %for each data
for j=1:n_particles*n_cluster_per_particle
distYX(j) = dist(Y(i,:),x(j,:)');
end
distMatrix(:,i)=distYX;
for k=1:n_cluster_per_particle
particle=mat2cell(distMatrix,[3 3 3], N);
end
I = find(distYX==min(distYX));
f= @(x) sum(sum(bsxfun(@minus,Y,x).^2)); % distance function
if f(x(I,:)) < f(pI)
pI = x(I,:);
end
if f(x(I,:)) < f(pG)
pG = x(I,:);
end
v(I,:) = min(vmax, max(-vmax, v(I,:) + phi1*(pI - x(I,:)) + phi2*(pG - x(I,:)) + phi3*(Y(i,:) - x(I,:))));
x(I,:)=x(I,:)+w*v(I,:);
end
w = 0.95*w;
% for plotting
plot(Y(:,1),Y(:,2),'bo'),hold on;
drawnow
plot(x(:,1),x(:,2),'k*'),hold off;
pause(0.1);
t = t + 1;
end
disp(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment