-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEM_algorithm.m
executable file
·77 lines (54 loc) · 1.46 KB
/
EM_algorithm.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
function [w,m,S,kvec] = EM_algorithm(x,K,MaxIter)
%%%%%Initialization%%%%%%%
wInit=zeros(K,1);
meanInit=zeros(K,3);
covInit=zeros(3,3,K);
kvec=randi(K,size(x,1),1);
for i=1:K
wInit(i)=numel(kvec==i)/numel(kvec);
meanInit(i,:)=mean(x(kvec==i,:));
covInit(:,:,i)=cov(x(kvec==i,:))+eye(3)*(1e-6);
end
iter=0;
M=size(x,1);
r=zeros(M,K);
%%%%%%%%%% EM iterations%%%%%%%%%%%%%%
w=wInit;
m=meanInit;
S=covInit;
temp=zeros(M,K);
temp2=zeros(M,K);
for k=1:K
temp(:,k)=w(k).*mvnpdf(x,m(k,:),S(:,:,k));
end
L=sum(log(sum(temp,2)));
for j=1:MaxIter
iter=iter+1;
Lprev=L;
%%%%%%%%%%%% E-step %%%%%%%%%%%%
for k=1:K
r(:,k)=w(k).*mvnpdf(x,m(k,:),S(:,:,k));
end
r=r./repmat(sum(r,2),[1 K]);
%%%%%%%%%%%%% M-step %%%%%%%%%%%%%
for i=1:K
w(i)=sum(r(:,i))/sum(sum(r));
m(i,:)=sum(bsxfun(@times,r(:,i),x))/sum(r(:,i));
C=x-repmat(m(i,:),[M 1]);
D=bsxfun(@times,r(:,i),C);
S(:,:,i)=D'*C/sum(r(:,i))+eye(size(x,2))*(1e-6);
end
%%%%%%% Calculation of Log Likelihood and Lower Bound
for k=1:K
temp(:,k)=w(k).*mvnpdf(x,m(k,:),S(:,:,k));
temp2(:,k)= r(:,k).*log(w(k).*mvnpdf(x,m(k,:),S(:,:,k))./r(:,k));
end
L=sum(log(sum(temp,2)));
B=sum(sum(temp2,2));
% fprintf('Iteration:%d L:%f B:%f\n',iter,L,B);
if(abs(L-Lprev) <= 1e-4)
break;
end
end
%fprintf('Number of EM iterations : %d\n',iter);
[~,kvec]=max(r,[],2);