www.pudn.com > DHMM_MATLAB.rar > DHMM_Train.m


%	by lkk@mails.tsinghua.edu.cn 
 
function [A,B] = DHMM_Train(characters_classify,divid_line,sort_number) 
%	输入: 
%		characters_classify			1行7486列矩阵,每一列记录特征所属于的类 
%		divid_line					1行 101列矩阵,每一列记录7486列的划分 
%       sort_number                 聚类个数,实验中选择为64     
%	输出: 
%       A B                  10个数字声音模型参数 
% 
 
%	初始化 
 
warnings=warning('OFF','MATLAB:LOG:LOGOFZERO'); 
y = cell(10); 
 
for i=0:9 
 	for j = 1:10 
 
	index_start = divid_line(i*10+j)+1; 
	index_end		= divid_line(i*10+j+1); 
	y{i+1,j} = characters_classify(index_start:index_end); 
	end 
end 
 
a = log([1;0;0;0;0]); 
A = cell(1,10); 
B = cell(1,10); 
 
 
alpha = cell(1,10); 
beta =  cell(1,10); 
NQ = zeros(1,10); 
 
 
 
for i=0:9 
	%init A B 
	A{i+1} = log(diag(ones(1,5)*0.5) + diag(ones(1,4)*0.5,1)); 
	A{i+1}(end,end) = -Inf; 
	B{i+1} = log([ones(4,sort_number)*(1/sort_number);zeros(1,sort_number)]); 
	for s=1:10 
		fprintf('	i=%d  s=%d  \n',i,s); 
		 
		%init alpha(10) beta(10) 
		for j=1:10 
			N = length(y{i+1,j}); 
	 
			L = 4; 
			% 初始化 alpha beta 
			alpha{j} = repmat(-Inf,5,N); 
			beta{j}  = repmat(-Inf,5,N); 
			% init alpha{j}(1,1), beta{j}(:,N) 
			alpha{j}(:,1) = B{i+1}(:,y{i+1,j}(1)) + a; 
			 beta{j}(:,N) = log(1); 
			% calc alpha(j) 2->N; beta(j) N-1 -> 1; 
			for n=2:N 
				for jj=1:5 
					temp = 0; 
					for ii=1:L 
						temp = temp + exp(alpha{j}(ii,n-1) + A{i+1}(ii,jj) + B{i+1}(jj,y{i+1,j}(n))); 
					end 
					alpha{j}(jj,n) = log(temp); 
				end 
			end % n 
			for n=(N-1):-1:1 
				for jj=1:5 
					temp = 0; 
					for ii=1:L 
						temp = temp + exp(beta{j}(ii,n+1) + A{i+1}(jj,ii) + B{i+1}(ii,y{i+1,j}(n+1))); 
					end 
					beta{j}(jj,n) = log(temp); 
				end 
			end % n	 
					 
		end	% for j 
			 
		% re-estimate A -> newA B->newB; newA->A, newB -> B 
		%	A_numerator A的分子 
				 
	newA=A{i+1}; 
		 
		for ii=1:L 
			for jj=1:L 
				if(A{i+1}(ii,jj)==-Inf||A{i+1}(ii,jj)==0) 
					continue; 
				end 
				 
				% A(ii,jj)的分子 
				temp = 0; 
				temp1 =0; 
				for q=1:10 
 
					for n=2:length(y{i+1,q}) 
						temp = temp + exp(alpha{q}(ii,n-1) + A{i+1}(ii,jj) + beta{q}(jj,n) + B{i+1}(jj,y{i+1,q}(n))); 
						for l=1:L 
							temp1 = temp1 + exp(alpha{q}(ii,n-1) + A{i+1}(ii,l) + beta{q}(l,n) + B{i+1}(l,y{i+1,q}(n))); 
						end 
					end 
				end 
				newA(ii,jj) = log(temp) - log(temp1); 
				 
			end 
		end % ii 
 
newB=B{i+1}; 
 
		for jj=1:L 
			for m=1:sort_number 
				% B(jj,m) 
				temp = 0; 
				temp1 = 0; 
				for q=1:10 
					Q=exp(alpha{q}(jj,:) + beta{q}(jj,:)); 
					temp =temp + sum(Q(find(y{i+1,q} == m))); 
					temp1 = temp1 + sum(Q); 
					 
				end 
		 
				newB(jj,m) = log(temp) -log(temp1); 
							 
			end 
		end % jj 
		 
 
		 
		A{i+1} = newA; 
		B{i+1} = newB; 
%		tmp = input('input ','s'); 
		 
	end	%	for s 
	% save A,B 
end	% for i 
 
warning(warnings);