% learncl1.m: competitive learning example with clustering % with annimation % copyright (c) 1996-2000 by Yu Hen Hu % created: 9/3/96 % last modified: 2/3/2000 % % mfiles needed: datagen1.m % clear all, close all disp('Enter 1 to pause .5 second after each iteration (default), '); pmode=input('Otherwise hit return key for continuous annimation: '); if isempty(pmode), pmode=1; end N=input('# of samples in each cluster (default = 30) = '); if isempty(N), N=30; end N2=N+N; B1=ceil(N/2); B2=N+B1; eta=0.2; means=[.7 -.8 .7 -.8]; var= [0.2 0.2]; x=datagen1([N N],[means;var]); % x is 2N by 2 x=randomize(x); % randomize the ordering of clusters ncenter=input('# of clusters (neurons) to use (Default = 2): '); if isempty(ncenter), ncenter=2; end w=rand(ncenter,2)-0.5*ones(ncenter,2); % both neuron initially at random place figure(1),clf plot(w(:,1),w(:,2),'*',x(:,1),x(:,2),'g.') title('initial') pause(1) disp('competitive learning in action ....'); if isempty(pmode), pmode=0; end i=1; iter=1; converge=0; while converge==0, dn=ones(ncenter,1)*x(i,:)-w; ddn=sum((dn.*dn)')'; % ddn: ncenter by 1 [tmp,istar]=min(ddn); w(istar,:)=w(istar,:)+eta*(x(i,:)-w(istar,:)); plot(w(:,1),w(:,2),'b*',x(:,1),x(:,2),'g.',x(i,1),x(i,2),'ro') drawnow if pmode==1, pause(.5) end i=rem(i+1,N2); iter=iter+1; if i==0, x=randomize(x); % randomize the ordering of clusters i=1; % start with a reordered input end if rem(iter,500)==0, converge=input('Enter return key to continue, 1 to quit! ') if isempty(converge), converge=0; end end end plot(w(:,1),w(:,2),'b*',x(:,1),x(:,2),'g.') title(['at end of ' num2str(iter) ' iterations'])