How to set evidence in a Bayesian Network

77 views
Skip to first unread message

Oleg N

unread,
Mar 5, 2019, 2:53:37 PM3/5/19
to python-weka-wrapper
Hello,
I'm pretty new to using Weka and python, but I'm able to train a BayesNet from an arff file, and use a simlar arff file to get predictions.
I'd like to know how to use the model I trained to be able to set evidence on the class for example, and see which features go up in probability.
What should I read about, or what can I add to my code below?

train_data = converters.load_any_file(data_dir + "1kStemsClasses.arff")
test_data = converters.load_any_file(data_dir + "1kStemsClassesTest.arff")

train_data.class_is_last()
test_data.class_is_last()

# http://git.mrman.de/dataMining/raw/8b3cae92dc714fdd46ad428a37ca76a0196268ab/assignment-question6.ipynb

#cls = Classifier(classname="weka.classifiers.trees.J48", options=["-C", "0.25", "-M", "2"])
cls = Classifier(
    classname="weka.classifiers.bayes.BayesNet",
    options=["-D", "-Q", "weka.classifiers.bayes.net.search.local.K2", "--", "-P", "2", "-S", "BAYES"])



print ("Classifier is: " + cls.classname)


pout = PredictionOutput(classname="weka.classifiers.evaluation.output.prediction.PlainText")
print ("Training...")
evl = Evaluation(train_data)
print("Crossvalidating...")
evl.crossvalidate_model(cls, train_data, 10, Random(1), pout)

print("Evaluation")
print(evl.summary())
print("pctCorrect: " + str(evl.percent_correct))
print("incorrect: " + str(evl.incorrect))



cls.build_classifier(train_data)



Peter Reutemann

unread,
Mar 5, 2019, 3:08:37 PM3/5/19
to python-weka-wrapper
> I'm pretty new to using Weka and python, but I'm able to train a BayesNet from an arff file, and use a simlar arff file to get predictions.
> I'd like to know how to use the model I trained to be able to set evidence on the class for example, and see which features go up in probability.
> What should I read about, or what can I add to my code below?

Unfortunately, I'm not much of a bayesian expert and not sure whether
you can even do it.

Have you looked at retrieving the graph (in XML BIF format)?
http://fracpete.github.io/python-weka-wrapper3/weka.html#weka.classifiers.Classifier.graph

Or, does printing the built model reveal anything?
print(cls)

Cheers, Peter
--
Peter Reutemann
Dept. of Computer Science
University of Waikato, NZ
+64 (7) 858-5174
http://www.cms.waikato.ac.nz/~fracpete/
http://www.data-mining.co.nz/

Oleg N

unread,
Mar 5, 2019, 5:04:44 PM3/5/19
to python-weka-wrapper
It's possible in Java, in this example I found, and the GUI Bayes Net editor, but I'd like to get to a similar place in Python.


I tried printing cls.graph, and it looks like the BIF xml file at the end! :)
Is there a way to load it and get an EditableBayesNet object out of it?
I think that would allow me setEvidence()
I'm just new to using wrappers. Thank you for replying!

Peter Reutemann

unread,
Mar 5, 2019, 5:12:41 PM3/5/19
to python-weka-wrapper
> It's possible in Java, in this example I found, and the GUI Bayes Net editor, but I'd like to get to a similar place in Python.
>
> http://informationstudent.blog.fc2.com/blog-entry-25.html
>
> I tried printing cls.graph, and it looks like the BIF xml file at the end! :)
> Is there a way to load it and get an EditableBayesNet object out of it?
> I think that would allow me setEvidence()
> I'm just new to using wrappers. Thank you for replying!

Never tried this, but...

You could try instantiating the EditableBayesNet classifier and train
it like you did the BayesNet one.
If that works, you can access the underlying Java object with the
"jwrapper" property:
http://fracpete.github.io/python-weka-wrapper3/weka.core.html#weka.core.classes.JavaObject.jwrapper

Then you should be able to use the setEvidence method directly.

Oleg N

unread,
Mar 5, 2019, 8:04:15 PM3/5/19
to python-weka-wrapper
It failed when I tried to instantiate the EditableBayesNet class instead of the BayesNet one.
Failed to instantiate weka.classifiers.bayes.EditableBayesNet: weka.classifiers.bayes.EditableBayesNet
Do you know if there is a way to convert/copy a BayesNet object to an EditableBayesNet?
Or a way to get an existing .BIF file into an EditableBayesNet if I train in the GUI?

