examples.TrainerFrame.java Source code

Java tutorial

Introduction

Here is the source code for examples.TrainerFrame.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package examples;

import jAudioFeatureExtractor.ACE.DataTypes.Batch;
import jAudioFeatureExtractor.ACE.XMLParsers.XMLDocumentParser;
import jAudioFeatureExtractor.CommandLineThread;
import jAudioFeatureExtractor.DataModel;
import jAudioFeatureExtractor.DataTypes.RecordingInfo;
import java.util.List;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import java.util.ArrayList;
import java.util.Random;
import weka.core.Instances;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import weka.classifiers.trees.J48;
import weka.core.Attribute;
import weka.core.Debug;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.converters.ArffSaver;

/**
 *
 * @author mick
 */
public class TrainerFrame extends javax.swing.JFrame {

    /**
     * Creates new form TrainerFrame
     */
    public TrainerFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonTrain = new javax.swing.JButton();
        jTextFieldCallDirectory = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldOtherSoundDirectory = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldClassifierName = new javax.swing.JTextField();
        pBar = new javax.swing.JProgressBar();
        jLabelTrainerStatus = new javax.swing.JLabel();

        jButtonTrain.setLabel("Create New Classifier");
        jButtonTrain.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonTrainActionPerformed(evt);
            }
        });

        jTextFieldCallDirectory.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldCallDirectoryActionPerformed(evt);
            }
        });

        jButton2.setLabel("Browse");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Calls Directory");

        jButton3.setLabel("Browse");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel2.setText("Other Sound Directory");

        jLabel3.setText("Name");

        jTextFieldClassifierName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldClassifierNameActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addComponent(jLabel3)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jTextFieldClassifierName)
                                        .addComponent(jTextFieldCallDirectory)
                                        .addComponent(jTextFieldOtherSoundDirectory)
                                        .addGroup(layout.createSequentialGroup().addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jLabel2).addComponent(jLabel1))
                                                .addGap(0, 210, Short.MAX_VALUE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jButton2).addComponent(jButton3))
                                .addGap(49, 49, 49))
                        .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabelTrainerStatus).addComponent(jButtonTrain))
                                .addGap(0, 0, Short.MAX_VALUE))
                        .addComponent(pBar, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                layout.createSequentialGroup().addContainerGap().addComponent(jLabel3).addGap(3, 3, 3)
                        .addComponent(jTextFieldClassifierName, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 16,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextFieldCallDirectory, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextFieldOtherSoundDirectory, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 100, Short.MAX_VALUE)
                        .addComponent(jButtonTrain)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelTrainerStatus)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(pBar,
                                javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.PREFERRED_SIZE)));

        jButtonTrain.getAccessibleContext().setAccessibleName("jButtonNewClassifier");

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonTrainActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTrainActionPerformed
        //This is a temporary fix to make it appear like its finished

        pBar.setMaximum(7);
        pBar.setValue(0);
        pBar.repaint();
        jLabelTrainerStatus.setText("Extracting Target Features");
        //Generate Target Features
        String featuresTarget = null;
        new Thread(new TrainerFrame.thread1()).start();
        try {
            featuresTarget = GlobalData.getFeatures(jTextFieldCallDirectory.getText());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        pBar.setValue(1);
        pBar.repaint();
        jLabelTrainerStatus.setText("Extracting Other Features");

        //Generate Non-targe features Features
        String featuresOther = null;
        new Thread(new TrainerFrame.thread1()).start();
        try {
            featuresOther = GlobalData.getFeatures(jTextFieldOtherSoundDirectory.getText());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        pBar.setValue(2);
        pBar.repaint();
        jLabelTrainerStatus.setText("Parsing Features");

        //Load Target Arrf File
        BufferedReader readerTarget;
        Instances dataTarget = null;
        try {
            readerTarget = new BufferedReader(new FileReader(featuresTarget));
            dataTarget = new Instances(readerTarget);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        pBar.setValue(3);
        pBar.repaint();
        //Load Other Arrf File
        BufferedReader readerOther;
        Instances dataOther = null;
        try {
            readerOther = new BufferedReader(new FileReader(featuresOther));
            dataOther = new Instances(readerOther);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        pBar.setValue(4);
        pBar.repaint();
        jLabelTrainerStatus.setText("Training Classifier");

        Instances newData = new Instances(dataTarget);
        FastVector typeList = new FastVector() {
        };
        typeList.add("target");
        typeList.add("other");
        newData.insertAttributeAt(new Attribute("NewNominal", (java.util.List<String>) typeList),
                newData.numAttributes());
        for (Instance instance : newData) {
            instance.setValue(newData.numAttributes() - 1, "target");
        }

        dataOther.insertAttributeAt(new Attribute("NewNominal", (java.util.List<String>) typeList),
                dataOther.numAttributes());
        for (Instance instance : dataOther) {
            instance.setValue(newData.numAttributes() - 1, "other");
            newData.add(instance);
        }

        newData.setClassIndex(newData.numAttributes() - 1);
        pBar.setValue(5);
        pBar.repaint();
        ArffSaver saver = new ArffSaver();
        saver.setInstances(newData);
        try {
            saver.setFile(new File("AnimalCallTrainingFile.arff"));
        } catch (IOException ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            saver.writeBatch();
        } catch (IOException ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        pBar.setValue(6);
        pBar.repaint();
        //Train a classifier
        String[] options = new String[1];
        options[0] = "-U";
        J48 tree = new J48();
        try {
            tree.setOptions(options);
        } catch (Exception ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            tree.buildClassifier(newData);
        } catch (Exception ex) {
            Logger.getLogger(TrainerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        Debug.saveToFile("Classifiers/" + jTextFieldClassifierName.getText(), tree);
        System.out.println("classifier saved");
        MyClassifier tempClass = new MyClassifier(jTextFieldClassifierName.getText());
        GlobalData.classifierList.addElement(tempClass.name);
        pBar.setValue(7);
        pBar.repaint();
        jLabelTrainerStatus.setText("Finished");

    }//GEN-LAST:event_jButtonTrainActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fc.showOpenDialog(null);
        jTextFieldCallDirectory.setText(fc.getSelectedFile().getPath());
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fc.showOpenDialog(null);
        jTextFieldOtherSoundDirectory.setText(fc.getSelectedFile().getPath());
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jTextFieldCallDirectoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCallDirectoryActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldCallDirectoryActionPerformed

    private void jTextFieldClassifierNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldClassifierNameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldClassifierNameActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TrainerFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TrainerFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TrainerFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TrainerFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TrainerFrame().setVisible(true);
            }
        });
    }

    public class thread1 implements Runnable {
        public void run() {
            /*pBar.setMaximum(50);
            for(int i = 0; i < 50; i++){
            final int percent = i;
            pBar.setValue(percent);
            pBar.repaint();
            if(i==0){
                jLabelTrainerStatus.setText("Extracting features");
            } else if (i==15)
            {
                jLabelTrainerStatus.setText("Testing SVM");
                         
            } else if (i==15){
                jLabelTrainerStatus.setText("Testing Decision Forest");
            } else if (i==29){
                jLabelTrainerStatus.setText("Testing KNN");
            }
            else if (i==40){
                jLabelTrainerStatus.setText("Testing LDA");
            }
            else if (i==49){
                jLabelTrainerStatus.setText("Forest Chosen");
            }
            try{Thread.sleep(200);}
            catch (InterruptedException err){}
                
            }*/

        }

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButtonTrain;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelTrainerStatus;
    private javax.swing.JTextField jTextFieldCallDirectory;
    private javax.swing.JTextField jTextFieldClassifierName;
    private javax.swing.JTextField jTextFieldOtherSoundDirectory;
    private static javax.swing.JProgressBar pBar;
    // End of variables declaration//GEN-END:variables
}