% function OptBetaLogPost   2005/2/23
%
% ytrue:n x 1 教師ラベル，post: gg x n 事後確率, expF: n x gg 重み行列
% beta，最適な beta  f:n x gg weak classifier
%
% expFnew: n x gg 更新された各点の重み

function  [beta, expFnew] = OptBetaLogPos(ytrue, f, expF);

[n gg] = size(expF); expFnew = zeros(n, gg);      % expF(i,k) = exp(F(i,k))
f = f'; f2 = f .* f;

% 正判別の f の値の合計
num1 = 0; for i = 1:n; num1 = num1 + f(i, ytrue(i)); end

% 判別方式 F + beta f の信頼度 beta を逐次的に計算
beta = 0; delta = 1; p = zeros(n, gg);
while abs(delta) > 10^(-8)
 expbf = exp(beta*f); expFc = expF .* expbf;
 for i = 1:n
  p(i, :) = expFc(i, :) ./ sum( expFc(i, :) );    % p(i,k): 事後確率
 end % i
 tmp   = f  .* p;
 num2  = sum( sum( tmp ) );
 den1  = sum( sum( f2 .* p) );
 den2  = sum( (sum(tmp')) .^ 2 );
 delta = (num1 - num2)/(den1 - den2); beta = beta + delta;
 fprintf('RealOptLogPost: beta = %f, delta = %f\n', beta, delta)
end

expFnew = p;                  % 更新した事後確率を返す
