-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathsample_hmm.m
61 lines (54 loc) · 1.64 KB
/
sample_hmm.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
function [samples state_seq] = sample_hmm(hmm)
% [samples state_seq] = sample_hmm(hmm)
%
% Generate a random sample from the given HMM.
%
% 2008-06-04 [email protected]
% Copyright (C) 2008 Ron J. Weiss
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
sp_pdf = exp(hmm.start_prob);
sp_cdf = cumsum(sp_pdf);
trans_pdf = exp([hmm.transmat hmm.end_prob']);
trans_cdf = cumsum(trans_pdf, 2);
% Initial state
p = rand(1);
s = min(find(sp_cdf >= p));
state_seq = s;
samples = sample_from_state(hmm, s);
i = 1;
while true
% Select next component or exit.
p = rand(1);
os = s;
s = min(find(trans_cdf(os,:) >= p));
if isempty(s)
s = length(trans_cdf(os,:));
end
if s > hmm.nstates
break
else
i = i + 1;
samples(:,i) = sample_from_state(hmm, s);
state_seq(i) = s;
end
end
function y = sample_from_state(hmm, s)
if strcmp(hmm.emission_type, 'GMM')
y = sample_gmm(hmm.gmms(s), 1);
elseif strcmp(hmm.emission_type, 'gaussian')
y = sample_gaussian(hmm.means(:,s), hmm.covars(:,s));
else
error(['Invalid HMM emission type: ' hmm.emission_type]);
end