Package weka.core

Examples of weka.core.Instances


        indexOfMetric = indexOfPercOfTarget;
      } else {
        indexOfMetric = indexOfThreshold;
      }
     
      Instances plotInstances = m_masterPlot.getPlotInstances();
      int index = findIndexForValue(value, plotInstances, indexOfMetric);
      updateInfoGivenIndex(index);
    }
View Full Code Here


     
      // First construct some Instances for the curve
      FastVector fv = new FastVector();
      fv.addElement(new Attribute("Sample Size"));
      fv.addElement(new Attribute("Cost/Benefit"));
      Instances costBenefitI = new Instances("Cost/Benefit Curve", fv, 100);
     
      // process the performance data to make this curve
      Instances performanceI = m_masterPlot.getPlotInstances();
     
      for (int i = 0; i < performanceI.numInstances(); i++) {
        Instance current = performanceI.instance(i);
       
        double[] vals = new double[2];
        vals[0] = current.value(10); // sample size
        vals[1] = (current.value(0) * tpCost
            + current.value(1) * fnCost
 
View Full Code Here

   * @throws IOException throws IOEXception if an instance cannot be saved incrementally.
   */ 
  public void writeIncremental(Instance inst) throws IOException{
 
      int writeMode = getWriteMode();
      Instances structure = getInstances();
      PrintWriter outW = null;
     
      if(getRetrieval() == BATCH || getRetrieval() == NONE)
          throw new IOException("Batch and incremental saving cannot be mixed.");
      if(getWriter() != null)
          outW = new PrintWriter(getWriter());
         
      if(writeMode == WAIT){
        if(structure == null){
            setWriteMode(CANCEL);
            if(inst != null)
                System.err.println("Structure(Header Information) has to be set in advance");
        }
        else
            setWriteMode(STRUCTURE_READY);
        writeMode = getWriteMode();
      }
      if(writeMode == CANCEL){
          if(outW != null)
              outW.close();
          cancel();
      }
      if(writeMode == STRUCTURE_READY){
          setWriteMode(WRITE);
          //write header
          if(retrieveFile() == null || outW == null){
              // print out attribute names as first row
              for (int i = 0; i < structure.numAttributes(); i++) {
                System.out.print(structure.attribute(i).name());
                if (i < structure.numAttributes()-1) {
                    System.out.print(m_FieldSeparator);
                } else {
                    System.out.println();
                }
              }
          }
          else{
              for (int i = 0; i < structure.numAttributes(); i++) {
                outW.print(structure.attribute(i).name());
                if (i < structure.numAttributes()-1) {
                    outW.print(m_FieldSeparator);
                } else {
                    outW.println();
                }
              }
View Full Code Here

      ClassifierErrorsPlotInstances plotInstances,
      AbstractOutput classificationOutput,
      boolean onlySetPriors) throws Exception {
       
    if (classifier instanceof weka.classifiers.misc.InputMappedClassifier) {
      Instances mappedClassifierHeader =
        ((weka.classifiers.misc.InputMappedClassifier)classifier).
          getModelHeader(new Instances(inst, 0));
     
      if (classificationOutput != null) {
        classificationOutput.setHeader(mappedClassifierHeader);
      }
     
      if (!onlySetPriors) {
        if (costMatrix != null) {
          eval = new Evaluation(new Instances(mappedClassifierHeader, 0), costMatrix);
        } else {
          eval = new Evaluation(new Instances(mappedClassifierHeader, 0));
        }
      }
     
      if (!eval.getHeader().equalHeaders(inst)) {
        // When the InputMappedClassifier is loading a model,
        // we need to make a new dataset that maps the training instances to
        // the structure expected by the mapped classifier - this is only
        // to ensure that the structure and priors computed by
        // evaluation object is correct with respect to the mapped classifier
        Instances mappedClassifierDataset =
          ((weka.classifiers.misc.InputMappedClassifier)classifier).
            getModelHeader(new Instances(mappedClassifierHeader, 0));
        for (int zz = 0; zz < inst.numInstances(); zz++) {
          Instance mapped = ((weka.classifiers.misc.InputMappedClassifier)classifier).
            constructMappedInstance(inst.instance(zz));
          mappedClassifierDataset.add(mapped);
        }
        eval.setPriors(mappedClassifierDataset);
        if (!onlySetPriors) {
          if (plotInstances != null) {
            plotInstances.setInstances(mappedClassifierDataset);
            plotInstances.setClassifier(classifier);
            /*          int mappedClass =
            ((weka.classifiers.misc.InputMappedClassifier)classifier).getMappedClassIndex();
          System.err.println("Mapped class index " + mappedClass); */
            plotInstances.setClassIndex(mappedClassifierDataset.classIndex());
            plotInstances.setEvaluation(eval);
          }
        }
      } else {
        eval.setPriors(inst);
View Full Code Here

      m_RunThread = new Thread() {
  public void run() {
    // Copy the current state of things
    m_Log.statusMessage("Setting up...");
    CostMatrix costMatrix = null;
    Instances inst = new Instances(m_Instances);
    DataSource source = null;
          Instances userTestStructure = null;
    ClassifierErrorsPlotInstances plotInstances = null;
   
    // for timing
    long trainTimeStart = 0, trainTimeElapsed = 0;

          try {
            if (m_TestLoader != null && m_TestLoader.getStructure() != null) {
              m_TestLoader.reset();
              source = new DataSource(m_TestLoader);
              userTestStructure = source.getStructure();
              userTestStructure.setClassIndex(m_TestClassIndex);
            }
          } catch (Exception ex) {
            ex.printStackTrace();
          }
    if (m_EvalWRTCostsBut.isSelected()) {
      costMatrix = new CostMatrix((CostMatrix) m_CostMatrixEditor
          .getValue());
    }
    boolean outputModel = m_OutputModelBut.isSelected();
    boolean outputConfusion = m_OutputConfusionBut.isSelected();
    boolean outputPerClass = m_OutputPerClassBut.isSelected();
    boolean outputSummary = true;
          boolean outputEntropy = m_OutputEntropyBut.isSelected();
    boolean saveVis = m_StorePredictionsBut.isSelected();
    boolean outputPredictionsText = (m_ClassificationOutputEditor.getValue().getClass() != Null.class);

    String grph = null;

    int testMode = 0;
    int numFolds = 10;
          double percent = 66;
    int classIndex = m_ClassCombo.getSelectedIndex();
    inst.setClassIndex(classIndex);
    Classifier classifier = (Classifier) m_ClassifierEditor.getValue();
    Classifier template = null;
    try {
      template = AbstractClassifier.makeCopy(classifier);
    } catch (Exception ex) {
      m_Log.logMessage("Problem copying classifier: " + ex.getMessage());
    }
    Classifier fullClassifier = null;
    StringBuffer outBuff = new StringBuffer();
    AbstractOutput classificationOutput = null;
    if (outputPredictionsText) {
      classificationOutput = (AbstractOutput) m_ClassificationOutputEditor.getValue();
      Instances header = new Instances(inst, 0);
      header.setClassIndex(classIndex);
      classificationOutput.setHeader(header);
      classificationOutput.setBuffer(outBuff);
    }
    String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date());
    String cname = "";
          String cmd = "";
    Evaluation eval = null;
    try {
      if (m_CVBut.isSelected()) {
        testMode = 1;
        numFolds = Integer.parseInt(m_CVText.getText());
        if (numFolds <= 1) {
    throw new Exception("Number of folds must be greater than 1");
        }
      } else if (m_PercentBut.isSelected()) {
        testMode = 2;
        percent = Double.parseDouble(m_PercentText.getText());
        if ((percent <= 0) || (percent >= 100)) {
    throw new Exception("Percentage must be between 0 and 100");
        }
      } else if (m_TrainBut.isSelected()) {
        testMode = 3;
      } else if (m_TestSplitBut.isSelected()) {
        testMode = 4;
        // Check the test instance compatibility
        if (source == null) {
          throw new Exception("No user test set has been specified");
        }
       
        if (!(classifier instanceof weka.classifiers.misc.InputMappedClassifier)) {
          if (!inst.equalHeaders(userTestStructure)) {
            boolean wrapClassifier = false;
            if (!Utils.
                getDontShowDialog("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier")) {
              JCheckBox dontShow = new JCheckBox("Do not show this message again");
              Object[] stuff = new Object[2];
              stuff[0] = "Train and test set are not compatible.\n" +
              "Would you like to automatically wrap the classifier in\n" +
              "an \"InputMappedClassifier\" before proceeding?.\n";
              stuff[1] = dontShow;

              int result = JOptionPane.showConfirmDialog(ClassifierPanel.this, stuff,
                  "ClassifierPanel", JOptionPane.YES_OPTION);
             
              if (result == JOptionPane.YES_OPTION) {
                wrapClassifier = true;
              }
             
              if (dontShow.isSelected()) {
                String response = (wrapClassifier) ? "yes" : "no";
                Utils.
                  setDontShowDialogResponse("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier",
                      response);
              }

            } else {
              // What did the user say - do they want to autowrap or not?
              String response =
                Utils.getDontShowDialogResponse("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier");
              if (response != null && response.equalsIgnoreCase("yes")) {
                wrapClassifier = true;
              }
            }

            if (wrapClassifier) {
              weka.classifiers.misc.InputMappedClassifier temp =
                new weka.classifiers.misc.InputMappedClassifier();

              // pass on the known test structure so that we get the
              // correct mapping report from the toString() method
              // of InputMappedClassifier
              temp.setClassifier(classifier);
              temp.setTestStructure(userTestStructure);
              classifier = temp;
            } else {
              throw new Exception("Train and test set are not compatible\n" + inst.equalHeadersMsg(userTestStructure));
            }
          }
        }
             
      } else {
        throw new Exception("Unknown test mode");
      }

      cname = classifier.getClass().getName();
      if (cname.startsWith("weka.classifiers.")) {
        name += cname.substring("weka.classifiers.".length());
      } else {
        name += cname;
      }
      cmd = classifier.getClass().getName();
      if (classifier instanceof OptionHandler)
        cmd += " " + Utils.joinOptions(((OptionHandler) classifier).getOptions());
     
      // set up the structure of the plottable instances for
      // visualization
      plotInstances = ExplorerDefaults.getClassifierErrorsPlotInstances();
      plotInstances.setInstances(inst);
      plotInstances.setClassifier(classifier);
      plotInstances.setClassIndex(inst.classIndex());
      plotInstances.setSaveForVisualization(saveVis);

      // Output some header information
      m_Log.logMessage("Started " + cname);
      m_Log.logMessage("Command: " + cmd);
      if (m_Log instanceof TaskLogger) {
        ((TaskLogger)m_Log).taskStarted();
      }
      outBuff.append("=== Run information ===\n\n");
      outBuff.append("Scheme:       " + cname);
      if (classifier instanceof OptionHandler) {
        String [] o = ((OptionHandler) classifier).getOptions();
        outBuff.append(" " + Utils.joinOptions(o));
      }
      outBuff.append("\n");
      outBuff.append("Relation:     " + inst.relationName() + '\n');
      outBuff.append("Instances:    " + inst.numInstances() + '\n');
      outBuff.append("Attributes:   " + inst.numAttributes() + '\n');
      if (inst.numAttributes() < 100) {
        for (int i = 0; i < inst.numAttributes(); i++) {
    outBuff.append("              " + inst.attribute(i).name()
             + '\n');
        }
      } else {
        outBuff.append("              [list of attributes omitted]\n");
      }

      outBuff.append("Test mode:    ");
      switch (testMode) {
        case 3: // Test on training
    outBuff.append("evaluate on training data\n");
    break;
        case 1: // CV mode
    outBuff.append("" + numFolds + "-fold cross-validation\n");
    break;
        case 2: // Percent split
    outBuff.append("split " + percent
        + "% train, remainder test\n");
    break;
        case 4: // Test on user split
    if (source.isIncremental())
      outBuff.append("user supplied test set: "
          + " size unknown (reading incrementally)\n");
    else
      outBuff.append("user supplied test set: "
          + source.getDataSet().numInstances() + " instances\n");
    break;
      }
            if (costMatrix != null) {
               outBuff.append("Evaluation cost matrix:\n")
               .append(costMatrix.toString()).append("\n");
            }
      outBuff.append("\n");
      m_History.addResult(name, outBuff);
      m_History.setSingle(name);
     
      // Build the model and output it.
      if (outputModel || (testMode == 3) || (testMode == 4)) {
        m_Log.statusMessage("Building model on training data...");

        trainTimeStart = System.currentTimeMillis();
        classifier.buildClassifier(inst);
        trainTimeElapsed = System.currentTimeMillis() - trainTimeStart;
      }

      if (outputModel) {
        outBuff.append("=== Classifier model (full training set) ===\n\n");
        outBuff.append(classifier.toString() + "\n");
        outBuff.append("\nTime taken to build model: " +
           Utils.doubleToString(trainTimeElapsed / 1000.0,2)
           + " seconds\n\n");
        m_History.updateResult(name);
        if (classifier instanceof Drawable) {
    grph = null;
    try {
      grph = ((Drawable)classifier).graph();
    } catch (Exception ex) {
    }
        }
        // copy full model for output
        SerializedObject so = new SerializedObject(classifier);
        fullClassifier = (Classifier) so.getObject();
      }
     
      switch (testMode) {
        case 3: // Test on training
        m_Log.statusMessage("Evaluating on training data...");
        eval = new Evaluation(inst, costMatrix);
       
        // make adjustments if the classifier is an InputMappedClassifier
        eval = setupEval(eval, classifier, inst, costMatrix,
            plotInstances, classificationOutput, false);
       
        //plotInstances.setEvaluation(eval);
              plotInstances.setUp();
       
        if (outputPredictionsText) {
    printPredictionsHeader(outBuff, classificationOutput, "training set");
        }

        for (int jj=0;jj<inst.numInstances();jj++) {
    plotInstances.process(inst.instance(jj), classifier, eval);
   
    if (outputPredictionsText) {
      classificationOutput.printClassification(classifier, inst.instance(jj), jj);
    }
    if ((jj % 100) == 0) {
      m_Log.statusMessage("Evaluating on training data. Processed "
              +jj+" instances...");
    }
        }
        if (outputPredictionsText)
    classificationOutput.printFooter();
        if (outputPredictionsText && classificationOutput.generatesOutput()) {
    outBuff.append("\n");
        }
        outBuff.append("=== Evaluation on training set ===\n");
        break;

        case 1: // CV mode
        m_Log.statusMessage("Randomizing instances...");
        int rnd = 1;
        try {
    rnd = Integer.parseInt(m_RandomSeedText.getText().trim());
    // System.err.println("Using random seed "+rnd);
        } catch (Exception ex) {
    m_Log.logMessage("Trouble parsing random seed value");
    rnd = 1;
        }
        Random random = new Random(rnd);
        inst.randomize(random);
        if (inst.attribute(classIndex).isNominal()) {
    m_Log.statusMessage("Stratifying instances...");
    inst.stratify(numFolds);
        }
        eval = new Evaluation(inst, costMatrix);
       
         // make adjustments if the classifier is an InputMappedClassifier
              eval = setupEval(eval, classifier, inst, costMatrix,
                  plotInstances, classificationOutput, false);
       
//        plotInstances.setEvaluation(eval);
              plotInstances.setUp();
     
        if (outputPredictionsText) {
    printPredictionsHeader(outBuff, classificationOutput, "test data");
        }

        // Make some splits and do a CV
        for (int fold = 0; fold < numFolds; fold++) {
    m_Log.statusMessage("Creating splits for fold "
            + (fold + 1) + "...");
    Instances train = inst.trainCV(numFolds, fold, random);
   
    // make adjustments if the classifier is an InputMappedClassifier
          eval = setupEval(eval, classifier, train, costMatrix,
              plotInstances, classificationOutput, true);
         
//    eval.setPriors(train);
    m_Log.statusMessage("Building model for fold "
            + (fold + 1) + "...");
    Classifier current = null;
    try {
      current = AbstractClassifier.makeCopy(template);
    } catch (Exception ex) {
      m_Log.logMessage("Problem copying classifier: " + ex.getMessage());
    }
    current.buildClassifier(train);
    Instances test = inst.testCV(numFolds, fold);
    m_Log.statusMessage("Evaluating model for fold "
            + (fold + 1) + "...");
    for (int jj=0;jj<test.numInstances();jj++) {
      plotInstances.process(test.instance(jj), current, eval);
      if (outputPredictionsText) {
        classificationOutput.printClassification(current, test.instance(jj), jj);
      }
    }
        }
        if (outputPredictionsText)
    classificationOutput.printFooter();
        if (outputPredictionsText) {
    outBuff.append("\n");
        }
        if (inst.attribute(classIndex).isNominal()) {
    outBuff.append("=== Stratified cross-validation ===\n");
        } else {
    outBuff.append("=== Cross-validation ===\n");
        }
        break;
   
        case 2: // Percent split
        if (!m_PreserveOrderBut.isSelected()) {
    m_Log.statusMessage("Randomizing instances...");
    try {
      rnd = Integer.parseInt(m_RandomSeedText.getText().trim());
    } catch (Exception ex) {
      m_Log.logMessage("Trouble parsing random seed value");
      rnd = 1;
    }
    inst.randomize(new Random(rnd));
        }
        int trainSize = (int) Math.round(inst.numInstances() * percent / 100);
        int testSize = inst.numInstances() - trainSize;
        Instances train = new Instances(inst, 0, trainSize);
        Instances test = new Instances(inst, trainSize, testSize);
        m_Log.statusMessage("Building model on training split ("+trainSize+" instances)...");
        Classifier current = null;
        try {
    current = AbstractClassifier.makeCopy(template);
        } catch (Exception ex) {
    m_Log.logMessage("Problem copying classifier: " + ex.getMessage());
        }
        current.buildClassifier(train);
        eval = new Evaluation(train, costMatrix);
       
        // make adjustments if the classifier is an InputMappedClassifier
              eval = setupEval(eval, classifier, train, costMatrix,
                  plotInstances, classificationOutput, false);
                     
//        plotInstances.setEvaluation(eval);
              plotInstances.setUp();
        m_Log.statusMessage("Evaluating on test split...");
      
        if (outputPredictionsText) {
    printPredictionsHeader(outBuff, classificationOutput, "test split");
        }
    
        for (int jj=0;jj<test.numInstances();jj++) {
    plotInstances.process(test.instance(jj), current, eval);
    if (outputPredictionsText) {
      classificationOutput.printClassification(current, test.instance(jj), jj);
    }
    if ((jj % 100) == 0) {
      m_Log.statusMessage("Evaluating on test split. Processed "
              +jj+" instances...");
    }
        }
        if (outputPredictionsText)
    classificationOutput.printFooter();
        if (outputPredictionsText) {
    outBuff.append("\n");
        }
        outBuff.append("=== Evaluation on test split ===\n");
        break;
   
        case 4: // Test on user split
        m_Log.statusMessage("Evaluating on test data...");
        eval = new Evaluation(inst, costMatrix);
        // make adjustments if the classifier is an InputMappedClassifier
              eval = setupEval(eval, classifier, inst, costMatrix,
                  plotInstances, classificationOutput, false);
             
//        plotInstances.setEvaluation(eval);
              plotInstances.setUp();
       
        if (outputPredictionsText) {
    printPredictionsHeader(outBuff, classificationOutput, "test set");
        }

        Instance instance;
        int jj = 0;
        while (source.hasMoreElements(userTestStructure)) {
    instance = source.nextElement(userTestStructure);
    plotInstances.process(instance, classifier, eval);
    if (outputPredictionsText) {
      classificationOutput.printClassification(classifier, instance, jj);
    }
    if ((++jj % 100) == 0) {
      m_Log.statusMessage("Evaluating on test data. Processed "
          +jj+" instances...");
    }
        }

        if (outputPredictionsText)
    classificationOutput.printFooter();
        if (outputPredictionsText) {
    outBuff.append("\n");
        }
        outBuff.append("=== Evaluation on test set ===\n");
        break;

        default:
        throw new Exception("Test mode not implemented");
      }
     
      if (outputSummary) {
        outBuff.append(eval.toSummaryString(outputEntropy) + "\n");
      }

      if (inst.attribute(classIndex).isNominal()) {

        if (outputPerClass) {
    outBuff.append(eval.toClassDetailsString() + "\n");
        }

        if (outputConfusion) {
    outBuff.append(eval.toMatrixString() + "\n");
        }
      }

            if (   (fullClassifier instanceof Sourcable)
                 && m_OutputSourceCode.isSelected()) {
              outBuff.append("=== Source code ===\n\n");
              outBuff.append(
                Evaluation.wekaStaticWrapper(
                    ((Sourcable) fullClassifier),
                    m_SourceCodeClass.getText()));
            }

      m_History.updateResult(name);
      m_Log.logMessage("Finished " + cname);
      m_Log.statusMessage("OK");
    } catch (Exception ex) {
      ex.printStackTrace();
      m_Log.logMessage(ex.getMessage());
      JOptionPane.showMessageDialog(ClassifierPanel.this,
            "Problem evaluating classifier:\n"
            + ex.getMessage(),
            "Evaluate classifier",
            JOptionPane.ERROR_MESSAGE);
      m_Log.statusMessage("Problem evaluating classifier");
    } finally {
      try {
              if (!saveVis && outputModel) {
      FastVector vv = new FastVector();
      vv.addElement(fullClassifier);
      Instances trainHeader = new Instances(m_Instances, 0);
      trainHeader.setClassIndex(classIndex);
      vv.addElement(trainHeader);
                  if (grph != null) {
        vv.addElement(grph);
      }
      m_History.addObject(name, vv);
              } else if (saveVis && plotInstances != null && plotInstances.getPlotInstances().numInstances() > 0) {
    m_CurrentVis = new VisualizePanel();
    m_CurrentVis.setName(name+" ("+inst.relationName()+")");
    m_CurrentVis.setLog(m_Log);
    m_CurrentVis.addPlot(plotInstances.getPlotData(cname));
    //m_CurrentVis.setColourIndex(plotInstances.getPlotInstances().classIndex()+1);
          m_CurrentVis.setColourIndex(plotInstances.getPlotInstances().classIndex());
    plotInstances.cleanUp();
     
                FastVector vv = new FastVector();
                if (outputModel) {
                  vv.addElement(fullClassifier);
                  Instances trainHeader = new Instances(m_Instances, 0);
                  trainHeader.setClassIndex(classIndex);
                  vv.addElement(trainHeader);
                  if (grph != null) {
                    vv.addElement(grph);
                  }
                }
View Full Code Here

    VisualizePanel temp_vp = null;
    String temp_grph = null;
    FastVector temp_preds = null;
    Attribute temp_classAtt = null;
    Classifier temp_classifier = null;
    Instances temp_trainHeader = null;
     
    if (o != null) {
      for (int i = 0; i < o.size(); i++) {
  Object temp = o.elementAt(i);
  if (temp instanceof Classifier) {
    temp_classifier = (Classifier)temp;
  } else if (temp instanceof Instances) { // training header
    temp_trainHeader = (Instances)temp;
  } else if (temp instanceof VisualizePanel) { // normal errors
    temp_vp = (VisualizePanel)temp;
  } else if (temp instanceof String) { // graphable output
    temp_grph = (String)temp;
  } else if (temp instanceof FastVector) { // predictions
    temp_preds = (FastVector)temp;
  } else if (temp instanceof Attribute) { // class attribute
    temp_classAtt = (Attribute)temp;
  }
      }
    }

    final VisualizePanel vp = temp_vp;
    final String grph = temp_grph;
    final FastVector preds = temp_preds;
    final Attribute classAtt = temp_classAtt;
    final Classifier classifier = temp_classifier;
    final Instances trainHeader = temp_trainHeader;
   
    JMenuItem saveModel = new JMenuItem("Save model");
    if (classifier != null) {
      saveModel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      saveClassifier(selectedName, classifier, trainHeader);
    }
  });
    } else {
      saveModel.setEnabled(false);
    }
    resultListMenu.add(saveModel);

    JMenuItem reEvaluate =
      new JMenuItem("Re-evaluate model on current test set");
    if (classifier != null && m_TestLoader != null) {
      reEvaluate.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      reevaluateModel(selectedName, classifier, trainHeader);
    }
  });
    } else {
      reEvaluate.setEnabled(false);
    }
    resultListMenu.add(reEvaluate);
   
    resultListMenu.addSeparator();
   
    JMenuItem visErrors = new JMenuItem("Visualize classifier errors");
    if (vp != null) {
      if ((vp.getXIndex() == 0) && (vp.getYIndex() == 1)) {
  try {
    vp.setXIndex(vp.getInstances().classIndex())// class
    vp.setYIndex(vp.getInstances().classIndex() - 1)// predicted class
  }
  catch (Exception e) {
    // ignored
  }
      }
      visErrors.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      visualizeClassifierErrors(vp);
    }
  });
    } else {
      visErrors.setEnabled(false);
    }
    resultListMenu.add(visErrors);

    JMenuItem visGrph = new JMenuItem("Visualize tree");
    if (grph != null) {
  if(((Drawable)temp_classifier).graphType()==Drawable.TREE) {
      visGrph.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
      String title;
      if (vp != null) title = vp.getName();
      else title = selectedName;
      visualizeTree(grph, title);
        }
    });
  }
  else if(((Drawable)temp_classifier).graphType()==Drawable.BayesNet) {
      visGrph.setText("Visualize graph");
      visGrph.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
      Thread th = new Thread() {
        public void run() {
        visualizeBayesNet(grph, selectedName);
        }
          };
      th.start();
        }
    });
  }
  else
      visGrph.setEnabled(false);
    } else {
      visGrph.setEnabled(false);
    }
    resultListMenu.add(visGrph);

    JMenuItem visMargin = new JMenuItem("Visualize margin curve");
    if ((preds != null) && (classAtt != null) && (classAtt.isNominal())) {
      visMargin.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      try {
        MarginCurve tc = new MarginCurve();
        Instances result = tc.getCurve(preds);
        VisualizePanel vmc = new VisualizePanel();
        vmc.setName(result.relationName());
        vmc.setLog(m_Log);
        PlotData2D tempd = new PlotData2D(result);
        tempd.setPlotName(result.relationName());
        tempd.addInstanceNumberAttribute();
        vmc.addPlot(tempd);
        visualizeClassifierErrors(vmc);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  });
    } else {
      visMargin.setEnabled(false);
    }
    resultListMenu.add(visMargin);

    JMenu visThreshold = new JMenu("Visualize threshold curve");
    if ((preds != null) && (classAtt != null) && (classAtt.isNominal())) {
      for (int i = 0; i < classAtt.numValues(); i++) {
  JMenuItem clv = new JMenuItem(classAtt.value(i));
  final int classValue = i;
  clv.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
    ThresholdCurve tc = new ThresholdCurve();
    Instances result = tc.getCurve(preds, classValue);
    //VisualizePanel vmc = new VisualizePanel();
    ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
    vmc.setROCString("(Area under ROC = " +
         Utils.doubleToString(ThresholdCurve.getROCArea(result), 4) + ")");
    vmc.setLog(m_Log);
    vmc.setName(result.relationName()+". (Class value "+
          classAtt.value(classValue)+")");
    PlotData2D tempd = new PlotData2D(result);
    tempd.setPlotName(result.relationName());
    tempd.addInstanceNumberAttribute();
    // specify which points are connected
    boolean[] cp = new boolean[result.numInstances()];
    for (int n = 1; n < cp.length; n++)
      cp[n] = true;
    tempd.setConnectPoints(cp);
    // add plot
    vmc.addPlot(tempd);
    visualizeClassifierErrors(vmc);
        } catch (Exception ex) {
    ex.printStackTrace();
        }
        }
    });
    visThreshold.add(clv);
      }
    } else {
      visThreshold.setEnabled(false);
    }
    resultListMenu.add(visThreshold);
   
    JMenu visCostBenefit = new JMenu("Cost/Benefit analysis");
    if ((preds != null) && (classAtt != null) && (classAtt.isNominal())) {
      for (int i = 0; i < classAtt.numValues(); i++) {
        JMenuItem clv = new JMenuItem(classAtt.value(i));
        final int classValue = i;
        clv.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              try {
                ThresholdCurve tc = new ThresholdCurve();
                Instances result = tc.getCurve(preds, classValue);

                // Create a dummy class attribute with the chosen
                // class value as index 0 (if necessary).
                Attribute classAttToUse = classAtt;
                if (classValue != 0) {
                  FastVector newNames = new FastVector();
                  newNames.addElement(classAtt.value(classValue));
                  for (int k = 0; k < classAtt.numValues(); k++) {
                    if (k != classValue) {
                      newNames.addElement(classAtt.value(k));
                    }
                  }
                  classAttToUse = new Attribute(classAtt.name(), newNames);
                }
               
                CostBenefitAnalysis cbAnalysis = new CostBenefitAnalysis();
               
                PlotData2D tempd = new PlotData2D(result);
                tempd.setPlotName(result.relationName());
                tempd.m_alwaysDisplayPointsOfThisSize = 10;
                // specify which points are connected
                boolean[] cp = new boolean[result.numInstances()];
                for (int n = 1; n < cp.length; n++)
                  cp[n] = true;
                tempd.setConnectPoints(cp);
               
                String windowTitle = "";
                if (classifier != null) {
                  String cname = classifier.getClass().getName();
                  if (cname.startsWith("weka.classifiers.")) {
                    windowTitle = "" + cname.substring("weka.classifiers.".length()) + " ";
                  }
                }
                windowTitle += " (class = " + classAttToUse.value(0) + ")";               
               
                // add plot
                cbAnalysis.setCurveData(tempd, classAttToUse);
                visualizeCostBenefitAnalysis(cbAnalysis, windowTitle);
              } catch (Exception ex) {
                ex.printStackTrace();
              }
              }
          });
          visCostBenefit.add(clv);
      }
    } else {
      visCostBenefit.setEnabled(false);
    }
    resultListMenu.add(visCostBenefit);

    JMenu visCost = new JMenu("Visualize cost curve");
    if ((preds != null) && (classAtt != null) && (classAtt.isNominal())) {
      for (int i = 0; i < classAtt.numValues(); i++) {
  JMenuItem clv = new JMenuItem(classAtt.value(i));
  final int classValue = i;
  clv.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
    CostCurve cc = new CostCurve();
    Instances result = cc.getCurve(preds, classValue);
    VisualizePanel vmc = new VisualizePanel();
    vmc.setLog(m_Log);
    vmc.setName(result.relationName()+". (Class value "+
          classAtt.value(classValue)+")");
    PlotData2D tempd = new PlotData2D(result);
    tempd.m_displayAllPoints = true;
    tempd.setPlotName(result.relationName());
    boolean [] connectPoints =
      new boolean [result.numInstances()];
    for (int jj = 1; jj < connectPoints.length; jj+=2) {
      connectPoints[jj] = true;
    }
    tempd.setConnectPoints(connectPoints);
    //      tempd.addInstanceNumberAttribute();
View Full Code Here

     
      try {
  loader.setFile(new File(options[0]));
  // incremental
  if (loader instanceof IncrementalConverter) {
    Instances structure = loader.getStructure();
    System.out.println(structure);
    Instance temp;
    do {
      temp = loader.getNextInstance(structure);
      if (temp != null)
View Full Code Here

  System.err.println("Usage: ModelPerformanceChart <dataset>");
  System.exit(1);
      }
      java.io.Reader r = new java.io.BufferedReader(
       new java.io.FileReader(args[0]));
      Instances inst = new Instances(r);
      final javax.swing.JFrame jf = new javax.swing.JFrame();
      jf.getContentPane().setLayout(new java.awt.BorderLayout());
      final ModelPerformanceChart as = new ModelPerformanceChart();
      PlotData2D pd = new PlotData2D(inst);
      pd.setPlotName(inst.relationName());
      ThresholdDataEvent roc = new ThresholdDataEvent(as, pd);
      as.acceptDataSet(roc);     

      jf.getContentPane().add(as, java.awt.BorderLayout.CENTER);
      jf.addWindowListener(new java.awt.event.WindowAdapter() {
View Full Code Here

    int returnVal = m_FileChooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File selected = m_FileChooser.getSelectedFile();
      Classifier classifier = null;
      Instances trainHeader = null;

      m_Log.statusMessage("Loading model from file...");

      try {
  InputStream is = new FileInputStream(selected);
  if (selected.getName().endsWith(PMML_FILE_EXTENSION)) {
    PMMLModel model = PMMLFactory.getPMMLModel(is, m_Log);
    if (model instanceof PMMLClassifier) {
      classifier = (PMMLClassifier)model;
      /*trainHeader =
        ((PMMLClassifier)classifier).getMiningSchema().getMiningSchemaAsInstances(); */
    } else {
      throw new Exception("PMML model is not a classification/regression model!");
    }
  } else {
  if (selected.getName().endsWith(".gz")) {
    is = new GZIPInputStream(is);
  }
  ObjectInputStream objectInputStream = new ObjectInputStream(is);
  classifier = (Classifier) objectInputStream.readObject();
  try { // see if we can load the header
    trainHeader = (Instances) objectInputStream.readObject();
  } catch (Exception e) {} // don't fuss if we can't
  objectInputStream.close();
  }
      } catch (Exception e) {
 
  JOptionPane.showMessageDialog(null, e, "Load Failed",
              JOptionPane.ERROR_MESSAGE);
     

      m_Log.statusMessage("OK");
     
      if (classifier != null) {
  m_Log.logMessage("Loaded model from file '" + selected.getName()+ "'");
  String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date());
  String cname = classifier.getClass().getName();
  if (cname.startsWith("weka.classifiers."))
    cname = cname.substring("weka.classifiers.".length());
  name += cname + " from file '" + selected.getName() + "'";
  StringBuffer outBuff = new StringBuffer();

  outBuff.append("=== Model information ===\n\n");
  outBuff.append("Filename:     " + selected.getName() + "\n");
  outBuff.append("Scheme:       " + classifier.getClass().getName());
  if (classifier instanceof OptionHandler) {
    String [] o = ((OptionHandler) classifier).getOptions();
    outBuff.append(" " + Utils.joinOptions(o));
  }
  outBuff.append("\n");
  if (trainHeader != null) {
    outBuff.append("Relation:     " + trainHeader.relationName() + '\n');
    outBuff.append("Attributes:   " + trainHeader.numAttributes() + '\n');
    if (trainHeader.numAttributes() < 100) {
      for (int i = 0; i < trainHeader.numAttributes(); i++) {
        outBuff.append("              " + trainHeader.attribute(i).name()
           + '\n');
      }
    } else {
      outBuff.append("              [list of attributes omitted]\n");
    }
View Full Code Here

            m_Log.statusMessage("Setting up...");
            Classifier classifierToUse = classifier;

            StringBuffer outBuff = m_History.getNamedBuffer(name);
            DataSource source = null;
            Instances userTestStructure = null;
            ClassifierErrorsPlotInstances plotInstances = null;

            CostMatrix costMatrix = null;
            if (m_EvalWRTCostsBut.isSelected()) {
              costMatrix = new CostMatrix((CostMatrix) m_CostMatrixEditor
                                          .getValue());
            }   
            boolean outputConfusion = m_OutputConfusionBut.isSelected();
            boolean outputPerClass = m_OutputPerClassBut.isSelected();
            boolean outputSummary = true;
            boolean outputEntropy = m_OutputEntropyBut.isSelected();
            boolean saveVis = m_StorePredictionsBut.isSelected();
            boolean outputPredictionsText = (m_ClassificationOutputEditor.getValue().getClass() != Null.class);
            String grph = null;   
            Evaluation eval = null;

            try {

              boolean incrementalLoader = (m_TestLoader instanceof IncrementalConverter);
              if (m_TestLoader != null && m_TestLoader.getStructure() != null) {
                m_TestLoader.reset();
                source = new DataSource(m_TestLoader);
                userTestStructure = source.getStructure();
                userTestStructure.setClassIndex(m_TestClassIndex);
              }
              // Check the test instance compatibility
              if (source == null) {
                throw new Exception("No user test set has been specified");
              }
              if (trainHeader != null) {
                boolean compatibilityProblem = false;
                if (trainHeader.classIndex() >
                    userTestStructure.numAttributes()-1) {
                  compatibilityProblem = true;
                  //throw new Exception("Train and test set are not compatible");
                }
                userTestStructure.setClassIndex(trainHeader.classIndex());
                if (!trainHeader.equalHeaders(userTestStructure)) {
                  compatibilityProblem = true;
                  // throw new Exception("Train and test set are not compatible:\n" + trainHeader.equalHeadersMsg(userTestStructure));
                 
                  if (compatibilityProblem &&
                      !(classifierToUse instanceof weka.classifiers.misc.InputMappedClassifier)) {

                    boolean wrapClassifier = false;
                    if (!Utils.
                        getDontShowDialog("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier")) {
                      JCheckBox dontShow = new JCheckBox("Do not show this message again");
                      Object[] stuff = new Object[2];
                      stuff[0] = "Data used to train model and test set are not compatible.\n" +
                      "Would you like to automatically wrap the classifier in\n" +
                      "an \"InputMappedClassifier\" before proceeding?.\n";
                      stuff[1] = dontShow;

                      int result = JOptionPane.showConfirmDialog(ClassifierPanel.this, stuff,
                          "ClassifierPanel", JOptionPane.YES_OPTION);
                     
                      if (result == JOptionPane.YES_OPTION) {
                        wrapClassifier = true;
                      }
                     
                      if (dontShow.isSelected()) {
                        String response = (wrapClassifier) ? "yes" : "no";
                        Utils.
                          setDontShowDialogResponse("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier",
                              response);
                      }

                    } else {
                      // What did the user say - do they want to autowrap or not?
                      String response =
                        Utils.getDontShowDialogResponse("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier");
                      if (response != null && response.equalsIgnoreCase("yes")) {
                        wrapClassifier = true;
                      }
                    }

                    if (wrapClassifier) {
                      weka.classifiers.misc.InputMappedClassifier temp =
                        new weka.classifiers.misc.InputMappedClassifier();

                      temp.setClassifier(classifierToUse);
                      temp.setModelHeader(trainHeader);
                      classifierToUse = temp;
                    } else {
                      throw new Exception("Train and test set are not compatible\n" +
                          trainHeader.equalHeadersMsg(userTestStructure));
                    }
                  }
                }
              } else {
          if (classifierToUse instanceof PMMLClassifier) {
            // set the class based on information in the mining schema
            Instances miningSchemaStructure =
              ((PMMLClassifier)classifierToUse).getMiningSchema().getMiningSchemaAsInstances();
            String className = miningSchemaStructure.classAttribute().name();
            Attribute classMatch = userTestStructure.attribute(className);
            if (classMatch == null) {
              throw new Exception("Can't find a match for the PMML target field "
            + className + " in the "
            + "test instances!");
View Full Code Here

TOP

Related Classes of weka.core.Instances

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.