Peter Reutemann

unread,
Mar 5, 2019, 8:31:54 PM3/5/19
to python-weka-wrapper
> It failed when I tried to instantiate the EditableBayesNet class instead of the BayesNet one.
> Failed to instantiate weka.classifiers.bayes.EditableBayesNet: weka.classifiers.bayes.EditableBayesNet
> Do you know if there is a way to convert/copy a BayesNet object to an EditableBayesNet?
> Or a way to get an existing .BIF file into an EditableBayesNet if I train in the GUI?

Sorry, but I'm not familiar with that code at all. You'll have to dive
into the Java code itself and look around the Weka code base where the
EditableBaseNet class is used.

Oleg N

unread,
Mar 11, 2019, 1:54:14 PM3/11/19
to python-weka-wrapper
I got it to work! I was doing it wrong....

cls = Classifier(
classname="weka.classifiers.bayes.net.EditableBayesNet",
options=["-D", "-Q", "weka.classifiers.bayes.net.search.local.K2", "--", "-P", "3", "-S", "BAYES"])

I was using the wrong classname.
Could you show me where an example of the jwrapper is used?

Peter Reutemann

unread,
Mar 11, 2019, 2:46:33 PM3/11/19
to python-weka-wrapper

Cheers, Peter
--
Peter Reutemann
Dept. of Computer Science
University of Waikato, NZ
+64 (7) 858-5174
http://www.cms.waikato.ac.nz/~fracpete/
http://www.data-mining.co.nz/
--
You received this message because you are subscribed to the Google Groups "python-weka-wrapper" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python-weka-wra...@googlegroups.com.
To post to this group, send email to python-we...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python-weka-wrapper/993b6440-9e02-45b1-ba50-f710feb32467%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Oleg N

unread,
Mar 11, 2019, 3:33:30 PM3/11/19
to python-weka-wrapper
Thank you! I was able to get the JRip code to run, but when I try the same thing with EditableBayesNet as a classifier, I get an error.

cls = Classifier(
classname="weka.classifiers.bayes.net.EditableBayesNet",
options=["-D", "-Q", "weka.classifiers.bayes.net.search.local.K2", "--", "-P", "3", "-S", "BAYES"])

print ("Classifier is: " + cls.classname)
cls.build_classifier(train_data)
gd = cls.jwrapper.getDistribution()
print(gd)

TypeError: No matching method found for getDistribution


even though when I evaluate the cls.jwrapper expression, I can see a list of methods in it.
I can evaluate JRip.jwrapper to see it's methods, including getRuleSet(), and it runs fine.

Is there something I'm missing, or would an EditableBayesNet with a jwrapper behave differently from JRip?

To unsubscribe from this group and stop receiving emails from it, send an email to python-weka-wrapper+unsub...@googlegroups.com.

Peter Reutemann

unread,
Mar 11, 2019, 3:42:46 PM3/11/19
to python-weka-wrapper
Thank you! I was able to get the JRip code to run, but when I try the
same thing with EditableBayesNet as a classifier, I get an error.
>
>
> cls = Classifier(
> classname="weka.classifiers.bayes.net.EditableBayesNet",
> options=["-D", "-Q", "weka.classifiers.bayes.net.search.local.K2", "--", "-P", "3", "-S", "BAYES"])
>
> print ("Classifier is: " + cls.classname)
> cls.build_classifier(train_data)
> gd = cls.jwrapper.getDistribution()
> print(gd)
>
>
> TypeError: No matching method found for getDistribution
>
>
> even though when I evaluate the cls.jwrapper expression, I can see a list of methods in it.
> I can evaluate JRip.jwrapper to see it's methods, including getRuleSet(), and it runs fine.
>
> Is there something I'm missing, or would an EditableBayesNet with a jwrapper behave differently from JRip?

You have to check the Javadoc of the relevant class:
http://weka.sourceforge.net/doc.dev/

For example, EditableNaiveBayes has this as documentation:
http://weka.sourceforge.net/doc.dev/weka/classifiers/bayes/net/EditableBayesNet.html

As you can see, the getDistribution method takes an integer as
parameter. You didn't supply one, hence the failure to locate a method
of that name without any parameters.

Oleg N

unread,
Mar 11, 2019, 4:44:09 PM3/11/19
to python-weka-wrapper

I tried that for a different method, but I must've been doing it wrong... but now I'm further:
gn = cls.jwrapper.getNode2('ab')
print(gn)
gd0 = cls.jwrapper.getDistribution(0)
print(gd0)

