Variational Inference入门:Mean field for the Ising model

Variational Inference是个比较难的方法,需要一步步认真学习并练习。


先从最简单的开始,Mean field for the Ising model是MLaPP中21.3.2节中的一个范例。回头来看,完成这个范例非常简单,就是一个公式(21.52)。但是,更重要的是理解这个公式的推导过程原理,并不容易。


还是老规矩,本文直接给代码和结果,原理请看MLaPP第21章。代码参考了MLaPP一书给出的范例程序,但做了大大的简化。


处理结果:



这个B是我装的在windows图画里画的,确实丑了点。运行此处的程序,需要先生成一个名为"LetterB.bmp"、分辨率为128*128的图片文件,和程序放在同一个目录下。


还是Matlab代码,有问题随时联系。


close all; clear all; rng(0);

%% Mean field method for Ising model
% chapter 21.3.2 in MLaPP
% by forseerwang, http://blog.csdn.net/foreseerwang
% QQ: 50834
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Image generation
a=double(imread('LetterB.bmp'))*2-1;
figure(1); subplot(2,2,1);
imagesc(a);
colorbar;
title('original image', 'fontsize', 20);
axis('square');
colormap gray;
axis off;

% add noise
sigma  = 2; % noise level
y = a + sigma*randn(size(a)); %y = noisy signal
figure(1); subplot(2,2,2);
imagesc(y);
colorbar;
title('noisy image', 'fontsize', 20);
axis('square');
colormap gray;
axis off;

%%
% 迭代参数
lambda = 0.8;
maxIter = 10;

% 函数初始化
% log(normpdf())与MLaPP示例程序中的gaussLogprob()函数等价
Lp = log(normpdf(y(:), 1, sigma)); 
Lm = log(normpdf(y(:), -1, sigma));
logodds = Lp - Lm;
mu = tanh(logodds); 

[M,N] = size(y);
for iter = 1:maxIter
    for ii = 1:N,
        for jj = 1:M,
            pos = jj + M*(ii-1);
            nbr = pos + [-1,1,-M,M];
            nbr(([jj==1,jj==M,ii==1,ii==N])) = [];
            Sbar = sum(mu(nbr));    
            % MLaPP中的公式(21.52)
            mu(pos) = (1-lambda)*mu(pos) + lambda*tanh(Sbar + 0.5*logodds(pos));
        end;
    end;
    
    if iter == round(maxIter/2),
        mu_tmp=reshape(mu,M,N);
        figure(1); subplot(2,2,3);
        imagesc(mu_tmp);
        colorbar;
        title(sprintf('image after %d iter', iter), 'fontsize', 20);
        axis('square');
        colormap gray;
        axis off;
    end;

end;

mu=reshape(mu,M,N);

figure(1); subplot(2,2,4);
imagesc(mu);
colorbar;
title(sprintf('image after %d iter', maxIter), 'fontsize', 20);
axis('square');
colormap gray;
axis off;



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值