Dan Richter J?rgensen

From ImageWiki

Jump to: navigation, search

Dan Richter J?rgensen
DIKU E-post: danjoe

Opgavebesvarelser


Uge 2

Loesning til opgave 2.41: File:MonsterUge2.pdf

Uge 4

Loesning til 1. matlab opgave: lav fig 3.7

function[post_mean,post_covar] = monster1(numdata)
  alpha = 2;
  beta = 25; %precision (1/noise_spread)^2
  Theta = [];
  [xs,targets] = makedata(numdata);
  
  % Make plots?
  mkfigs = 1;
  
  for i=1:numdata
      % Update posterior mean and covariance
      Theta = [Theta;1,xs(i)]; % eq:(3.16)
      post_covar = inv(alpha*eye(2) + beta*Theta'*Theta); % eq:(3.51)
      post_mean  = beta*post_covar*Theta'*targets(1:i);   % eq:(3.50)
     
     
      if (mkfigs)
          % Plot posterior
          [X,Y,gauss] = TwoD_Gauss(post_mean,post_covar);
          figure(1),contour(X,Y,gauss'),xlabel('a0'),ylabel('a1')
          hold on
          plot(-0.3,0.5,'*r')
          hold off
         
          % Sample from the posterior distribution
          samples = gausssamples(5,post_mean,post_covar)';
          figure(2)
          plot(xs(1:i),targets(1:i),'*'),xlabel('x'),ylabel('t')
          hold on
          % plot lines based on the sampled values of a0 and a1
          for j=1:5
              a0 = samples(j,1);
              a1 = samples(j,2);
              line = [a0+a1*-1, a0+a1*1];
              plot([-1,1],line),axis([-1,1,-1,1])
          end
          hold off
      end
  end
end


function[xs targets ] = makedata(numdata)
% function[ datapoints ] = makedata(numdata)
% Samples 'numdata' 1d datapoints from a line (a0+a1*x) in the interval
% from [-1,1] and adds gaussian noise. 
 a0 = -0.3;
 a1 = 0.5;
 noise_spread = 0.2;
 
 % create x-values from model: y = a0 + a1*x 
 xs = rand(numdata,1);
 xs = (xs-0.5)*2;
 true_datapoints = a0 + a1*xs;
 noise = 0 + noise_spread*randn(numdata,1);
 targets = true_datapoints+noise;
 %figure(1), plot(xs,true_datapoints,'.')
 %figure(2), plot(xs,targets,'.')
end


function[X,Y,gauss] = TwoD_Gauss(me,cv)
% Makes a 2-d gaussian filter with mean 'me' and covariance 'cv'
 normalize = (1/(2*pi)) * sqrt(det(cv));
 X = [-1:0.01:1];
 Y = [1:-0.01:-1];
 for i=1:length(X)
     for j=1:length(Y)
         e(i,j)= exp( -1/2*( ([X(i);Y(j)]-me)'*(inv(cv))*([X(i);Y(j)]-me) ) );
     end
 end
 gauss     = normalize*e;
end


function X=gausssamples(N, m, S)
 % X=gausssamples(N, m, S)
 % Take N samples from a multivariate Gaussian distribution with mean m and
 % covariance matrix S.
 D=length(m);
 [V,E]=eig(S);
 X = sqrt(E) * V * randn(D,N) + repmat(m, 1, N);
end
Personal tools