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]);

Tuesday 2 February 2016

Implement perceptron for AND function using bipolar inputs

%Code

clc
clear all;
close all;

x1=[-1 -1 1 1];
x2=[-1 1 -1 1];
t=[-1 -1 -1 1];
alpha=input('Enter the value of alpha=');
th=input('enter the threshold=');
yin=zeros(1,4);
y=zeros(1,4);
w1=0;
w2=0;
b=0;
c=1;
cnt=0;
while(c)
    c=0
    for i=1:4
        %yin(i)=b+(x(i,1)*w1)+(x(i,2)*w2);
       yin(i)=b+(x1(i)*w1)+(x2(i)*w2);
        if yin(i)>th
            y(i)=1;
        else if yin(i)<-th
                y(i)=-1;
            else
                y(i)=0;
            end
            if t(i)~=y(i)
                w1=w1+(alpha*x1(i)*t(i));
                w2=w2+(alpha*x2(i)*t(i));
                b=b+(alpha*t(i));
                c=1;
            else
                w1=w1;
                w2=w2;
                b=b;
            end
        end
        cnt=cnt+1;
    end
    disp('OUTPUT MATRIX:');
    disp(y);
    disp('w1=');
    disp(w1);
    disp('w2=');
    disp(w2);
    disp('bias=');
    disp(b);
    a1=x1;
    a2=x2;
    a2=(-w1/w2)*a1-(b/w2);
    plot(x1,x2,'*r',a1,a2);
    axis([-2 2 -2 2]);
end