martes, 22 de noviembre de 2011

An example of Weka and Java Persistence API

For this example I'm using MacBook Pro with Lion, Netbeans 6.9, MySQL Database.
First of all, we have to create a database in MySQL to retrieve the data. You can use the following script:


CREATE DATABASE IF NOT EXISTS exampleWeka;
USE exampleWeka;
DROP TABLE IF EXISTS weather;
CREATE TABLE  weather (
    id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id),
    outlook varchar(10),
    temperature varchar(10),
    humidity varchar(10),
    windy varchar(10),
    play varchar(10)
);
insert into weather(outlook,temperature,humidity,windy,play)values('sunny','hot','high','FALSE','no');
insert into weather(outlook,temperature,humidity,windy,play)values('sunny','hot','high','TRUE','no');
insert into weather(outlook,temperature,humidity,windy,play)values('overcast','hot','high','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('rainy','mild','high','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('rainy','cool','normal','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('rainy','cool','normal','TRUE','no');
insert into weather(outlook,temperature,humidity,windy,play)values('overcast','cool','normal','TRUE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('sunny','mild','high','FALSE','no');
insert into weather(outlook,temperature,humidity,windy,play)values('sunny','cool','normal','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('rainy','mild','normal','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('sunny','mild','normal','TRUE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('overcast','mild','high','TRUE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('overcast','hot','normal','FALSE','yes');
insert into weather(outlook,temperature,humidity,windy,play)values('rainy','mild','high','TRUE','no');
commit;



Then you can download Weka. I downloaded the version 3.4.19 from  http://sourceforge.net/projects/weka/files/weka-3-4/3.4.19/weka-3-4-19.zip/download. Then you have to extract the file and add weka.jar to the libraries of your EJB project

Then you have to create an Enterprise Application project in Netbeans.




Add MySQL library to the EJB Project.

Add the library weka.jar to the EJB project. I'm using the version available at:http://sourceforge.net/projects/weka/files/weka-3-7/3.7.5/weka-3-7-5-monolithic.jar/download

After this, create a Datasource to the database created above.

Create an Entity class to use the weather table.

Create a Session bean with remote interface.

Create the following utility class in the package com.example.ejb.util of the EJB project



package com.example.ejb.util;

import com.example.ejb.entity.Weather;
import java.util.List;
import weka.classifiers.trees.J48;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;

public class UtilWeka {
    static Instances instances = null;

    private static FastVector createAttributes(boolean classification) {
        FastVector fvWekaAttributes = new FastVector(9);
        FastVector fvOutlook = new FastVector(3);
        fvOutlook.addElement("sunny");
        fvOutlook.addElement("overcast");
        fvOutlook.addElement("rainy");
        Attribute outlook = new Attribute("outlook", fvOutlook);
        fvWekaAttributes.addElement(outlook);

        FastVector fvTemperature = new FastVector(3);
        fvTemperature.addElement("hot");
        fvTemperature.addElement("mild");
        fvTemperature.addElement("cool");
        Attribute temperature = new Attribute("temperature", fvTemperature);
        fvWekaAttributes.addElement(temperature);

        FastVector fvHumidity = new FastVector(2);
        fvHumidity.addElement("high");
        fvHumidity.addElement("normal");
        Attribute humidity = new Attribute("humidity", fvHumidity);
        fvWekaAttributes.addElement(humidity);

        FastVector fvWindy = new FastVector(2);
        fvWindy.addElement("TRUE");
        fvWindy.addElement("FALSE");
        Attribute windy = new Attribute("windy", fvWindy);
        fvWekaAttributes.addElement(windy);


        if(!classification){
        FastVector fvPlay = new FastVector(2);
        fvPlay.addElement("no");
        fvPlay.addElement("yes");
        Attribute play = new Attribute("play", fvPlay);
        fvWekaAttributes.addElement(play);
        }

        return fvWekaAttributes;
    }

    private static Instances generateInstances(List list) {
        FastVector fvAttributes = createAttributes(false);
        Instances instances = new Instances("Rel", fvAttributes, 5);
        instances.setClassIndex(instances.numAttributes() - 1);
        for (Weather weather : list) {
            Instance iExample = new Instance(5);
            iExample.setValue((Attribute) fvAttributes.elementAt(0), weather.getOutlook());
            iExample.setValue((Attribute) fvAttributes.elementAt(1), weather.getTemperature());
            iExample.setValue((Attribute) fvAttributes.elementAt(2), weather.getHumidity());
            iExample.setValue((Attribute) fvAttributes.elementAt(3), weather.getWindy());
            iExample.setValue((Attribute) fvAttributes.elementAt(4), weather.getPlay());
            instances.add(iExample);
        }
        return instances;
    }

    private static Instance generateWeatherInstance(Weather weather) {
        FastVector fvAttributes = createAttributes(true);
        Instances instances = new Instances("Rel", fvAttributes, 9);
        instances.setClassIndex(instances.numAttributes() - 1);



        Instance iExample = new Instance(9);
        iExample.setValue((Attribute) fvAttributes.elementAt(0), weather.getOutlook());
        iExample.setValue((Attribute) fvAttributes.elementAt(1), weather.getTemperature());
        iExample.setValue((Attribute) fvAttributes.elementAt(2), weather.getHumidity());
        iExample.setValue((Attribute) fvAttributes.elementAt(3), weather.getWindy());
       // iExample.setValue((Attribute) fvAttributes.elementAt(4), weather.getPlay());

        instances.add(iExample);

        return instances.firstInstance();
    }

    public static void initJ48Tree(List list) {
        instances=generateInstances(list);
        try {
            J48 j48 = new J48();
            instances.setClassIndex(instances.numAttributes() - 1);
            j48.buildClassifier(instances);
            System.out.println(j48.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void classifyInstanceJ48(Weather weather) {
        double val=0;
        try {
            J48 j48 = new J48();
            instances.setClassIndex(instances.numAttributes() - 1);
            j48.buildClassifier(instances);
            val=j48.classifyInstance(generateWeatherInstance(weather));
            if(val==1){
                System.out.println("We can play");
            }else{
                System.out.println("We can't play");
            }
           
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
 

Change SessionBean to: 


package com.example.ejb.session;

import com.example.ejb.entity.Weather;
import com.example.ejb.util.UtilWeka;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import weka.core.Instances;

@Stateless
public class SessionBean implements SessionBeanRemote {

    @PersistenceContext
EntityManager em;
Instances instances =null;
    public void initWeatherData() {
        Query query=em.createNamedQuery("Weather.findAll");
        UtilWeka.initJ48Tree((List)query.getResultList());
}

    public void classifyJ48(Weather weather) {
        UtilWeka.classifyInstanceJ48(weather);
    }
   
}
 


Modify the client with an injection to the Session Bean.

package mavenwekaapp;

import com.example.ejb.entity.Weather;
import com.example.ejb.session.SessionBeanRemote;
import javax.ejb.EJB;

public class Main {
    @EJB
    private static SessionBeanRemote sessionBean;


    public static void main(String[] args) {
        sessionBean.initWeatherData();
        Weather wheater=new Weather();
        wheater.setHumidity("normal");
        wheater.setOutlook("overcast");
        wheater.setTemperature("hot");
        wheater.setWindy("FALSE");
        sessionBean.classifyJ48(wheater);
    }
}



Run the Enterprise Project.


These are functions,which implement ID3 and NBTree algorithms.
public static void initId3Tree(List list) {
        instances=generateInstances(list);
        try {
            Id3 id3 = new Id3();
            instances.setClassIndex(instances.numAttributes() - 1);
            id3.buildClassifier(instances);
            System.out.println(id3.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void classifyInstanceId3(Weather weather) {
        double val=0;
        try {
            Id3 id3 = new Id3();
            instances.setClassIndex(instances.numAttributes() - 1);
            id3.buildClassifier(instances);
            val=id3.classifyInstance(generateWeatherInstance(weather));
            if(val==1){
                System.out.println("We can play");
            }else{
                System.out.println("We can't play");
            }
           
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }



    public static void initNBTree(List list) {
        instances=generateInstances(list);
        try {
            NBTree nbTree = new NBTree();
            instances.setClassIndex(instances.numAttributes() - 1);
            nbTree.buildClassifier(instances);
            System.out.println(nbTree.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void classifyInstanceNBTree(Weather weather) {
        double val=0;
        try {
            NBTree nbTree = new NBTree();
            instances.setClassIndex(instances.numAttributes() - 1);
            nbTree.buildClassifier(instances);
            val=nbTree.classifyInstance(generateWeatherInstance(weather));
            if(val==1){
                System.out.println("We can play");
            }else{
                System.out.println("We can't play");
            }
           
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }






No hay comentarios:

Publicar un comentario