Monday, 15 February 2016

Kohonen Self organizing feature map MATLAB code

clc;
clear all;
close all;
 
alpha=0.5;
x1=rand(1,100)-0.5;
x2=rand(1,100)-0.5;
x=[x1;x2];
 
w1=rand(1,50)-rand(1,50);
w2=rand(1,50)-rand(1,50);
w=[w1;w2];
 
figure(1);
plot([-0.5 0.5 0.5 -0.5 -0.5],[0.5 0.5 -0.5 -0.5 0.5]);
hold on;
plot(x1,x2,'b.');
axis([-1 1 -1 1]);
 
figure(2);
plot([-0.5 0.5 0.5 -0.5 -0.5],[0.5 0.5 -0.5 -0.5 0.5]);
hold on;
plot(w(1,:),w(2,:),'b.',w(1,:),w(2,:));
axis([-1 1 -1 1]);
hold off;
con=1;
ep=0;
while(con)
    for i=1:100
        for j=1:50
            d(j)=0;
            for k=1:2
                d(j)=d(j)+(w(k,j)-x(k,i))^2;
            end
        end
%         for j=1:50
%             if d(j)==min(d);
%                 J=j;
%             end
%         end
        [val J]=min(d);   
        I=J-1;
        K=J+1;
        
        if(I<1)
            I=50;
        end
        
        if(K>50)
            K=1;
        end
        
        w(:,J)=w(:,J)+alpha*(x(:,i)-w(:,J));
        w(:,I)=w(:,I)+alpha*(x(:,i)-w(:,I));
        w(:,K)=w(:,K)+alpha*(x(:,i)-w(:,K));
    end
    
    alpha=alpha-0.0049;
    ep=ep+1;
    plot([-0.5 0.5 0.5 -0.5 -0.5],[0.5 0.5 -0.5 -0.5 0.5]);
    hold on;
    plot(w(1,:),w(2,:),'b*',w(1,:),w(2,:));
    axis([-1 1 -1 1]);
    pause(0.1);
    hold off;
    if(ep==100)
        con=0;
    end
end
 
figure(3);
plot([-0.5 0.5 0.5 -0.5 -0.5],[0.5 0.5 -0.5 -0.5 0.5]);
hold on;
plot(w(1,:),w(2,:),'b.',w(1,:),w(2,:));
axis([-1 1 -1 1]);

No comments:

Post a Comment