samer@11
|
1 function T=sample_transmat_hdp(A0,B0,A1,B1,K,L,T0)
|
samer@0
|
2 % sample_transmat_hdp - Sample 1st order Markov transition matrix using HDP
|
samer@0
|
3 %
|
samer@0
|
4 % sample_transmat_hdp ::
|
samer@0
|
5 % nonneg ~'Shape parameter for base Dirichlet Gamma prior',
|
samer@0
|
6 % nonneg ~'Scale parameter for base Dirichlet Gamma prior',
|
samer@0
|
7 % nonneg ~'Shape parameter for sub Dirichlet Gamma prior',
|
samer@0
|
8 % nonneg ~'Scale parameter for sub Dirichlet Gamma prior',
|
samer@0
|
9 % natural ~'size of alphabet',
|
samer@0
|
10 % natural ~'num of transition matrices to produce',
|
samer@11
|
11 % -> [[K,K,L]] ~ 'lots of transition matrices'.
|
samer@0
|
12 %
|
samer@0
|
13 % An extra optional argument of type [[K,K]] can be added, which
|
samer@0
|
14 % is used as a sort of bias for the sampled matrices.
|
samer@0
|
15
|
samer@0
|
16 if nargin<7, T0=ones(K,K); end
|
samer@0
|
17
|
samer@0
|
18 Alpha0=gamrnd(A0,B0,1,1,L);
|
samer@0
|
19 Alpha1=gamrnd(A1,B1,1,1,L);
|
samer@0
|
20
|
samer@0
|
21
|
samer@0
|
22 % base distributions
|
samer@0
|
23 H0=sample_dir(repmat(Alpha0/K,[K,1,1]));
|
samer@0
|
24 HT=stoch(repmat(H0,[1,K,1])).*repmat(T0/sum(T0(:)),[1,1,L]);
|
samer@0
|
25 T=sample_dir(repmat(Alpha1,[K,K,1]).*HT);
|
samer@0
|
26
|
samer@0
|
27 if any(sum(H0)<0.99)
|
samer@11
|
28 error('normalisation problem in H')
|
samer@0
|
29 end
|
samer@0
|
30 end
|
samer@0
|
31
|
samer@0
|
32 % taken from stats/models/dirichlet.m>stoch_gamma
|
samer@0
|
33 function y=sample_dir(beta)
|
samer@0
|
34 x=randg(beta);
|
samer@0
|
35 z=sum(x,1);
|
samer@0
|
36 y=x./repmat(z,size(x,1),1);
|
samer@0
|
37 bad=find(z==0);
|
samer@0
|
38 for i=1:length(bad)
|
samer@0
|
39 beta_i=beta(:,bad(i)); % misbehaving params
|
samer@0
|
40 k=(beta_i==max(beta_i)); % entries with max beta
|
samer@0
|
41 y(:,bad(i))=mnrnd(1,stoch(k));
|
samer@0
|
42 end
|
samer@0
|
43 end
|
samer@0
|
44
|
samer@0
|
45 function [Y,Z]=stoch(X),
|
samer@0
|
46 Z=sum(X,1);
|
samer@0
|
47 Y=X./repmat(Z,size(X,1),1);
|
samer@0
|
48 end
|
samer@0
|
49
|
samer@0
|
50
|