List of usage examples for weka.classifiers.trees J48 graph
@Override public String graph() throws Exception
From source file:classif.ExperimentsLauncher.java
License:Open Source License
public void launchJ48() { try {/* w w w . j a va 2 s . c o m*/ String algo = "J48"; System.out.println(algo); double testError = 0.0; J48 dt = new J48(); dt.buildClassifier(train); Evaluation eval = new Evaluation(train); eval.evaluateModel(dt, test); testError = eval.errorRate(); System.out.println("TestError:" + testError + "\n"); System.out.println(dt.toSummaryString()); System.out.println(dt.graph()); System.out.println(eval.toSummaryString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:Controller.CtlDataMining.java
public String arbolJ48(Instances data) { try {// w ww . java 2s. com // 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.DecisionTreeBean.java
public void generateTree(int positiontomine) { System.out.println("Start Generating Tree"); model = new DefaultDiagramModel(); model.setMaxConnections(-1);/*from w ww . j ava 2 s . c o m*/ try { inst.setClassIndex(positiontomine); J48 tree; String[] options = new String[1]; options[0] = "-U"; tree = new J48(); tree.setOptions(options); // set the options tree.buildClassifier(inst); // build classifier dis = inst.toSummaryString(); System.out.println(tree.graph()); System.out.println(tree.toString()); List<String> liNodeStr = new LinkedList<>(); List<String> liConnStr = new LinkedList<>(); liNodeElement = new LinkedList<>(); liConnElement = new LinkedList<>(); BufferedReader br = new BufferedReader(new StringReader(tree.graph())); br.readLine(); String tmp; while ((tmp = br.readLine()) != null) { if (tmp.contains("}")) { break; } else if (tmp.contains("->")) { liConnStr.add(tmp); } else { liNodeStr.add(tmp); } } System.out.println(liConnStr); System.out.println(liNodeStr); for (String s : liNodeStr) { String[] arr = s.split(" "); String entitie1 = arr[0]; arr = s.split("\""); String entitie2 = arr[1]; System.out.println("ID:" + entitie1 + " Name:" + entitie2); TreeElement te = new TreeElement(entitie1, entitie2); liNodeElement.add(te); } for (String s : liConnStr) { String[] arr = s.split(" "); arr = arr[0].split("->"); String from = arr[0]; String to = arr[1]; arr = s.split("\""); String label = arr[1]; System.out.println("From:" + from + " To:" + to + "Label:" + label); TreeConector ce = new TreeConector(from, to, label); liConnElement.add(ce); } //----------------------------------------------------------------------------------------------- for (TreeElement te : liNodeElement) { if (te.getID().equals("N0")) { System.out.println("inside"); genlevel(te, 0); te.setPosition(25); genposition(te, 50); } } for (TreeElement te : liNodeElement) { Element el = new Element(te, te.getPosition() + "em", te.getLevel() * 15 + "em"); el.addEndPoint(new BlankEndPoint(EndPointAnchor.TOP)); el.addEndPoint(new BlankEndPoint(EndPointAnchor.BOTTOM)); model.addElement(el); } List<Element> ellist = model.getElements(); for (TreeConector tc : liConnElement) { Element beginn = null; for (Element e : ellist) { TreeElement t; t = (TreeElement) e.getData(); if (t.getID().equals(tc.getFrom())) { beginn = e; break; } } Element endeee = null; for (Element e : ellist) { TreeElement t; t = (TreeElement) e.getData(); if (t.getID().equals(tc.getTo())) { endeee = e; break; } } StraightConnector connector = new StraightConnector(); connector.setPaintStyle("{strokeStyle:'#F28D2A', lineWidth:3}"); connector.setHoverPaintStyle("{strokeStyle:'#F28D2A'}"); Connection con = new Connection(beginn.getEndPoints().get(1), endeee.getEndPoints().get(0), connector); con.getOverlays().add(new LabelOverlay(tc.getLabel(), "flow-label", 0.5)); model.connect(con); } } catch (Exception ex) { Logger.getLogger(DecisionTreeBean.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:coreferenceresolver.gui.WekaTreeGUI.java
/** * Creates new form WekaTreeGUI/*from w ww .j a va2s . c om*/ */ public WekaTreeGUI(J48 tree) throws Exception { initComponents(); this.tree = tree; // display classifier this.setTitle("Weka Classifier Tree Visualizer: J48"); this.setExtendedState(JFrame.MAXIMIZED_BOTH); this.getContentPane().setLayout(new BorderLayout()); TreeVisualizer tv = new TreeVisualizer(null, tree.graph(), new PlaceNode2()); this.getContentPane().add(tv, BorderLayout.CENTER); this.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { WekaTreeGUI.this.dispose(); } }); tv.fitToScreen(); }
From source file:meddle.TrainModelByDomainOS.java
License:Open Source License
/** * Given a classifier model, print out the tree graph and its html report. * * @param j48/* ww w . j a v a 2 s .c om*/ * - the classifier model * @param domainOS * - domain,os name * @param mem * - the measurement results * */ public static void doGraphicOutput(J48 j48, String domainOS, MetaEvaluationMeasures mem) { try { String on = RConfig.dtGraphFolder + domainOS + ".dot"; String png = RConfig.dtGraphFolder + domainOS + ".png"; BufferedWriter bw = new BufferedWriter(new FileWriter(on)); bw.write(j48.graph()); bw.close(); String sum = "<h3>" + mem.info.domain + "(" + mem.info.OS + ")</h3>\n"; sum += "Accuracy: " + mem.accuracy + "<br/> \n"; sum += "AUC: " + mem.AUC + "<br/> \n"; sum += "False Positive Rate: " + mem.falsePositiveRate + "<br/> \n"; sum += "False Negative Rate: " + mem.falseNegativeRate + "<br/> <br/> \n"; sum += "Initial Number of Samples: " + mem.info.initNumTotal + "<br/>\n"; sum += "Initial Number of Positive: " + mem.info.initNumPos + "<br/>\n"; sum += "Initial Number of Negative: " + mem.info.initNumNeg + "<br/><br/>\n"; sum += ">>> After balancing ...<br/> \n"; sum += "Trained Number of Samples: " + mem.numTotal + "<br/>\n"; sum += "Trained Number of Positive: " + mem.numPositive + "<br/>\n"; sum += "Trained Number of Negative: " + mem.numNegative + "<br/></br/>\n"; sum += "<img src='" + domainOS + ".png'/><br/> <br/> \n"; sum += j48.toString().replace("\n", "<br/>"); sum += "Number of Rules: " + j48.measureNumRules() + "<br/>\n"; sum += "<a href='../domain_os/" + mem.info.fileNameRelative + "'>training data</a>"; sum = "<html><body>" + sum; sum += "</body></html>"; String cmd = RConfig.DOT_PATH + " -o " + png + " " + on + " -Tpng"; // http://www.graphviz.org/content/output-formats#ddot // need to install graphviz tool // Mac OX: brew install graphviz // Ubuntu: sudo apt-get install graphviz String html = RConfig.dtGraphFolder + domainOS + ".html"; bw = new BufferedWriter(new FileWriter(html)); bw.write(sum); bw.close(); Runtime.getRuntime().exec(cmd); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
From source file:rdfsystem.data.DataMining.java
public static String classify(RdfManager manager) throws Exception { Instances ins = transformData(manager, true); ins.setClassIndex(ins.attribute("year").index()); J48 tree = new J48(); tree.buildClassifier(ins);/*from w w w .j a v a 2 s . c o m*/ return tree.graph(); }