gn = 0, which I understand, 'ab' is my first attribute.

but gd0 prints: '[[D@325e1871' without the ticks.

How do I look at the distribution matrix for the node?

Peter Reutemann

unread,
Mar 11, 2019, 5:39:28 PM3/11/19
to python-weka-wrapper
> I tried that for a different method, but I must've been doing it wrong... but now I'm further:
>
> gn = cls.jwrapper.getNode2('ab')
> print(gn)
> gd0 = cls.jwrapper.getDistribution(0)
> print(gd0)
>
>
> gn = 0, which I understand, 'ab' is my first attribute.
>
> but gd0 prints: '[[D@325e1871' without the ticks.
>
> How do I look at the distribution matrix for the node?

What you received is a Java 2-dimensional double array.

Lucky for you, you can use the "double_matrix_to_ndarray" method in
the "weka.core.typeconv" module to turn this into a numpy matrix.

Oleg N

unread,
Mar 12, 2019, 12:21:08 PM3/12/19
to python-weka-wrapper
Thank you some more, heh, I am lucky! :D
I've gotten further, I can get some of the methods to work, but I'm doing something wrong with getEvidence(324), setEvidence(324,0) and getMargin(324). They all give me this error:
javabridge.jutil.JavaException: Index 324 out of bounds for length 0
Can you tell me what I'm missing?
I'd like to be able to setEvidence to my class node, and see which attribute nodes become most influential. This is what I have so far:
cls = Classifier(
classname="weka.classifiers.bayes.net.EditableBayesNet",
    options=["-D", "-Q", "weka.classifiers.bayes.net.search.local.K2", "--", "-P", "2", "-S", "BAYES"])


print ("Classifier is: " + cls.classname)
cls.build_classifier(train_data)
#Get CPC node ID
cpcID = cls.jwrapper.getNode2('CPC')
print('cpcID: ', cpcID) # 324 for CPC

#Print distribution for CPC node
gdCPC = cls.jwrapper.getDistribution(cpcID)
arr = typeconv.double_matrix_to_ndarray(gdCPC.o)
print('matrix length:', len(arr[0])) #len = 294
print('cpc distribution:', arr)

#Get values of CPC node
print('cpc values')
gvCPC = cls.jwrapper.getValues(cpcID)
lstVals = typeconv.string_array_to_list(gvCPC.o)
print('length, list:', len(lstVals), lstVals) # len = 294 also

#Get value name of CPC node
print('get cpc value name')
gvnCPC = cls.jwrapper.getValueName(cpcID, 1)
print('value in 1 position:', gvnCPC)

#Print margin for CPC node
#gmCPC = cls.jwrapper.getMargin(cpcID) #<---fails
#arr = typeconv.double_matrix_to_ndarray(gmCPC.o)
#print('cpc margin:', arr)

#Set evidence to first element
print('get evidence')
print(cls.jwrapper.getEvidence(cpcID)) #<---fails

#Set evidence to first element
print('set evidence')
cls.jwrapper.setEvidence(cpcID, 0) #<---fails

#Print new distribution for CPC node
print('new distribution')
gdCPC = cls.jwrapper.getDistribution(cpcID)
arr = typeconv.double_matrix_to_ndarray(gdCPC.o)
print(arr)

Is there something else I have to do after setEvidence but before getDistribution() to get the new distribution on a node?

Peter Reutemann

unread,
Mar 12, 2019, 3:59:17 PM3/12/19
to python-weka-wrapper
Sorry, but I'm not familiar with this code. From the exception, it
looks like the internal data structures have not been initialized to
fit your data (length 0 instead of the number attributes in your
dataset). You would have to look through the Weka code base where it
is being used and how it is initialized.

Cheers, Peter
> --
> You received this message because you are subscribed to the Google Groups "python-weka-wrapper" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to python-weka-wra...@googlegroups.com.
> To post to this group, send email to python-we...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/python-weka-wrapper/0e0213e3-355b-4475-bef8-cb88dd324c57%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



Oleg N

unread,
Mar 12, 2019, 4:17:24 PM3/12/19
to python-weka-wrapper
I don't think I know enough Java :/
Is there an order that these need to be called? Is there a method to use before setEvidence() that initializes things internally?
> To unsubscribe from this group and stop receiving emails from it, send an email to python-weka-wrapper+unsub...@googlegroups.com.

