List of usage examples for weka.classifiers Classifier classifyInstance
public double classifyInstance(Instance instance) throws Exception;
From source file:es.bsc.autonomic.powermodeller.tools.classifiers.WekaWrapper.java
License:Apache License
public static List<Double> validateDataset(Classifier classifier, DataSet validationDS) { logger.debug("Validating dataset."); List<Double> estimated = new ArrayList<Double>(); Instances validation_ds = convertDataSetToInstances(validationDS); //logger.debug(classifier.toString()); try {//from w w w. j ava2 s.c o m // estimate each instance for (Instance instance : validation_ds) { try { Double k = classifier.classifyInstance(instance); estimated.add(k); } catch (Exception e) { logger.error("Error while estimating instances", e); throw new WekaWrapperException("Error while estimating instances"); } } } catch (Exception e) { logger.error("Error while reading input DataSet", e); throw new WekaWrapperException("Error while reading input DataSet"); } return estimated; }
From source file:es.ubu.XRayDetector.modelo.ventana.VentanaAbstracta.java
License:Open Source License
/** * Method that uses a classifier to classifiy an instance. * @return Value of the classifier//from w w w .j ava 2s . c o m */ public double clasificar() { Instance instancia = crearInstancia(); Classifier clas = abrirModelo(); double clase = 0; try { clase = clas.classifyInstance(instancia); } catch (Exception e) { throw new RuntimeException(e); } return clase; }
From source file:farm_ads.MyClassifier.java
public String ClassifyMultiInstances(Classifier c, Instances t) throws Exception { String format = "%4s %15s %15s\n"; String format1 = "%15s %15s %15s\n"; String s = new String(); TP = FP = FN = TN = 0.0;/*from w w w . j a v a 2s.c om*/ s += "S lng mu: " + Integer.toString(t.numInstances()) + "\n\n"; s += "======= Kt qu d on qung co========\n"; s += String.format(format, "STT", "Trc d on", "Sau d on"); for (int i = 0; i < t.numInstances(); i++) { String[] classAds = { "Ph hp", "Khng ph hp" }; double actValue = t.instance(i).classValue(); Instance newInst = t.instance(i); double pred = c.classifyInstance(newInst); countPredicted(actValue, pred); s += String.format(format, Integer.toString(i + 1), classAds[(int) actValue], classAds[(int) pred]); } s += "\nCh thch --> Ph hp: (+1) , Khng ph hp: (-1)\n"; s += "\nS mu c phn lp ng: " + Integer.toString(getCorrect()); s += "\nS mu c phn lp sai: " + Integer.toString(getInCorrect()); s += "\n\n======= ?nh gi kt qu d on ========\n"; s += String.format(format1, "Prediction", "Recall", "F-measure"); s += String.format(format1, getPrecision(), getRecall(), getFMeasure()); return s; }
From source file:farm_ads.MyClassifier.java
public String ClassifyInstance(Classifier c, String instance) throws Exception { String format = "%4s %15s %15s\n"; FarmAds fa = new FarmAds(instance, 1); FarmAdsVector fav = new FarmAdsVector(); fav.writeFile("data\\dataVecto.dat", fa); DataSource source = new DataSource("data\\dataVecto.dat"); Instances instances = source.getDataSet(); if (instances.classIndex() == -1) { instances.setClassIndex(instances.numAttributes() - 1); }//from www .ja v a 2 s.co m String s = new String(); s += "======= Kt qu d on qung co========\n"; s += String.format(format, "STT", "Trc d on", "Sau d on"); String[] classAds = { "Ph hp", "Khng Ph Hp" }; double actValue = instances.firstInstance().classValue(); Instance newInst = instances.firstInstance(); double pred = c.classifyInstance(newInst); s += String.format(format, Integer.toString(1), classAds[(int) actValue], classAds[(int) pred]); if (actValue == pred) { s += "\n\n ==> D on ng"; } else { s += "\n\n ==> D on sai"; } return s; }
From source file:ffnn.TucilWeka.java
public static String testInstance(Classifier cls, Instances testData) { String value = null;/*from ww w. ja v a 2 s . c om*/ double result = 0; try { result = cls.classifyInstance(testData.get(0)); } catch (Exception ex) { Logger.getLogger(TucilWeka.class.getName()).log(Level.SEVERE, null, ex); } if (result == 0) { value = "iris-setosa / 0"; } else if (result == 1) { value = "iris-vesicolor / 1"; } else if (result == 2) { value = "iris-virginica / 2"; } else { value = "error"; } return value; }
From source file:FinalMineria.Reconocimiento.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//w w w . j a v a 2s . co m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception { String accion = request.getParameter("accion"); BufferedReader br = null; String ruta = request.getServletContext().getRealPath("/Recursos"); br = new BufferedReader(new FileReader(ruta + "/nombres.txt")); linea = br.readLine(); br.close(); if ("Detener".equals(accion)) { grabar.finish(); try { Thread.sleep(4000); } catch (InterruptedException ex) { Logger.getLogger(GrabarAudio.class.getName()).log(Level.SEVERE, null, ex); } String comando = "cmd /c " + request.getServletContext().getRealPath("/Recursos/OpenSmile") + "\\SMILExtract_Release.exe -C " + request.getServletContext().getRealPath("/Recursos/config") + "\\IS12_speaker_trait.conf -I " + request.getServletContext().getRealPath("/Recursos/audios") + "\\prueba.wav -O " + request.getServletContext().getRealPath("/Recursos/arff") + "\\prueba.arff -classes {" + linea + "} -classlabel ?"; Process proceso = Runtime.getRuntime().exec(comando); proceso.waitFor(); Instances prueba, conocimiento; try (BufferedReader archivoBase = new BufferedReader(new FileReader( request.getServletContext().getRealPath("/Recursos/arff") + "\\baseDatos.arff"))) { conocimiento = new Instances(archivoBase); } try (BufferedReader archivoPrueba = new BufferedReader( new FileReader(request.getServletContext().getRealPath("/Recursos/arff") + "\\prueba.arff"))) { prueba = new Instances(archivoPrueba); } conocimiento.deleteStringAttributes(); conocimiento.setClassIndex(981); prueba.deleteStringAttributes(); prueba.setClassIndex(981); Classifier clasificadorModelo = (Classifier) new NaiveBayes(); clasificadorModelo.buildClassifier(conocimiento); double valorP = clasificadorModelo.classifyInstance(prueba.instance(prueba.numInstances() - 1)); String prediccion = prueba.classAttribute().value((int) valorP); System.out.println(prediccion); request.setAttribute("prediccion", prediccion); RequestDispatcher dispatcher = request.getRequestDispatcher("./Hablante.jsp"); dispatcher.forward(request, response); } else if ("Grabar".equals(accion)) { ruta = request.getServletContext().getRealPath("/Recursos/audios"); grabar = new Grabador(ruta + "\\" + "prueba"); Thread stopper = new Thread(new Runnable() { public void run() { try { Thread.sleep(tiempo); } catch (InterruptedException ex) { ex.printStackTrace(); } grabar.finish(); } }); stopper.start(); // start recording grabar.start(); response.sendRedirect("./grabar.jsp"); } }
From source file:fr.loria.synalp.jtrans.phonetiseur.Classifieurs.java
License:Open Source License
private double tester(Classifier res, String fichierTestARFF, Filter filtre) throws Exception { double nbOk = 0; double nbTotal = 0; if (res == null) { System.out.println("===============>" + fichierTestARFF); return -1; }//from w w w . j a va2 s . c o m DataSource source = new DataSource(fichierTestARFF); Instances instances = source.getDataSet(); nbTotal = instances.numInstances(); instances.setClassIndex(instances.numAttributes() - 1); instances = appliquerFiltre(filtre, instances); // !!!!!!!!!!!!!!!!! SUPER IMPORTANT !!!!!!!!!!!!! for (int i = 0; i < instances.numInstances(); i++) { double numeroClass = res.classifyInstance(instances.instance(i)); if (numeroClass == instances.instance(i).classValue()) { nbOk++; } } return nbOk / nbTotal * 100; }
From source file:fr.loria.synalp.jtrans.phonetiseur.Classifieurs.java
License:Open Source License
private String resultatClassifieur(Instance instance, Classifier classifieur, Instances instances) throws Exception { double r = classifieur.classifyInstance(instance); return instances.attribute(instances.numAttributes() - 1).value((int) r); }
From source file:function.ClassifyUnseen.java
public static double classify(Classifier cl, Instance inst) throws Exception { return cl.classifyInstance(inst); }
From source file:gate.plugin.learningframework.engines.EngineWeka.java
@Override public List<GateClassification> classify(AnnotationSet instanceAS, AnnotationSet inputAS, AnnotationSet sequenceAS, String parms) { Instances instances = crWeka.getRepresentationWeka(); CorpusRepresentationMalletTarget data = (CorpusRepresentationMalletTarget) corpusRepresentationMallet; data.stopGrowth();//from w ww.j av a 2 s. c om List<GateClassification> gcs = new ArrayList<GateClassification>(); LFPipe pipe = (LFPipe) data.getRepresentationMallet().getPipe(); Classifier wekaClassifier = (Classifier) model; // iterate over the instance annotations and create mallet instances for (Annotation instAnn : instanceAS.inDocumentOrder()) { Instance inst = data.extractIndependentFeatures(instAnn, inputAS); inst = pipe.instanceFrom(inst); // Convert to weka Instance weka.core.Instance wekaInstance = CorpusRepresentationWeka.wekaInstanceFromMalletInstance(instances, inst); // classify with the weka classifier or predict the numeric value: if the mallet pipe does have // a target alphabet we assume classification, otherwise we assume regression GateClassification gc = null; if (pipe.getTargetAlphabet() == null) { // regression double result = Double.NaN; try { result = wekaClassifier.classifyInstance(wekaInstance); } catch (Exception ex) { // Hmm, for now we just log the error and continue, not sure if we should stop here! ex.printStackTrace(System.err); Logger.getLogger(EngineWeka.class.getName()).log(Level.SEVERE, null, ex); } //gc = new GateClassification(instAnn, (result==Double.NaN ? null : String.valueOf(result)), 1.0); gc = new GateClassification(instAnn, result); } else { // classification // Weka AbstractClassifier already handles the situation correctly when // distributionForInstance is not implemented by the classifier: in that case // is calls classifyInstance and returns an array of size numClasses where // the entry of the target class is set to 1.0 except when the classification is a missing // value, then all class probabilities will be 0.0 // If distributionForInstance is implemented for the algorithm, we should get // the probabilities or all zeros for missing class from the algorithm. double[] predictionDistribution = new double[0]; try { //System.err.println("classifying instance "+wekaInstance.toString()); predictionDistribution = wekaClassifier.distributionForInstance(wekaInstance); } catch (Exception ex) { throw new RuntimeException( "Weka classifier error in document " + instanceAS.getDocument().getName(), ex); } // This is classification, we should always get a distribution list > 1 if (predictionDistribution.length < 2) { throw new RuntimeException("Classifier returned less than 2 probabilities: " + predictionDistribution.length + "for instance" + wekaInstance); } double bestprob = 0.0; int bestlabel = 0; /* System.err.print("DEBUG: got classes from pipe: "); Object[] cls = pipe.getTargetAlphabet().toArray(); boolean first = true; for(Object cl : cls) { if(first) { first = false; } else { System.err.print(", "); } System.err.print(">"+cl+"<"); } System.err.println(); */ List<String> classList = new ArrayList<String>(); List<Double> confidenceList = new ArrayList<Double>(); for (int i = 0; i < predictionDistribution.length; i++) { int thislabel = i; double thisprob = predictionDistribution[i]; String labelstr = (String) pipe.getTargetAlphabet().lookupObject(thislabel); classList.add(labelstr); confidenceList.add(thisprob); if (thisprob > bestprob) { bestlabel = thislabel; bestprob = thisprob; } } // end for i < predictionDistribution.length String cl = (String) pipe.getTargetAlphabet().lookupObject(bestlabel); gc = new GateClassification(instAnn, cl, bestprob, classList, confidenceList); } gcs.add(gc); } data.startGrowth(); return gcs; }