annotate toolboxes/FullBNT-1.0.7/bnt/examples/static/Misc/mixexp_graddesc.m @ 0:cc4b1211e677 tip

initial commit to HG from Changeset: 646 (e263d8a21543) added further path and more save "camirversion.m"
author Daniel Wolff
date Fri, 19 Aug 2016 13:07:06 +0200
parents
children
rev   line source
Daniel@0 1
Daniel@0 2 %%%%%%%%%%
Daniel@0 3
Daniel@0 4 function [theta, eta] = mixture_of_experts(q, data, num_iter, theta, eta)
Daniel@0 5 % MIXTURE_OF_EXPERTS Fit a piecewise linear regression model using stochastic gradient descent.
Daniel@0 6 % [theta, eta] = mixture_of_experts(q, data, num_iter)
Daniel@0 7 %
Daniel@0 8 % Inputs:
Daniel@0 9 % q = number of pieces (experts)
Daniel@0 10 % data(l,:) = input example l
Daniel@0 11 %
Daniel@0 12 % Outputs:
Daniel@0 13 % theta(i,:) = regression vector for expert i
Daniel@0 14 % eta(i,:) = softmax (gating) params for expert i
Daniel@0 15
Daniel@0 16 [num_cases dim] = size(data);
Daniel@0 17 data = [ones(num_cases,1) data]; % prepend with offset
Daniel@0 18 mu = 0.5; % step size
Daniel@0 19 sigma = 1; % variance of noise
Daniel@0 20
Daniel@0 21 if nargin < 4
Daniel@0 22 theta = 0.1*rand(q, dim);
Daniel@0 23 eta = 0.1*rand(q, dim);
Daniel@0 24 end
Daniel@0 25
Daniel@0 26 for t=1:num_iter
Daniel@0 27 for iter=1:num_cases
Daniel@0 28 x = data(iter, 1:dim);
Daniel@0 29 ystar = data(iter, dim+1); % target
Daniel@0 30 % yhat(i) = E[y | Q=i, x] = prediction of i'th expert
Daniel@0 31 yhat = theta * x';
Daniel@0 32 % gate_prior(i,:) = Pr(Q=i | x)
Daniel@0 33 gate_prior = exp(eta * x');
Daniel@0 34 gate_prior = gate_prior / sum(gate_prior);
Daniel@0 35 % lik(i) = Pr(y | Q=i, x)
Daniel@0 36 lik = (1/(sqrt(2*pi)*sigma)) * exp(-(0.5/sigma^2) * ((ystar - yhat) .* (ystar - yhat)));
Daniel@0 37 % gate_posterior(i,:) = Pr(Q=i | x, y)
Daniel@0 38 gate_posterior = gate_prior .* lik;
Daniel@0 39 gate_posterior = gate_posterior / sum(gate_posterior);
Daniel@0 40 % Update
Daniel@0 41 eta = eta + mu*(gate_posterior - gate_prior)*x;
Daniel@0 42 theta = theta + mu*(gate_posterior .* (ystar - yhat))*x;
Daniel@0 43 end
Daniel@0 44
Daniel@0 45 if mod(t,100)==0
Daniel@0 46 fprintf(1, 'iter %d\n', t);
Daniel@0 47 end
Daniel@0 48
Daniel@0 49 end
Daniel@0 50 fprintf(1, '\n');
Daniel@0 51