Peter Reutemann

unread,
Mar 12, 2019, 4:25:47 PM3/12/19
to python-weka-wrapper
> I don't think I know enough Java :/
> Is there an order that these need to be called? Is there a method to use before setEvidence() that initializes things internally?

This is very specific Bayesian stuff that I have no idea about, even
less about its implementation within Weka.
Your best bet is to post on the Weka mailing list on how to use the
EditableBayesNet class and how to set the evidence.

Oleg N

unread,
Mar 12, 2019, 6:42:20 PM3/12/19
to python-weka-wrapper
Ok, I'll do that, thank you very much for all the help you've given me!

Oleg N

unread,
Mar 13, 2019, 1:32:48 PM3/13/19
to python-weka-wrapper
I found this Java code that gets to setEvidence() pretty quickly, but they use a BIFReader to instantiate an EditableBayesNet. I have an xml file I made from the Weka gui and I could load it, but how do I get to a BIFReader in Python? Or how else can I load the file? I think it might create enough behind the scenes to let me use setEvidence().

Peter Reutemann

unread,
Mar 13, 2019, 4:22:22 PM3/13/19
to python-weka-wrapper
> I found this Java code that gets to setEvidence() pretty quickly, but they use a BIFReader to instantiate an EditableBayesNet. I have an xml file I made from the Weka gui and I could load it, but how do I get to a BIFReader in Python? Or how else can I load the file? I think it might create enough behind the scenes to let me use setEvidence().
>
> https://gist.github.com/carl0967/1138b5a55d31ca1dda5c

import javabridge
import weka.core.jvm as jvm
from weka.core.classes import JavaObject
from weka.classifiers import Classifier

jvm.start()

xmlfile = "/home/fracpete/temp/bayesnet_iris.xml"
bifreader = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.BIFReader"))
editable = Classifier(jobject=javabridge.make_instance(
"weka/classifiers/bayes/net/EditableBayesNet",
"(Lweka/classifiers/bayes/net/BIFReader;)V",
bifreader.jwrapper.processFile(xmlfile)))
print(editable)

jvm.stop()

Oleg N

unread,
Mar 14, 2019, 12:37:34 PM3/14/19
to python-weka-wrapper
Thank you very much for that, I was able to setEvidence and getEvidence on the editable! :)
the next thing I'd like to do it see the Margins and how they change after setting evidence.
Following your code, I created a MarginCalculator()

marginCalc = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.MarginCalculator"))
marginCalc.jwrapper.calcMargins(editable)

but calcMargins() not happy with the editable it seems, but it doesn't say how... the EditableBayesNet class should be ok.
In the BayesNet editor gui for the saved bifxml file, I go to Tool --> Show Margins, and then I can right-click and set evidence on a node, and see the results change, so I'm trying the same steps here.
What does calcMargins() need? Is it enough to be able to use getMargin afterwards? Thank you again!

Peter Reutemann

unread,
Mar 14, 2019, 3:45:03 PM3/14/19
to python-weka-wrapper
> Thank you very much for that, I was able to setEvidence and getEvidence on the editable! :)
> Like in this example: https://gist.github.com/carl0967/1138b5a55d31ca1dda5c
> the next thing I'd like to do it see the Margins and how they change after setting evidence.
> Following your code, I created a MarginCalculator()
>
> marginCalc = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.MarginCalculator"))
> marginCalc.jwrapper.calcMargins(editable)
>
> but calcMargins() not happy with the editable it seems, but it doesn't say how... the EditableBayesNet class should be ok.
> In the BayesNet editor gui for the saved bifxml file, I go to Tool --> Show Margins, and then I can right-click and set evidence on a node, and see the results change, so I'm trying the same steps here.
> What does calcMargins() need? Is it enough to be able to use getMargin afterwards? Thank you again!

The "jwrapper" property exposes the underlying native Java objects.
When using these methods, you need to provide them with native
objects.

In short, try this:

marginCalc = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.MarginCalculator"))
marginCalc.jwrapper.calcMargins(editable.jobject)

NB: Not tested.

Oleg N

unread,
Mar 14, 2019, 5:00:07 PM3/14/19
to python-weka-wrapper
Ok, that worked to get me further :)

marginCalc = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.MarginCalculator"))
marginCalc.jwrapper.calcMargins(editable.jobject)

so = javabridge.make_instance("weka/core/SerializedObject", "(Ljava/lang/Object;)V", marginCalc.jobject)
m_marginCalculatorWithEvidence = javabridge.call(so, "getObject", "()Ljava/lang/Object;")

