List of usage examples for weka.classifiers Evaluation Evaluation
public Evaluation(Instances data) throws Exception
From source file:com.sliit.rules.RuleContainer.java
public String predictionResult(String filePath) throws Exception { File testPath = new File(filePath); CSVLoader loader = new CSVLoader(); loader.setSource(testPath);//from www .j ava 2 s . c o m Instances testInstances = loader.getDataSet(); testInstances.setClassIndex(testInstances.numAttributes() - 1); Evaluation eval = new Evaluation(testInstances); eval.evaluateModel(ruleMoldel, testInstances); ArrayList<Prediction> predictions = eval.predictions(); int predictedVal = (int) predictions.get(0).predicted(); String cdetails = instances.classAttribute().value(predictedVal); return cdetails; }
From source file:com.sliit.views.DataVisualizerPanel.java
void getRocCurve() { try {/*w ww . ja v a 2 s. c o m*/ Instances data; data = new Instances(new BufferedReader(new FileReader(datasetPathText.getText()))); data.setClassIndex(data.numAttributes() - 1); // train classifier Classifier cl = new NaiveBayes(); Evaluation eval = new Evaluation(data); eval.crossValidateModel(cl, data, 10, new Random(1)); // generate curve ThresholdCurve tc = new ThresholdCurve(); int classIndex = 0; Instances result = tc.getCurve(eval.predictions(), classIndex); // plot curve ThresholdVisualizePanel vmc = new ThresholdVisualizePanel(); vmc.setROCString("(Area under ROC = " + Utils.doubleToString(tc.getROCArea(result), 4) + ")"); vmc.setName(result.relationName()); 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); // display curve String plotName = vmc.getName(); final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Classifier Visualize: " + plotName); jf.setSize(500, 400); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(vmc, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); } }); jf.setVisible(true); } catch (IOException ex) { Logger.getLogger(DataVisualizerPanel.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(DataVisualizerPanel.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.sliit.views.KNNView.java
void getRocCurve() { try {// www . ja va 2 s . c o m Instances data; data = new Instances(new BufferedReader(new java.io.FileReader(PredictorPanel.modalText.getText()))); data.setClassIndex(data.numAttributes() - 1); // train classifier Classifier cl = new NaiveBayes(); Evaluation eval = new Evaluation(data); eval.crossValidateModel(cl, data, 10, new Random(1)); // generate curve ThresholdCurve tc = new ThresholdCurve(); int classIndex = 0; Instances result = tc.getCurve(eval.predictions(), classIndex); // plot curve ThresholdVisualizePanel vmc = new ThresholdVisualizePanel(); vmc.setROCString("(Area under ROC = " + Utils.doubleToString(tc.getROCArea(result), 4) + ")"); vmc.setName(result.relationName()); 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); rocPanel.removeAll(); rocPanel.add(vmc, "vmc", 0); rocPanel.revalidate(); } catch (IOException ex) { Logger.getLogger(DataVisualizerPanel.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(DataVisualizerPanel.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.sliit.views.SVMView.java
/** * draw ROC curve//from w w w . jav a 2 s .com */ void getRocCurve() { try { Instances data; data = new Instances(new BufferedReader(new FileReader(PredictorPanel.modalText.getText()))); data.setClassIndex(data.numAttributes() - 1); //train classifier Classifier cl = new NaiveBayes(); Evaluation eval = new Evaluation(data); eval.crossValidateModel(cl, data, 10, new Random(1)); // generate curve ThresholdCurve tc = new ThresholdCurve(); int classIndex = 0; Instances result = tc.getCurve(eval.predictions(), classIndex); // plot curve ThresholdVisualizePanel vmc = new ThresholdVisualizePanel(); vmc.setROCString("(Area under ROC = " + Utils.doubleToString(tc.getROCArea(result), 4) + ")"); vmc.setName(result.relationName()); 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); // rocPanel.removeAll(); // rocPanel.add(vmc, "vmc", 0); // rocPanel.revalidate(); } catch (IOException ex) { Logger.getLogger(DataVisualizerPanel.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(DataVisualizerPanel.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Control.Classificador.java
public ArrayList<Resultado> classificar(Plano plano, Arquivo arq) { try {/* ww w . j av a 2 s . com*/ FileReader leitor = new FileReader(arq.arquivo); Instances conjunto = new Instances(leitor); conjunto.setClassIndex(conjunto.numAttributes() - 1); Evaluation avaliacao = new Evaluation(conjunto); conjunto = conjunto.resample(new Random()); Instances baseTreino = null, baseTeste = null; Random rand = new Random(1); if (plano.eHoldOut) { baseTeste = conjunto.testCV(3, 0); baseTreino = conjunto.trainCV(3, 0); } else { baseTeste = baseTreino = conjunto; } if (plano.IBK) { try { IB1 vizinho = new IB1(); vizinho.buildClassifier(baseTeste); avaliacao.crossValidateModel(vizinho, baseTeste, (plano.eHoldOut) ? 4 : baseTeste.numInstances(), rand); Resultado resultado = new Resultado("NN", avaliacao.toMatrixString("Algortmo Vizinho Mais Prximo - Matriz de Confuso"), avaliacao.toClassDetailsString("kNN")); resultado.setTaxaErro(avaliacao.errorRate()); resultado.setTaxaAcerto(1 - avaliacao.errorRate()); resultado.setRevocacao(recallToDouble(avaliacao, baseTeste)); resultado.setPrecisao(precisionToDouble(avaliacao, baseTeste)); this.resultados.add(resultado); } catch (UnsupportedAttributeTypeException ex) { Mensagem.erro("Algortmo IB1 no suporta atributos numricos!", "MTCS - ERRO"); } } if (plano.J48) { try { J48 j48 = new J48(); j48.buildClassifier(baseTeste); avaliacao.crossValidateModel(j48, baseTeste, (plano.eHoldOut) ? 4 : baseTeste.numInstances(), rand); Resultado resultado = new Resultado("J48", avaliacao.toMatrixString("Algortmo J48 - Matriz de Confuso"), avaliacao.toClassDetailsString("J48")); resultado.setTaxaErro(avaliacao.errorRate()); resultado.setTaxaAcerto(1 - avaliacao.errorRate()); resultado.setRevocacao(recallToDouble(avaliacao, baseTeste)); resultado.setPrecisao(precisionToDouble(avaliacao, baseTeste)); this.resultados.add(resultado); } catch (UnsupportedAttributeTypeException ex) { Mensagem.erro("Algortmo J48 no suporta atributos nominais!", "MTCS - ERRO"); } } if (plano.KNN) { try { IBk knn = new IBk(3); knn.buildClassifier(baseTeste); avaliacao.crossValidateModel(knn, baseTeste, (plano.eHoldOut) ? 4 : baseTeste.numInstances(), rand); Resultado resultado = new Resultado("KNN", avaliacao.toMatrixString("Algortmo KNN - Matriz de Confuso"), avaliacao.toClassDetailsString("kNN")); resultado.setTaxaErro(avaliacao.errorRate()); resultado.setTaxaAcerto(1 - avaliacao.errorRate()); resultado.setRevocacao(recallToDouble(avaliacao, baseTeste)); resultado.setPrecisao(precisionToDouble(avaliacao, baseTeste)); this.resultados.add(resultado); } catch (UnsupportedAttributeTypeException ex) { Mensagem.erro("Algortmo KNN no suporta atributos numricos!", "MTCS - ERRO"); } } if (plano.Naive) { NaiveBayes naive = new NaiveBayes(); naive.buildClassifier(baseTeste); avaliacao.crossValidateModel(naive, baseTeste, (plano.eHoldOut) ? 4 : baseTeste.numInstances(), rand); Resultado resultado = new Resultado("Naive", avaliacao.toMatrixString("Algortmo NaiveBayes - Matriz de Confuso"), avaliacao.toClassDetailsString("kNN")); resultado.setTaxaErro(avaliacao.errorRate()); resultado.setTaxaAcerto(1 - avaliacao.errorRate()); resultado.setRevocacao(recallToDouble(avaliacao, baseTeste)); resultado.setPrecisao(precisionToDouble(avaliacao, baseTeste)); this.resultados.add(resultado); } if (plano.Tree) { try { Id3 id3 = new Id3(); id3.buildClassifier(baseTeste); avaliacao.crossValidateModel(id3, baseTeste, (plano.eHoldOut) ? 4 : baseTeste.numInstances(), rand); Resultado resultado = new Resultado("ID3", avaliacao.toMatrixString("Algortmo ID3 - Matriz de Confuso"), avaliacao.toClassDetailsString("kNN")); resultado.setTaxaErro(avaliacao.errorRate()); resultado.setTaxaAcerto(1 - avaliacao.errorRate()); resultado.setRevocacao(recallToDouble(avaliacao, baseTeste)); resultado.setPrecisao(precisionToDouble(avaliacao, baseTeste)); this.resultados.add(resultado); } catch (UnsupportedAttributeTypeException ex) { Mensagem.erro("Algortmo Arvore de Deciso no suporta atributos numricos!", "MTCS - ERRO"); } } } catch (FileNotFoundException ex) { Logger.getLogger(Classificador.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Classificador.class.getName()).log(Level.SEVERE, null, ex); } catch (NullPointerException ex) { Mensagem.erro("Selecione um arquivo para comear!", "MTCS - ERRO"); Logger.getLogger(Classificador.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(Classificador.class.getName()).log(Level.SEVERE, null, ex); } return this.resultados; }
From source file:controller.BothClassificationsServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String dir = "/data/"; String path = getServletContext().getRealPath(dir); String action = request.getParameter("action"); switch (action) { case "create": { String fileName = request.getParameter("file"); String aux = fileName.substring(0, fileName.indexOf(".")); String pathInput = path + "/" + request.getParameter("file"); String pathTrainingOutput = path + "/" + aux + "-training-arff.txt"; String pathTestOutput = path + "/" + aux + "-test-arff.txt"; String pathBothClassifications = path + "/" + aux + "-bothClassifications.txt"; String name = request.getParameter("name"); int range = Integer.parseInt(request.getParameter("range")); int size = Integer.parseInt(request.getParameter("counter")); String[] columns = new String[size]; String[] types = new String[size]; int[] positions = new int[size]; int counter = 0; for (int i = 0; i < size; i++) { if (request.getParameter("column-" + (i + 1)) != null) { columns[counter] = request.getParameter("column-" + (i + 1)); types[counter] = request.getParameter("type-" + (i + 1)); positions[counter] = Integer.parseInt(request.getParameter("position-" + (i + 1))); counter++;// w w w . j a va 2 s . c o m } } FormatFiles.convertTxtToArff(pathInput, pathTrainingOutput, pathTestOutput, name, columns, types, positions, counter, range); try { J48 j48 = new J48(); BufferedReader readerTraining = new BufferedReader(new FileReader(pathTrainingOutput)); Instances instancesTraining = new Instances(readerTraining); instancesTraining.setClassIndex(instancesTraining.numAttributes() - 1); j48.buildClassifier(instancesTraining); BufferedReader readerTest = new BufferedReader(new FileReader(pathTestOutput)); //BufferedReader readerTest = new BufferedReader(new FileReader(pathTrainingOutput)); Instances instancesTest = new Instances(readerTest); instancesTest.setClassIndex(instancesTest.numAttributes() - 1); int correctsDecisionTree = 0; for (int i = 0; i < instancesTest.size(); i++) { Instance instance = instancesTest.get(i); double correctValue = instance.value(instance.attribute(instancesTest.numAttributes() - 1)); double classification = j48.classifyInstance(instance); if (correctValue == classification) { correctsDecisionTree++; } } Evaluation eval = new Evaluation(instancesTraining); eval.evaluateModel(j48, instancesTest); PrintWriter writer = new PrintWriter( new BufferedWriter(new FileWriter(pathBothClassifications, false))); writer.println("?rvore de Deciso\n\n"); writer.println(j48.toString()); writer.println(""); writer.println(""); writer.println("Results"); writer.println(eval.toSummaryString()); NaiveBayes naiveBayes = new NaiveBayes(); naiveBayes.buildClassifier(instancesTraining); eval = new Evaluation(instancesTraining); eval.evaluateModel(naiveBayes, instancesTest); int correctsNaiveBayes = 0; for (int i = 0; i < instancesTest.size(); i++) { Instance instance = instancesTest.get(i); double correctValue = instance.value(instance.attribute(instancesTest.numAttributes() - 1)); double classification = naiveBayes.classifyInstance(instance); if (correctValue == classification) { correctsNaiveBayes++; } } writer.println("Naive Bayes\n\n"); writer.println(naiveBayes.toString()); writer.println(""); writer.println(""); writer.println("Results"); writer.println(eval.toSummaryString()); writer.close(); response.sendRedirect("BothClassifications?action=view&correctsDecisionTree=" + correctsDecisionTree + "&correctsNaiveBayes=" + correctsNaiveBayes + "&totalTest=" + instancesTest.size() + "&totalTrainig=" + instancesTraining.size() + "&range=" + range + "&fileName=" + aux + "-bothClassifications.txt"); } catch (Exception e) { System.out.println(e.getMessage()); response.sendRedirect("Navigation?action=decisionTree"); } break; } default: response.sendError(404); } }
From source file:Controller.CtlDataMining.java
public String redBayesiana(Instances data) { try {//from w w w.j a v a 2 s .c o m //Creamos un clasificador Bayesiano NaiveBayes nb = new NaiveBayes(); //creamos el clasificador de la redBayesiana nb.buildClassifier(data); //Creamos un objeto para la validacion del modelo con redBayesiana Evaluation evalB = new Evaluation(data); /*Aplicamos el clasificador bayesiano hacemos validacion cruzada, de redBayesiana, con 10 campos, y un aleatorio para la semilla, en este caso es 1 para el muestreo de la validacion cruzada (Como ordenar para luego partirlo en 10)*/ evalB.crossValidateModel(nb, data, 10, new Random(1)); String resBay = "<br><br><b><center>Resultados NaiveBayes</center>" + "<br>========<br>" + "Modelo generado indica los siguientes resultados:" + "<br>========<br></b>"; //Obtenemos resultados resBay = resBay + ("<b>1. Numero de instancias clasificadas:</b> " + (int) evalB.numInstances() + "<br>"); resBay = resBay + ("<b>2. Porcentaje de instancias correctamente " + "clasificadas:</b> " + formato.format(evalB.pctCorrect()) + "%<br>"); resBay = resBay + ("<b>3. Numero de instancias correctamente " + "clasificadas:</b> " + (int) evalB.correct() + "<br>"); resBay = resBay + ("<b>4. Porcentaje de instancias incorrectamente " + "clasificadas:</b> " + formato.format(evalB.pctIncorrect()) + "%<br>"); resBay = resBay + ("<b>5. Numero de instancias incorrectamente " + "clasificadas:</b> " + (int) evalB.incorrect() + "<br>"); resBay = resBay + ("<b>6. Media del error absoluto:</b> " + formato.format(evalB.meanAbsoluteError()) + "%<br>"); resBay = resBay + ("<b>7. " + evalB.toMatrixString("Matriz de " + "confusion</b>").replace("\n", "<br>")); return resBay; } catch (Exception e) { return "El error es" + e.getMessage(); } }
From source file:Controller.CtlDataMining.java
public String arbolJ48(Instances data) { try {//w w w.ja va 2 s. co m // Creamos un clasidicador J48 J48 j48 = new J48(); //creamos el clasificador del J48 con los datos j48.buildClassifier(data); //Creamos un objeto para la validacion del modelo con redBayesiana Evaluation evalJ48 = new Evaluation(data); /*Aplicamos el clasificador J48 hacemos validacion cruzada, de redBayesiana, con 10 campos, y el aleatorio arrancando desde 1 para la semilla*/ evalJ48.crossValidateModel(j48, data, 10, new Random(1)); //Obtenemos resultados String resJ48 = "<br><b><center>Resultados Arbol de decision J48" + "</center><br>========<br>Modelo generado indica los " + "siguientes resultados:<br>========<br></b>"; resJ48 = resJ48 + ("<b>1. Numero de instancias clasificadas:</b> " + (int) evalJ48.numInstances() + "<br>"); resJ48 = resJ48 + ("<b>2. Porcentaje de instancias correctamente " + "clasificadas:</b> " + formato.format(evalJ48.pctCorrect()) + "<br>"); resJ48 = resJ48 + ("<b>3. Numero de instancias correctamente " + "clasificadas:</b>" + (int) evalJ48.correct() + "<br>"); resJ48 = resJ48 + ("<b>4. Porcentaje de instancias incorrectamente " + "clasificadas:</b> " + formato.format(evalJ48.pctIncorrect()) + "<br>"); resJ48 = resJ48 + ("<b>5. Numero de instancias incorrectamente " + "clasificadas:</b> " + (int) evalJ48.incorrect() + "<br>"); resJ48 = resJ48 + ("<b>6. Media del error absoluto:</b> " + formato.format(evalJ48.meanAbsoluteError()) + "<br>"); resJ48 = resJ48 + ("<b>7. " + evalJ48.toMatrixString("Matriz de" + " confusion</b>").replace("\n", "<br>")); // SE GRAFICA EL ARBOL GENERADO //Se crea un Jframe Temporal final javax.swing.JFrame jf = new javax.swing.JFrame("Arbol de decision: J48"); /*Se asigna un tamao*/ jf.setSize(500, 400); /*Se define un borde*/ jf.getContentPane().setLayout(new BorderLayout()); /*Se instancia la grafica del arbol, estableciendo el tipo J48 Parametros (Listener, Tipo de arbol, Tipo de nodos) El placeNode2 colocar los nodos para que caigan en forma uniforme por debajo de su padre*/ TreeVisualizer tv = new TreeVisualizer(null, j48.graph(), new PlaceNode2()); /*Aade el arbol centrandolo*/ jf.getContentPane().add(tv, BorderLayout.CENTER); /*Aadimos un listener para la X del close*/ jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); } }); /*Lo visualizamos*/ jf.setVisible(true); /*Ajustamos el arbol al ancho del JFRM*/ tv.fitToScreen(); return resJ48; } catch (Exception e) { return "El error es" + e.getMessage(); } }
From source file:controller.DecisionTreeServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String dir = "/data/"; String path = getServletContext().getRealPath(dir); String action = request.getParameter("action"); switch (action) { case "create": { String fileName = request.getParameter("file"); String aux = fileName.substring(0, fileName.indexOf(".")); String pathInput = path + "/" + request.getParameter("file"); String pathTrainingOutput = path + "/" + aux + "-training-arff.txt"; String pathTestOutput = path + "/" + aux + "-test-arff.txt"; String pathDecisionTree = path + "/" + aux + "-decisionTree.txt"; String name = request.getParameter("name"); int range = Integer.parseInt(request.getParameter("range")); int size = Integer.parseInt(request.getParameter("counter")); String[] columns = new String[size]; String[] types = new String[size]; int[] positions = new int[size]; int counter = 0; for (int i = 0; i < size; i++) { if (request.getParameter("column-" + (i + 1)) != null) { columns[counter] = request.getParameter("column-" + (i + 1)); types[counter] = request.getParameter("type-" + (i + 1)); positions[counter] = Integer.parseInt(request.getParameter("position-" + (i + 1))); counter++;//from w w w . j a va 2 s . co m } } FormatFiles.convertTxtToArff(pathInput, pathTrainingOutput, pathTestOutput, name, columns, types, positions, counter, range); try { J48 j48 = new J48(); BufferedReader readerTraining = new BufferedReader(new FileReader(pathTrainingOutput)); Instances instancesTraining = new Instances(readerTraining); instancesTraining.setClassIndex(instancesTraining.numAttributes() - 1); j48.buildClassifier(instancesTraining); BufferedReader readerTest = new BufferedReader(new FileReader(pathTestOutput)); //BufferedReader readerTest = new BufferedReader(new FileReader(pathTrainingOutput)); Instances instancesTest = new Instances(readerTest); instancesTest.setClassIndex(instancesTest.numAttributes() - 1); int corrects = 0; int truePositive = 0; int trueNegative = 0; int falsePositive = 0; int falseNegative = 0; for (int i = 0; i < instancesTest.size(); i++) { Instance instance = instancesTest.get(i); double correctValue = instance.value(instance.attribute(instancesTest.numAttributes() - 1)); double classification = j48.classifyInstance(instance); if (correctValue == classification) { corrects++; } if (correctValue == 1 && classification == 1) { truePositive++; } if (correctValue == 1 && classification == 0) { falseNegative++; } if (correctValue == 0 && classification == 1) { falsePositive++; } if (correctValue == 0 && classification == 0) { trueNegative++; } } Evaluation eval = new Evaluation(instancesTraining); eval.evaluateModel(j48, instancesTest); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(pathDecisionTree, false))); writer.println(j48.toString()); writer.println(""); writer.println(""); writer.println("Results"); writer.println(eval.toSummaryString()); writer.close(); response.sendRedirect("DecisionTree?action=view&corrects=" + corrects + "&totalTest=" + instancesTest.size() + "&totalTrainig=" + instancesTraining.size() + "&truePositive=" + truePositive + "&trueNegative=" + trueNegative + "&falsePositive=" + falsePositive + "&falseNegative=" + falseNegative + "&fileName=" + aux + "-decisionTree.txt"); } catch (Exception e) { System.out.println(e.getMessage()); response.sendRedirect("Navigation?action=decisionTree"); } break; } default: response.sendError(404); } }
From source file:controller.NaiveBayesServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String dir = "/data/"; String path = getServletContext().getRealPath(dir); String action = request.getParameter("action"); switch (action) { case "create": { String fileName = request.getParameter("file"); String aux = fileName.substring(0, fileName.indexOf(".")); String pathInput = path + "/" + request.getParameter("file"); String pathTrainingOutput = path + "/" + aux + "-training-arff.txt"; String pathTestOutput = path + "/" + aux + "-test-arff.txt"; String pathNaivebayes = path + "/" + aux + "-naiveBayes.txt"; String name = request.getParameter("name"); int range = Integer.parseInt(request.getParameter("range")); int size = Integer.parseInt(request.getParameter("counter")); String[] columns = new String[size]; String[] types = new String[size]; int[] positions = new int[size]; int counter = 0; for (int i = 0; i < size; i++) { if (request.getParameter("column-" + (i + 1)) != null) { columns[counter] = request.getParameter("column-" + (i + 1)); types[counter] = request.getParameter("type-" + (i + 1)); positions[counter] = Integer.parseInt(request.getParameter("position-" + (i + 1))); counter++;//from w w w .j av a2s. co m } } FormatFiles.convertTxtToArff(pathInput, pathTrainingOutput, pathTestOutput, name, columns, types, positions, counter, range); try { NaiveBayes naiveBayes = new NaiveBayes(); BufferedReader readerTraining = new BufferedReader(new FileReader(pathTrainingOutput)); Instances instancesTraining = new Instances(readerTraining); instancesTraining.setClassIndex(instancesTraining.numAttributes() - 1); naiveBayes.buildClassifier(instancesTraining); BufferedReader readerTest = new BufferedReader(new FileReader(pathTestOutput)); //BufferedReader readerTest = new BufferedReader(new FileReader(pathTrainingOutput)); Instances instancesTest = new Instances(readerTest); instancesTest.setClassIndex(instancesTest.numAttributes() - 1); Evaluation eval = new Evaluation(instancesTraining); eval.evaluateModel(naiveBayes, instancesTest); int corrects = 0; int truePositive = 0; int trueNegative = 0; int falsePositive = 0; int falseNegative = 0; for (int i = 0; i < instancesTest.size(); i++) { Instance instance = instancesTest.get(i); double correctValue = instance.value(instance.attribute(instancesTest.numAttributes() - 1)); double classification = naiveBayes.classifyInstance(instance); if (correctValue == classification) { corrects++; } if (correctValue == 1 && classification == 1) { truePositive++; } if (correctValue == 1 && classification == 0) { falseNegative++; } if (correctValue == 0 && classification == 1) { falsePositive++; } if (correctValue == 0 && classification == 0) { trueNegative++; } } PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(pathNaivebayes, false))); writer.println(naiveBayes.toString()); writer.println(""); writer.println(""); writer.println("Results"); writer.println(eval.toSummaryString()); writer.close(); response.sendRedirect( "NaiveBayes?action=view&corrects=" + corrects + "&totalTest=" + instancesTest.size() + "&totalTrainig=" + instancesTraining.size() + "&range=" + range + "&truePositive=" + truePositive + "&trueNegative=" + trueNegative + "&falsePositive=" + falsePositive + "&falseNegative=" + falseNegative + "&fileName=" + aux + "-naiveBayes.txt"); } catch (Exception e) { System.out.println(e.getMessage()); response.sendRedirect("Navigation?action=naiveBayes"); } break; } default: response.sendError(404); } }