/*
* LearnCPTs.c
*
* Example use of Netica-C-API for learning the CPTs of a Bayes net
* from a file of cases.
*/
#include "Netica.h"
#include "NeticaEx.c"
#define CHKERR {if (GetError_ns (env, ERROR_ERR, NULL)) goto error;}
environ_ns* env;
int main (void){
net_bn *orig_net, *learned_net;
const nodelist_bn* orig_nodes;
nodelist_bn* learned_nodes;
caseposn_bn case_posn;
int numnodes;
stream_ns* casefile;
char mesg[MESG_LEN_ns];
int nn, res;
env = NewNeticaEnviron_ns (NULL, NULL, NULL);
res = InitNetica2_bn (env, mesg);
printf ("%s\n", mesg);
if (res < 0) exit (-1);
/* Read in the net created by the BuildNet.c example program */
orig_net = ReadNet_bn ( NewStreamFile_ns ("AsiaEx.dne", env, NULL),
NO_VISUAL_INFO);
orig_nodes = GetNetNodes_bn (orig_net);
SetNetAutoUpdate_bn (orig_net, 0);
CHKERR
learned_net = NewNet_bn ("Learned_Asia", env);
learned_nodes = DuplicateNodes_bn (orig_nodes, learned_net);
numnodes = LengthNodeList_bn (learned_nodes);
/* Remove CPTables of nodes in learned_net, so new ones can be learned.*/
for (nn = 0; nn < numnodes; ++nn)
DeleteNodeRelation_bn (NthNode_bn (learned_nodes, nn));
CHKERR
/* Read in the case file created by the the SimulateCases.c
example program, and learn new CPTables. */
casefile = NewStreamFile_ns ("AsiaEx.cas", env, NULL);
ReviseCPTsByCaseFile_bn (casefile, learned_nodes, 0, 1.0);
WriteNet_bn (learned_net, NewStreamFile_ns ("Learned_AsiaEx.dnet",
env, NULL));
CHKERR
end:
FreeNodeList_bn (learned_nodes);
FreeNet_bn (orig_net);
FreeNet_bn (learned_net);
res= CloseNetica_bn (env, mesg);
printf ("%s\n", mesg);
return (res < 0 ? -1 : 0);
error:
fprintf (stderr, "LearnCPTs: Error in %s\n",
ErrorMessage_ns (GetError_ns (env, ERROR_ERR, NULL)));
goto end;
}
/* ==============================================================
* This alternate way can replace the ReviseCPTsByCaseFile_bn
* line above, if you need to filter or adjust individual cases.
case_posn = FIRST_CASE;
while(1){
RetractNetFindings_bn (learned_net);
ReadCase_bn (&case_posn, casefile, learned_nodes, NULL, NULL);
if (case_posn == NO_MORE_CASES) break;
ReviseCPTsByFindings_bn (learned_nodes, 0, 1.0);
case_posn = NEXT_CASE;
CHKERR
}
============================================================== */
|