so I continued like that link (https://gist.github.com/carl0967/1138b5a55d31ca1dda5c) and I also found and I found a little with SerializedObject in the source code (https://github.com/fracpete/python-weka-wrapper/blob/master/python/weka/core/serialization.py)

Are 'so' and 'm_marginCalculatorWithEvidence' created correctly? I don't get any errors in those lines.
What 'so' for? Does it make a copy of the marginCalc object?
My next problem is that I can't get m_marginCalculatorWithEvidence.setEvidence(iNode, bayes.getEvidence(iNode)) to work.
I tried with jwrapper and without, and I tried marginCalc.setEvidence, which didn't fail, but it didn't make any difference when I printed
print('margincalc: ', marginCalc)
From which object should I setEvidence on, and what's the proper way to view the changes afterwards?

Peter Reutemann

unread,
Mar 14, 2019, 5:10:52 PM3/14/19
to python-weka-wrapper
> Ok, that worked to get me further :)
>
> marginCalc = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.MarginCalculator"))
> marginCalc.jwrapper.calcMargins(editable.jobject)
>
> so = javabridge.make_instance("weka/core/SerializedObject", "(Ljava/lang/Object;)V", marginCalc.jobject)
> m_marginCalculatorWithEvidence = javabridge.call(so, "getObject", "()Ljava/lang/Object;")
>
>
> so I continued like that link (https://gist.github.com/carl0967/1138b5a55d31ca1dda5c) and I also found and I found a little with SerializedObject in the source code (https://github.com/fracpete/python-weka-wrapper/blob/master/python/weka/core/serialization.py)
>
> Are 'so' and 'm_marginCalculatorWithEvidence' created correctly? I don't get any errors in those lines.
> What 'so' for? Does it make a copy of the marginCalc object?

Why don't you just use the "deepcopy" method in the
weka.core.serialization module to create a copy of an object? No need
to do the low-level calls yourself.

> My next problem is that I can't get m_marginCalculatorWithEvidence.setEvidence(iNode, bayes.getEvidence(iNode)) to work.
> I tried with jwrapper and without, and I tried marginCalc.setEvidence, which didn't fail, but it didn't make any difference when I printed
>
> print('margincalc: ', marginCalc)
>
> From which object should I setEvidence on, and what's the proper way to view the changes afterwards?

If "bayes" is wrapped in a JavaObject, then you have to use the
"jwrapper" property to access the underlying Java object, in order to
get access to the getEvidence/setEvidence methods.

I can only repeat myself: I have no idea how this code is to be used.

Oleg N

unread,
Mar 14, 2019, 8:27:41 PM3/14/19
to python-weka-wrapper
Ok, I really do appreciate your help, and I'm almost there :)
I think I have one type conversion left that's not working, it just crashes with no error message.
How do I tell what kind of object 'gm4' is below?
What's the proper way to convert it?
Thank you very much!

import weka.core.jvm as jvm
from weka.classifiers import Classifier
from weka.core.classes import JavaObject
import numpy as np
import weka.core.typeconv as typeconv
import javabridge

# from: http://pythonhosted.org/python-weka-wrapper/examples.html
# https://github.com/LeeKamentsky/python-javabridge/blob/master/javabridge/noseplugin.py
# https://gist.github.com/carl0967/1138b5a55d31ca1dda5c
# https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/python-weka-wrapper/qF4vw_6sqAA/EmqTph1NAAAJ

jvm.start(max_heap_size="4000M")

data_dir = "D:/weka/"

xmlfile = "D:/weka/iris.xml" # created with BayesNet, MaxNrParents=2
bifreader = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.BIFReader"))
editable = Classifier(jobject=javabridge.make_instance(
"weka/classifiers/bayes/net/EditableBayesNet",
"(Lweka/classifiers/bayes/net/BIFReader;)V",
bifreader.jwrapper.processFile(xmlfile)))

classID = editable.jwrapper.getNode2('class')
print('class id:', classID)



marginCalc = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.MarginCalculator"))
marginCalc.jwrapper.calcMargins(editable.jobject)

print('Pre-evidence:\n', marginCalc)

marginCalc.jwrapper.setEvidence(classID, 1)

print('Post-evidence:\n', marginCalc)

gm4 = marginCalc.jwrapper.getMargin(0) # I believe this could be 0 to 4
#arr = typeconv.double_matrix_to_ndarray(gm4.o) # <--- This line fails... I couldn't find a conversion that works
print('getMargin4: ', gm4)

jvm.stop()

Peter Reutemann

unread,
Mar 14, 2019, 8:39:34 PM3/14/19
to python-weka-wrapper
> I think I have one type conversion left that's not working, it just crashes with no error message.
> How do I tell what kind of object 'gm4' is below?

You look up the Javadoc documentation for the relevant class:
http://weka.sourceforge.net/doc.dev/

MarginCalculator class:
http://weka.sourceforge.net/doc.dev/weka/classifiers/bayes/net/MarginCalculator.html

As you can see the return value of "getMargin(int)" is a double array.

> What's the proper way to convert it?

I use the following code in the Classifier.distribution_for_instance
method to turn it into a numpy array:
javabridge.get_env().get_double_array_elements(<doublearray>)

[Not sure whether the ".get_env()" is still really necessary. The
javabridge library has evolved a lot since that code was written.]

Oleg N

unread,
Mar 15, 2019, 3:36:57 PM3/15/19
to python-weka-wrapper
Thank you very, very much for all your help! This will get me going for a while :)
My working code is below, maybe it will help someone, and it's nice to see it correspond to the numbers in the gui.

Could you tell me how I'd know the difference between the doublearray and 2D doublearry resulting from getMargin() and getDistribution()?


import weka.core.jvm as jvm
from weka.classifiers import Classifier
from weka.core.classes import JavaObject
import numpy as np
import weka.core.typeconv as typeconv
import javabridge
import weka.core.serialization as Serial
'''
5 Nodes for Iris dataset:

4 attributes:
node id: 0 (sepallength) [-inf-5.55, 5.55-6.15, 6.15-inf]
node id: 1 (sepalwidth) [-inf-2.95, 2.95-3.35, 3.35-inf]
node id: 2 (petallength) [-inf-2.45, 2.45-4.75, 4.75-inf]
node id: 3 (petalwidth) [-inf-0.8, 0.8-1.75, 1.75-inf]

1 class:
node id: 4 (class) [0=iris-setosa, 1=iris-versicolor, 2=iris-virginica]
'''

# Choose trained Weka BIFXML file
xmlfile = "D:/weka/iris.xml" # created with BayesNet, MaxNrParents=2, BIFXML file
bifreader = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.BIFReader"))
editable = Classifier(jobject=javabridge.make_instance(
"weka/classifiers/bayes/net/EditableBayesNet",
"(Lweka/classifiers/bayes/net/BIFReader;)V",
bifreader.jwrapper.processFile(xmlfile)))

# We need to calculate the margins of all the attributes
marginCalc = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.MarginCalculator"))
marginCalc.jwrapper.calcMargins(editable.jobject)

marginCalcNoEvidence = Serial.deepcopy(marginCalc)    # could maybe get by without this, just use marginCalc()

# Have a look before we set evidence
print('Pre-evidence:\n', marginCalcNoEvidence)

# determine your class ID by name
classID = editable.jwrapper.getNode2('class')
print('class id:', classID)

for j in range(0,3):

marginCalc = JavaObject(JavaObject.new_instance("weka.classifiers.bayes.net.MarginCalculator"))
marginCalc.jwrapper.calcMargins(editable.jobject)

    # Set evidence to an index value of the class node to see which attributes are most influential
marginCalc.jwrapper.setEvidence(classID, j) #0=setosa, 1=versicolor, 2=virginica
print('\n\n', editable.jwrapper.getNodeValue(classID, j))

# View margins post-evidence
    print('Post-evidence:\n', marginCalc)

    # Get the margin on the attribute nodes(0-4)
for i in range(0,4):
gm = marginCalc.jwrapper.getMargin(i) # I believe this could be 0 to 4
arr = javabridge.get_env().get_double_array_elements(gm.o)
print('Margin node', i, '(' + editable.jwrapper.getNodeName(i) + '):', arr)

jvm.stop()

Peter Reutemann

unread,
Mar 15, 2019, 3:52:46 PM3/15/19
to python-weka-wrapper
> Could you tell me how I'd know the difference between the doublearray and 2D doublearry resulting from getMargin() and getDistribution()?

Consulting the Javadoc of the relevant class, that's what I did. One
returned "double[]" and the other "double[][]".

Java tells you more about the types than Python. ;-)
Reply all
Reply to author
Forward
0 new messages