上传者: xuelei163
|
上传时间: 2021-09-13 16:02:21
|
文件大小: 2KB
|
文件类型: M
贝叶斯网络的K2结构学习
clear
N = 4;
dag = zeros(N,N);
%C = 1; S = 2; R = 3; W = 4; % topological order
C = 4; S = 2; R = 3; W = 1; % arbitrary order
dag(C,[R S]) = 1;
dag(R,W) = 1;
dag(S,W)=1;
false = 1; true = 2;
ns = 2*ones(1,N); % binary nodes
bnet = mk_bnet(dag, ns);
bnet.CPD{C} = tabular_CPD(bnet, C, 'CPT', [0.5 0.5]);
bnet.CPD{R} = tabular_CPD(bnet, R, 'CPT', [0.8 0.2 0.2 0.8]);
bnet.CPD{S} = tabular_CPD(bnet, S, 'CPT', [0.5 0.9 0.5 0.1]);
bnet.CPD{W} = tabular_CPD(bnet, W, 'CPT', [1 0.1 0.1 0.01 0 0.9 0.9 0.99]);
[n ncases] = size(data);
% set default params
type = cell(1,n);
params = cell(1,n);
for i=1:n
type{i} = 'tabular';
%params{i} = { 'prior', 1 };
params{i} = { 'prior_type', 'dirichlet', 'dirichlet_weight', 1 };
end
scoring_fn = 'bayesian';
discrete = 1:n;
clamped = zeros(n, ncases);
max_fan_in = n;
verbose = 0;
dag = zeros(n,n);
for i=1:n
ps = [];
j = order(i);
u = find(clamped(j,:)==0);
score = score_family(j, ps, type{j}, scoring_fn, ns, discrete, data(:,u), params{j});
if verbose, fprintf('\nnode %d, empty score %6.4f\n', j, score), end
done = 0;
while ~done & (length(ps) score
score = best_pscore;
ps = [ps best_p];
if verbose, fprintf('* adding %d to %d, score %6.4f\n', best_p, j, best_pscore),end
else
done = 1;
end
end
if ~isempty(ps) % need this check for matlab 5.2
dag(ps, j) = 1;
end
end