diff --git a/CLPBN/learning/learn_utils.yap b/CLPBN/learning/learn_utils.yap new file mode 100644 index 000000000..2ea6c94f1 --- /dev/null +++ b/CLPBN/learning/learn_utils.yap @@ -0,0 +1,35 @@ +% +% Utilities for learning +% + +:- module(bnt_learn_utils, [run_all/1, + clpbn_vars/2]). + +run_all([]). +run_all([G|Gs]) :- + call(user:G), + run_all(Gs). + +clpbn_vars(Vs,BVars) :- + get_clpbn_vars(Vs,CVs), + keysort(CVs,KVs), + merge_vars(KVs,BVars). + +get_clpbn_vars([],[]). +get_clpbn_vars([V|GVars],[K-V|CLPBNGVars]) :- + clpbn:get_atts(V, [key(K)]), !, + get_clpbn_vars(GVars,CLPBNGVars). +get_clpbn_vars([_|GVars],CLPBNGVars) :- + get_clpbn_vars(GVars,CLPBNGVars). + +merge_vars([],[]). +merge_vars([K-V|KVs],[V|BVars]) :- + get_var_has_same_key(KVs,K,V,KVs0), + merge_vars(KVs0,BVars). + +get_var_has_same_key([K-V|KVs],K,V,KVs0) :- !, + get_var_has_same_key(KVs,K,V,KVs0). +get_var_has_same_key(KVs,_,_,KVs). + + + diff --git a/CLPBN/learning/mle.yap b/CLPBN/learning/mle.yap new file mode 100644 index 000000000..d134c7d28 --- /dev/null +++ b/CLPBN/learning/mle.yap @@ -0,0 +1,42 @@ +% +% This assumes we have a single big example. +% + +:- use_module(library('clpbn_learning/utils'), + [run_all/1, + clpbn_vars/2]). + +:- module(bnt_mle, [learn_parameters/2]). + +% +% full evidence learning +% +learn_parameters(Items, Tables, Extras) :- + run_all(Items), + attributes:all_attvars(AVars), + % sort and incorporte evidence + clpbn_vars(AVars, AllVars), + mk_sample(AllVars, Sample), + compute_tables(Extras, Sample, Tables). + +mk_sample(AllVars, NVars, LL) :- + add2sample(AllVars, Sample), + msort(Sample, AddL), + compute_params(AddL, Parms). + +add2sample([], []). +add2sample([V|Vs],[val(Id,[Ev|EParents])|Vals]) :- + clpbn:get_atts(V, [evidence(Ev),dist(Id,Parents)]), + get_eparents(Parents, EParents), + add2sample(Vs, Vals). + +get_eparents([P|Parents], [E|EParents]) :- + clpbn:get_atts(V, [evidence(Ev)]), + get_eparents(Parents, EParents). +get_eparents([], []). + + +compute_tables([], Sample, Tables) :- + mle(Sample, Tables). +compute_tables([laplace|_], Sample, Tables) :- + laplace(Sample, Tables).