Advertisement
Jeren

Untitled

Nov 20th, 2012
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.92 KB | None | 0 0
  1. function [F, Q, R, x_T, P_T] = em_algo(y, G)
  2.     % y_t = G_t'*x_t + v_t    1*1 = 1*p p*1
  3.     % x_t = F*x_t-1 + w_t     p*1 = p*p p*1
  4.     % G is T*p
  5.     p = size(G,2); % p = nb assets ; G = T*p
  6.     q = size(y,2); % q = nb observations ; y = T*q
  7.     T = size(y,1); % y is T*1
  8.     F = eye(p); % = Transition matrix  p*p
  9.     Q = eye(p); % innovation (v) covariance matrix p*p
  10.     R = eye(q); % noise (w) covariance matrix q x q
  11.     x_T_old = zeros(p,T);
  12.     mu0 = zeros(p,1);
  13.     Sigma = eye(p); % Initial state covariance matrix p*p
  14.     converged = 0;
  15.     i = 0;
  16.     max_iter = 60; % only for testing purposes
  17.     while ~converged
  18.         if i > max_iter
  19.             break;
  20.         end
  21.         % E step = smoothing
  22.         fprintf('Iteration %d\n',i);
  23.         [x_T,P_T,P_Tm2] = smoother(G,F,Q,R,mu0,Sigma,y);
  24.         %x_T
  25.        
  26.         % M step
  27.         A = zeros(p,p);
  28.         B = zeros(p,p);
  29.         C = zeros(p,p);
  30.         R = eye(q);
  31.        
  32.         for t = 2:T % eq (9) in EM paper
  33.             A = A + (P_T(:,:,t-1) + (x_T(:,t-1)*x_T(:,t-1)'));
  34.         end
  35.        
  36.         for t = 2:T % eq (10)
  37.             %B = B + (P_Tm2(:,:,t-1) + (x_T(:,t)*x_T(:,t-1)'));
  38.             B = B + (P_Tm2(:,:,t) + (x_T(:,t)*x_T(:,t-1)'));
  39.         end
  40.        
  41.         for t = 1:T %eq (11)
  42.             C = C + (P_T(:,:,t) + (x_T(:,t)*x_T(:,t)'));
  43.         end    
  44.        
  45.         F = B*inv(A); %eq (12)
  46.         Q = (1/T)*(C - (B*inv(A)*B')); % eq (13)  pxp
  47.        
  48.         for t = 1:T
  49.             bias = y(t) - (G(t,:)*x_T(:,t));
  50.             R = R + ((bias*bias') + (G(t,:)*P_T(:,:,t)*G(t,:)'));
  51.         end
  52.         R = (1/T)*R;
  53.        
  54.         if i>1            
  55.             err = norm(x_T-x_T_old)/norm(x_T_old);
  56.             if err < 1e-4
  57.                 converged = 1;
  58.             end            
  59.         end  
  60.         x_T_old = x_T;
  61.         i = i+1;
  62.     end
  63.     fprintf('EM algorithm iterated %d times\n',i);
  64. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement