javadata-miningweka

how to display the premise and consequence when the setcar is set to true


I want to get the premise and consequence for each line of generated rules after the running the apriori algorithm in Weka 3.8.6.

`apriori.setNumRules(NUMBER_OF_RULES); apriori.setMinMetric(MINIMUM_CONFIDENCE); apriori.setLowerBoundMinSupport(MINIMUM_SUPPORT);

    apriori.setCar(true);

    apriori.buildAssociations(instances);`

But a exception: java.lang.ClassCastException: class weka.associations.ItemSet cannot be cast to class weka.associations.AprioriItemSet (weka.associations.ItemSet and weka.associations.AprioriItemSet are in unnamed module of loader.

Why when I simple change setCar(false) to setCar(true) I can't call buildAssociations(instances)? When setCar(false) I can call the method with no problems. How can I do this? How to call the method buildAssociations whit setCar(true).

I want to call the apriori.buildAssociations(instances) whit no errors


Solution

  • When using car==false, you cannot use getAssociationRules(), as different data structures have been built internally. Instead, you need to call getAllTheRules().

    You have to do something like this:

    import weka.associations.Apriori;
    import weka.associations.ItemSet;
    import weka.core.Instances;
    import weka.core.Utils;
    import weka.core.converters.ConverterUtils.DataSource;
    
    public class AprioriCarExample {
    
      public static void main(String[] args) throws Exception {
        Instances instances = DataSource.read("/some/where/supermarket.arff");
        instances.setClassIndex(instances.numAttributes() - 1);
    
        Apriori apriori = new Apriori();
        apriori.setNumRules(10);
        apriori.setMinMetric(0.50);
        apriori.setLowerBoundMinSupport(0.1);
        apriori.setCar(true);
        apriori.buildAssociations(instances);
    
        // rules
        System.out.println("\nRules:");
        for (int i = 0; i < apriori.getAllTheRules()[0].size(); i++) {
          String premise = ((ItemSet) apriori.getAllTheRules()[0].get(i)).toString(apriori.getInstancesNoClass(), ' ', ' ');
          String consequence = ((ItemSet) apriori.getAllTheRules()[1].get(i)).toString(apriori.getInstancesOnlyClass(), ' ', ' ');
          String confidence = Utils.doubleToString(((Double) apriori.getAllTheRules()[2].get(i)), 2);
          System.out.println((i+1) + ".:");
          System.out.println("  premise: " + premise);
          System.out.println("  consequence: " + consequence);
          System.out.println("  confidence: " + confidence);
        }
      }
    }