%clear all;clc;
trai_pairs=30; % 48 samples
out_neurons=5; % no of words
hid_neurons=6; %matka
in_nodes=13; %features are 13
eata=0.1;emax=0.001;q=1;e=0;lamda=.7;  t=1;


load speechp.mat S

p1=max(max(S));
s=S/p1;

% for i=1:40:80
%     zzz(t:t+19,:)=zz(i:i+19,:);
%     t=t+20;
%     
% end

Z= double(s);
% d1=[1 -1 -1];
% d2=[-1 1 -1];
% d3=[-1 -1 1];

dummy=[1 -1 -1 -1 -1;
   -1 1 -1 -1 -1;
   -1 -1 1 -1 -1;
   -1 -1 -1 1 -1;
   -1 -1 -1 -1 1];
   

% dummy=[1 -1 -1 -1 -1 -1 -1;
%    -1 1 -1 -1 -1 -1 -1;
%    -1 -1 1 -1 -1 -1 -1;
%    -1 -1 -1 1 -1 -1 -1;
%    -1 -1 -1 -1 1 -1 -1;
%    -1 -1 -1 -1 -1 1 -1;
%    -1 -1 -1 -1 -1 -1 1];
t=trai_pairs/out_neurons;
D=dummy;
for i= 1:1:5
    D=cat(1,D,dummy);
end
%D=[d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3;d1;d2;d3]; %d will be a 15 X 3 matrix

%step 1 initialisation of weight matrices

W=randn(out_neurons,hid_neurons);
V=randn(hid_neurons,in_nodes);
for main_loop=1:3000

% step 2 training step starts here compute layer responses

for p=1:trai_pairs
    z=transpose(Z(p,:));
  d=transpose(D(p,:));

   %calculate output of hidden and output layer

   y=(tansig(V*(z)));
   o=(tansig(W*(y))); 

% step 3 Error value is computed

        e=0.5*norm(d-o)^2+e;

% step 4 error signal vectors of both layers are computed
                 
                 % error signal vector for output layer
              
                 for k=1:out_neurons
                       delta_ok(k,:)=0.5*(d(k)-o(k))*(1-o(k)^2);
                 end

                 %error signal vector for hidden layer

                 for j=1:hid_neurons
                        sum=0;
                 for k=1:out_neurons
                 sum=sum+delta_ok(k)*W(k,j);
                 end
                 delta_yj(j,:)=0.5*(1-y(j)^2)*sum;
                 end

% step 5 Adjust weights of output and hidden layer

     W=W+eata*delta_ok*transpose(y);
     V=V+eata*delta_yj*transpose(z);
     q=q+1;                           % update step counter
 end

% step 6 training cycle is completed

fprintf('error=%f no of epcohes = %d \n',e,main_loop);
            if e>=emax
               e=0;
            else
               save backp20_2.mat W V Z;
                   break;
            end
                  
end 
save backp.mat W V Z;