List of usage examples for weka.filters.unsupervised.attribute Add setNominalLabels
public void setNominalLabels(String labelList)
From source file:classifyfromimage.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.name3 = IJ.getImage().getTitle(); this.name4 = this.name3.replaceFirst("[.][^.]+$", ""); System.out.println("hola " + this.name4); selectWindow(this.name3); System.out.println(this.name4); System.out.println(this.name3); RoiManager rm = RoiManager.getInstance(); IJ.run("Duplicate...", this.name3); IJ.run("Set Measurements...", "area perimeter fit shape limit scientific redirect=None decimal=5"); selectWindow(this.name3); IJ.run("Subtract Background...", "rolling=1.5"); IJ.run("Enhance Contrast...", "saturated=25 equalize"); IJ.run("Subtract Background...", "rolling=1.5"); IJ.run("Convolve...", "text1=[-1 -3 -4 -3 -1\n-3 0 6 0 -3\n-4 6 50 6 -4\n-3 0 6 0 -3\n-1 -3 -4 -3 -1\n] normalize"); IJ.run("8-bit", ""); IJ.run("Restore Selection", ""); IJ.run("Make Binary", ""); Prefs.blackBackground = false;//from w w w . j av a2s .co m IJ.run("Convert to Mask", ""); IJ.run("Restore Selection", ""); this.valor1 = this.interval3.getText(); this.valor2 = this.interval4.getText(); System.out.println("VECTOR-> punctua: " + this.valor1 + " " + this.valor2); this.text = "size=" + this.valor1 + "-" + this.valor2 + " pixel show=Outlines display include summarize add"; IJ.run("Analyze Particles...", this.text); IJ.saveAs("tif", this.name3 + "_processed"); String dest_filename1, dest_filename2, full; selectWindow("Results"); //dest_filename1 = this.name2 + "_complete.txt"; dest_filename2 = this.name3 + "_complete.csv"; //IJ.saveAs("Results", prova + File.separator + dest_filename1); IJ.run("Input/Output...", "jpeg=85 gif=-1 file=.csv copy_row save_column save_row"); //IJ.saveAs("Results", dir + File.separator + dest_filename2); IJ.saveAs("Results", this.name3 + "_complete.csv"); IJ.run("Restore Selection"); IJ.run("Clear Results"); //txtarea.setText("Converting, please wait... "); try { CSVLoader loader = new CSVLoader(); loader.setSource(new File(this.name3 + "_complete.csv")); Instances data = loader.getDataSet(); System.out.println(data); // save ARFF String arffile = this.name3 + ".arff"; System.out.println(arffile); ArffSaver saver = new ArffSaver(); saver.setInstances(data); saver.setFile(new File(arffile)); saver.writeBatch(); } catch (IOException ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } //txtdata2.setText(this.name3); //txtarea.setText("Succesfully converted " + this.name3); //txtarea.setText("Analysing your data, please wait... "); Instances data; try { data = new Instances(new BufferedReader(new FileReader(this.name3 + ".arff"))); Instances newData = null; Add filter; newData = new Instances(data); filter = new Add(); filter.setAttributeIndex("last"); filter.setNominalLabels("rods,punctua,networks"); filter.setAttributeName("target"); filter.setInputFormat(newData); newData = Filter.useFilter(newData, filter); System.out.print(newData); Vector vec = new Vector(); newData.setClassIndex(newData.numAttributes() - 1); if (!newData.equalHeaders(newData)) { throw new IllegalArgumentException("Train and test are not compatible!"); } URL urlToModel = this.getClass().getResource("/" + "Final.model"); InputStream stream = urlToModel.openStream(); Classifier cls = (Classifier) weka.core.SerializationHelper.read(stream); System.out.println("PROVANT MODEL.classifyInstance"); for (int i = 0; i < newData.numInstances(); i++) { double pred = cls.classifyInstance(newData.instance(i)); double[] dist = cls.distributionForInstance(newData.instance(i)); System.out.print((i + 1) + " - "); System.out.print(newData.classAttribute().value((int) pred) + " - "); //txtarea2.setText(Utils.arrayToString(dist)); System.out.println(Utils.arrayToString(dist)); vec.add(newData.classAttribute().value((int) pred)); } int p = 0, n = 0, r = 0; //txtarea2.append(Utils.arrayToString(this.target)); for (Object vec1 : vec) { if ("rods".equals(vec1.toString())) { r = r + 1; } if ("punctua".equals(vec1.toString())) { p = p + 1; } if ("networks".equals(vec1.toString())) { n = n + 1; } PrintWriter out = null; try { out = new PrintWriter(this.name3 + "_morphology.txt"); out.println(vec); out.close(); } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(vec.get(i)); } System.out.println("VECTOR-> punctua: " + p + ", rods: " + r + ", networks: " + n); IJ.showMessage( "Your file:" + this.name3 + "arff" + "\nhas been analysed, and it is composed by-> punctua: " + p + ", rods: " + r + ", networks: " + n); this.txtarea2.setText( "Your file:" + this.name3 + ".arff" + "\nhas been analysed, and it is composed by-> punctua: " + p + ", rods: " + r + ", networks: " + n); A_MachineLearning nf1 = new A_MachineLearning(); A_MachineLearning.txtresults1.setText(this.txtarea2.getText()); A_MachineLearning.txtresults1.setText(this.txtarea2.getText()); A_MachineLearning.txtresults1.setText(this.txtarea2.getText()); A_MachineLearning.txtresults1.append(this.txtarea2.getText()); A_MachineLearning.txtresults1.append(this.txtarea2.getText()); A_MachineLearning.txtresults1.append(this.txtarea2.getText()); nf1.setVisible(true); } catch (IOException ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } IJ.run("Clear Results"); //IJ.RoiManager("Delete"); IJ.run("Clear Results"); IJ.run("Close All", ""); if (WindowManager.getFrame("Results") != null) { IJ.selectWindow("Results"); IJ.run("Close"); } if (WindowManager.getFrame("Summary") != null) { IJ.selectWindow("Summary"); IJ.run("Close"); } if (WindowManager.getFrame("Results") != null) { IJ.selectWindow("Results"); IJ.run("Close"); } if (WindowManager.getFrame("ROI Manager") != null) { IJ.selectWindow("ROI Manager"); IJ.run("Close"); } IJ.run("Close All", "roiManager"); IJ.run("Close All", ""); setVisible(false); dispose();// TODO add your handling code here: setVisible(false); dispose();// TODO add your handling code here: // TODO add your handling code here: }
From source file:A_MachineLearning.java
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed Instances data;/*from ww w. j ava 2s.c o m*/ try { data = new Instances(new BufferedReader(new FileReader(this.file2 + ".arff"))); Instances newData = null; Add filter; newData = new Instances(data); filter = new Add(); filter.setAttributeIndex("last"); filter.setNominalLabels("rods,punctua,networks"); filter.setAttributeName("target"); filter.setInputFormat(newData); newData = Filter.useFilter(newData, filter); System.out.print(newData); Vector vec = new Vector(); newData.setClassIndex(newData.numAttributes() - 1); if (!newData.equalHeaders(newData)) { throw new IllegalArgumentException("Train and test are not compatible!"); } URL urlToModel = this.getClass().getResource("/" + "Final.model"); InputStream stream = urlToModel.openStream(); Classifier cls = (Classifier) weka.core.SerializationHelper.read(stream); System.out.println("PROVANT MODEL.classifyInstance"); for (int i = 0; i < newData.numInstances(); i++) { double pred = cls.classifyInstance(newData.instance(i)); double[] dist = cls.distributionForInstance(newData.instance(i)); System.out.print((i + 1) + " - "); System.out.print(newData.classAttribute().value((int) pred) + " - "); //txtarea2.setText(Utils.arrayToString(dist)); System.out.println(Utils.arrayToString(dist)); vec.add(newData.classAttribute().value((int) pred)); } int p = 0, n = 0, r = 0; //txtarea2.append(Utils.arrayToString(this.target)); for (Object vec1 : vec) { if ("rods".equals(vec1.toString())) { r = r + 1; } if ("punctua".equals(vec1.toString())) { p = p + 1; } if ("networks".equals(vec1.toString())) { n = n + 1; } PrintWriter out = null; try { out = new PrintWriter(this.file2 + "_morphology.txt"); out.println(vec); out.close(); } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(vec.get(i)); } System.out.println("VECTOR-> punctua: " + p + ", rods: " + r + ", networks: " + n); IJ.showMessage( "Your file:" + this.file2 + "arff" + "\nhas been analysed, and it is composed by-> punctua: " + p + ", rods: " + r + ", networks: " + n); txtresults1.setText( "Your file:" + this.file2 + "arff" + "\nhas been analysed, and it is composed by: \npunctua: " + p + ", rods: " + r + ", networks: " + n); } catch (IOException ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } IJ.showMessage("analysing complete "); }
From source file:classificationPLugin.java
private void ClassifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClassifyActionPerformed this.name = txtdirecotry2.getText(); System.out.println(this.name); try {// ww w . ja va 2 s . c o m CSVLoader loader = new CSVLoader(); loader.setSource(new File(this.name)); Instances data = loader.getDataSet(); System.out.println(data); // save ARFF String arffile = this.name + ".arff"; System.out.println(arffile); ArffSaver saver = new ArffSaver(); saver.setInstances(data); saver.setFile(new File(arffile)); saver.writeBatch(); } catch (IOException ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } try { FileReader reader = new FileReader(this.name + ".arff"); BufferedReader br = new BufferedReader(reader); instance.read(br, null); br.close(); instance.requestFocus(); } catch (Exception e2) { System.out.println(e2); } Instances data; try { data = new Instances(new BufferedReader(new FileReader(this.name + ".arff"))); Instances newData = null; Add filter; newData = new Instances(data); filter = new Add(); filter.setAttributeIndex("last"); filter.setNominalLabels("rods,punctua,networks"); filter.setAttributeName("target"); filter.setInputFormat(newData); newData = Filter.useFilter(newData, filter); System.out.print(newData); Vector vec = new Vector(); newData.setClassIndex(newData.numAttributes() - 1); if (!newData.equalHeaders(newData)) { throw new IllegalArgumentException("Train and test are not compatible!"); } URL urlToModel = this.getClass().getResource("/" + "Final.model"); InputStream stream = urlToModel.openStream(); Classifier cls = (Classifier) weka.core.SerializationHelper.read(stream); System.out.println("PROVANT MODEL.classifyInstance"); for (int i = 0; i < newData.numInstances(); i++) { double pred = cls.classifyInstance(newData.instance(i)); double[] dist = cls.distributionForInstance(newData.instance(i)); System.out.print((i + 1) + " - "); System.out.print(newData.classAttribute().value((int) pred) + " - "); //txtarea2.setText(Utils.arrayToString(dist)); System.out.println(Utils.arrayToString(dist)); vec.add(newData.classAttribute().value((int) pred)); } int p = 0, n = 0, r = 0; //txtarea2.append(Utils.arrayToString(this.target)); for (Object vec1 : vec) { if ("rods".equals(vec1.toString())) { r = r + 1; } if ("punctua".equals(vec1.toString())) { p = p + 1; } if ("networks".equals(vec1.toString())) { n = n + 1; } PrintWriter out = null; try { out = new PrintWriter(this.name + "_morphology.txt"); out.println(vec); out.close(); } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(vec.get(i)); } System.out.println("VECTOR-> punctua: " + p + ", rods: " + r + ", networks: " + n); IJ.showMessage( "Your file:" + this.name + "arff" + "\nhas been analysed, and it is composed by-> \npunctua: " + p + ", rods: " + r + ", networks: " + n); classi.setText( "Your file:" + this.name + "arff" + "\nhas been analysed, and it is composed by: \npunctua: " + p + ", rods: " + r + ", networks: " + n); } catch (IOException ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } IJ.run("Clear Results"); IJ.run("Clear Results"); IJ.run("Close All", ""); if (WindowManager.getFrame("Results") != null) { IJ.selectWindow("Results"); IJ.run("Close"); } if (WindowManager.getFrame("Summary") != null) { IJ.selectWindow("Summary"); IJ.run("Close"); } if (WindowManager.getFrame("Results") != null) { IJ.selectWindow("Results"); IJ.run("Close"); } if (WindowManager.getFrame("ROI Manager") != null) { IJ.selectWindow("ROI Manager"); IJ.run("Close"); } IJ.run("Close All", "roiManager"); IJ.run("Close All", ""); }
From source file:dialog1.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try {// w w w . j ava 2s . co m CSVLoader loader = new CSVLoader(); loader.setSource(new File(txtfilename.getText() + "_complete.csv")); Instances data = loader.getDataSet(); System.out.println(data); // save ARFF String arffile = this.name3 + ".arff"; System.out.println(arffile); ArffSaver saver = new ArffSaver(); saver.setInstances(data); saver.setFile(new File(arffile)); saver.writeBatch(); } catch (IOException ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } Instances data; try { data = new Instances(new BufferedReader(new FileReader(this.name3 + ".arff"))); Instances newData = null; Add filter; newData = new Instances(data); filter = new Add(); filter.setAttributeIndex("last"); filter.setNominalLabels("rods,punctua,networks"); filter.setAttributeName("target"); filter.setInputFormat(newData); newData = Filter.useFilter(newData, filter); System.out.print(newData); Vector vec = new Vector(); newData.setClassIndex(newData.numAttributes() - 1); if (!newData.equalHeaders(newData)) { throw new IllegalArgumentException("Train and test are not compatible!"); } /*URL urlToModel = this.getClass().getResource("/" + "Final.model"); InputStream stream = urlToModel.openStream();*/ InputStream stream = this.getClass().getResourceAsStream("/" + "Final.model"); Classifier cls = (Classifier) weka.core.SerializationHelper.read(stream); System.out.println("PROVANT MODEL.classifyInstance"); for (int i = 0; i < newData.numInstances(); i++) { double pred = cls.classifyInstance(newData.instance(i)); double[] dist = cls.distributionForInstance(newData.instance(i)); System.out.print((i + 1) + " - "); System.out.print(newData.classAttribute().value((int) pred) + " - "); //txtarea2.setText(Utils.arrayToString(dist)); System.out.println(Utils.arrayToString(dist)); vec.add(newData.classAttribute().value((int) pred)); //txtarea2.append(Utils.arrayToString(newData.classAttribute().value((int) pred))); //this.target2.add((i + 1) + " -); //this.target.add(newData.classAttribute().value((int) pred)); //for (String s : this.list) { //this.target2 += s + ","; } int p = 0, n = 0, r = 0; //txtarea2.append(Utils.arrayToString(this.target)); for (Object vec1 : vec) { if ("rods".equals(vec1.toString())) { r = r + 1; } if ("punctua".equals(vec1.toString())) { p = p + 1; } if ("networks".equals(vec1.toString())) { n = n + 1; } PrintWriter out = null; try { out = new PrintWriter(this.name3 + "_morphology.txt"); out.println(vec); out.close(); } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(vec.get(i)); } System.out.println("VECTOR-> punctua: " + p + ", rods: " + r + ", networks: " + n); IJ.showMessage( "Your file:" + this.name3 + "arff" + "\nhas been analysed, and it is composed by-> punctua: " + p + ", rods: " + r + ", networks: " + n); //txtarea2.setText("Your file:" + this.name3 + ".arff" //+ "\nhas been analysed, and it is composed by-> punctua: " + p + ", rods: " + r + ", networks: " + n //+ "\n" //+ "\nAnalyse complete"); //txtarea.setText("Analyse complete"); } catch (IOException ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } IJ.run("Clear Results"); IJ.run("Clear Results"); IJ.run("Close All", ""); if (WindowManager.getFrame("Results") != null) { IJ.selectWindow("Results"); IJ.run("Close"); } if (WindowManager.getFrame("Summary") != null) { IJ.selectWindow("Summary"); IJ.run("Close"); } if (WindowManager.getFrame("Results") != null) { IJ.selectWindow("Results"); IJ.run("Close"); } if (WindowManager.getFrame("ROI Manager") != null) { IJ.selectWindow("ROI Manager"); IJ.run("Close"); } IJ.run("Close All", "roiManager"); IJ.run("Close All", ""); setVisible(false); dispose();// TODO add your handling code here: setVisible(false); dispose();// TODO add your handling code here: // TODO add your handling code here: }
From source file:classifyfromimage1.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed selectWindow(this.name3); this.name3 = IJ.getImage().getTitle(); this.name4 = this.name3.replaceFirst("[.][^.]+$", ""); RoiManager rm = RoiManager.getInstance(); IJ.run("Duplicate...", this.name4); IJ.run("Set Measurements...", "area perimeter fit shape limit scientific redirect=None decimal=5"); selectWindow(this.name3); IJ.run("Subtract Background...", "rolling=1.5"); IJ.run("Enhance Contrast...", "saturated=25 equalize"); IJ.run("Subtract Background...", "rolling=1.5"); IJ.run("Convolve...", "text1=[-1 -3 -4 -3 -1\n-3 0 6 0 -3\n-4 6 50 6 -4\n-3 0 6 0 -3\n-1 -3 -4 -3 -1\n] normalize"); IJ.run("8-bit", ""); IJ.run("Restore Selection", ""); IJ.run("Make Binary", ""); Prefs.blackBackground = false;//from w ww . jav a2s . co m IJ.run("Convert to Mask", ""); IJ.run("Restore Selection", ""); this.valor1 = this.interval3.getText(); this.valor2 = this.interval4.getText(); this.text = "size=" + this.valor1 + "-" + this.valor2 + " pixel show=Outlines display include summarize add"; IJ.saveAs("tif", this.name3 + "_processed"); String dest_filename1, dest_filename2, full; selectWindow("Results"); //dest_filename1 = this.name2 + "_complete.txt"; dest_filename2 = this.name3 + "_complete.csv"; //IJ.saveAs("Results", prova + File.separator + dest_filename1); IJ.run("Input/Output...", "jpeg=85 gif=-1 file=.csv copy_row save_column save_row"); //IJ.saveAs("Results", dir + File.separator + dest_filename2); IJ.saveAs("Results", this.name3 + "_complete.csv"); IJ.run("Restore Selection"); IJ.run("Clear Results"); try { CSVLoader loader = new CSVLoader(); loader.setSource(new File(this.name3 + "_complete.csv")); Instances data = loader.getDataSet(); System.out.println(data); // save ARFF String arffile = this.name3 + ".arff"; System.out.println(arffile); ArffSaver saver = new ArffSaver(); saver.setInstances(data); saver.setFile(new File(arffile)); saver.writeBatch(); } catch (IOException ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } Instances data; try { data = new Instances(new BufferedReader(new FileReader(this.name3 + ".arff"))); Instances newData = null; Add filter; newData = new Instances(data); filter = new Add(); filter.setAttributeIndex("last"); filter.setNominalLabels(txtlabel.getText()); filter.setAttributeName(txtpath2.getText()); filter.setInputFormat(newData); newData = Filter.useFilter(newData, filter); System.out.print(newData); Vector vec = new Vector(); newData.setClassIndex(newData.numAttributes() - 1); if (!newData.equalHeaders(newData)) { throw new IllegalArgumentException("Train and test are not compatible!"); } Classifier cls = (Classifier) weka.core.SerializationHelper.read(txtpath.getText()); System.out.println("PROVANT MODEL.classifyInstance"); for (int i = 0; i < newData.numInstances(); i++) { double pred = cls.classifyInstance(newData.instance(i)); double[] dist = cls.distributionForInstance(newData.instance(i)); System.out.print((i + 1) + " - "); System.out.print(newData.classAttribute().value((int) pred) + " - "); //txtarea2.setText(Utils.arrayToString(dist)); System.out.println(Utils.arrayToString(dist)); vec.add(newData.classAttribute().value((int) pred)); //txtarea2.append(Utils.arrayToString(dist)); classif.add(newData.classAttribute().value((int) pred)); } classif.removeAll(Arrays.asList("", null)); System.out.println(classif); String vecstring = ""; for (Object s : classif) { vecstring += s + ","; System.out.println("Hola " + vecstring); } Map<String, Integer> seussCount = new HashMap<String, Integer>(); for (String t : classif) { Integer i = seussCount.get(t); if (i == null) { i = 0; } seussCount.put(t, i + 1); } String s = vecstring; int counter = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '$') { counter++; } } System.out.println(seussCount); System.out.println("hola " + counter++); IJ.showMessage("Your file:" + this.name3 + "arff" + "\n is composed by" + seussCount); txtpath2.setText("Your file:" + this.name3 + "arff" + "\n is composed by" + seussCount); A_MachineLearning nf2 = new A_MachineLearning(); A_MachineLearning.txtresult2.append(this.txtpath2.getText()); nf2.setVisible(true); } catch (Exception ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } IJ.run("Close All", ""); if (WindowManager.getFrame("Results") != null) { IJ.selectWindow("Results"); IJ.run("Close"); } if (WindowManager.getFrame("Summary") != null) { IJ.selectWindow("Summary"); IJ.run("Close"); } if (WindowManager.getFrame("Results") != null) { IJ.selectWindow("Results"); IJ.run("Close"); } if (WindowManager.getFrame("ROI Manager") != null) { IJ.selectWindow("ROI Manager"); IJ.run("Close"); } setVisible(false); dispose();// TODO add your handling code here: // TODO add your handling code here: }
From source file:MachinLearningInterface.java
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed Instances data;/*from w w w . j a va 2 s . c o m*/ try { data = new Instances(new BufferedReader(new FileReader(this.name3 + ".arff"))); Instances newData = null; Add filter; newData = new Instances(data); filter = new Add(); filter.setAttributeIndex("last"); filter.setNominalLabels("rods,punctua,networks"); filter.setAttributeName("target"); filter.setInputFormat(newData); newData = Filter.useFilter(newData, filter); System.out.print(newData); Vector vec = new Vector(); newData.setClassIndex(newData.numAttributes() - 1); if (!newData.equalHeaders(newData)) { throw new IllegalArgumentException("Train and test are not compatible!"); } URL urlToModel = this.getClass().getResource("/" + "Final.model"); InputStream stream = urlToModel.openStream(); Classifier cls = (Classifier) weka.core.SerializationHelper.read(stream); System.out.println("PROVANT MODEL.classifyInstance"); for (int i = 0; i < newData.numInstances(); i++) { double pred = cls.classifyInstance(newData.instance(i)); double[] dist = cls.distributionForInstance(newData.instance(i)); System.out.print((i + 1) + " - "); System.out.print(newData.classAttribute().value((int) pred) + " - "); //txtarea2.setText(Utils.arrayToString(dist)); System.out.println(Utils.arrayToString(dist)); vec.add(newData.classAttribute().value((int) pred)); } int p = 0, n = 0, r = 0; //txtarea2.append(Utils.arrayToString(this.target)); for (Object vec1 : vec) { if ("rods".equals(vec1.toString())) { r = r + 1; } if ("punctua".equals(vec1.toString())) { p = p + 1; } if ("networks".equals(vec1.toString())) { n = n + 1; } PrintWriter out = null; try { out = new PrintWriter(this.name3 + "_morphology.txt"); out.println(vec); out.close(); } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(vec.get(i)); } System.out.println("VECTOR-> punctua: " + p + ", rods: " + r + ", networks: " + n); IJ.showMessage( "Your file:" + this.name3 + "arff" + "\nhas been analysed, and it is composed by-> punctua: " + p + ", rods: " + r + ", networks: " + n); } catch (IOException ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } IJ.showMessage("analysing complete "); }
From source file:MachinLearningInterface.java
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed Instances data;// w w w .j av a2s .com try { data = new Instances(new BufferedReader(new FileReader(this.name3 + ".arff"))); Instances newData = null; Add filter; newData = new Instances(data); filter = new Add(); filter.setAttributeIndex("last"); filter.setNominalLabels(this.liststring); filter.setAttributeName("target"); filter.setInputFormat(newData); newData = Filter.useFilter(newData, filter); System.out.print(newData); Vector vec = new Vector(); newData.setClassIndex(newData.numAttributes() - 1); if (!newData.equalHeaders(newData)) { throw new IllegalArgumentException("Train and test are not compatible!"); } Classifier cls = (Classifier) weka.core.SerializationHelper.read(this.model); System.out.println("PROVANT MODEL.classifyInstance"); for (int i = 0; i < newData.numInstances(); i++) { double pred = cls.classifyInstance(newData.instance(i)); double[] dist = cls.distributionForInstance(newData.instance(i)); System.out.print((i + 1) + " - "); System.out.print(newData.classAttribute().value((int) pred) + " - "); //txtarea2.setText(Utils.arrayToString(dist)); System.out.println(Utils.arrayToString(dist)); vec.add(newData.classAttribute().value((int) pred)); //txtarea2.append(Utils.arrayToString(dist)); } URL urlToModel = this.getClass().getResource("/" + "Final.model"); InputStream stream = urlToModel.openStream(); Classifier cls2 = (Classifier) weka.core.SerializationHelper.read(stream); System.out.println("PROVANT MODEL.classifyInstance"); for (int i = 0; i < newData.numInstances(); i++) { double pred = cls2.classifyInstance(newData.instance(i)); double[] dist = cls2.distributionForInstance(newData.instance(i)); System.out.print((i + 1) + " - "); System.out.print(newData.classAttribute().value((int) pred) + " - "); //txtarea2.setText(Utils.arrayToString(dist)); System.out.println(Utils.arrayToString(dist)); vec.add(newData.classAttribute().value((int) pred)); } int p = 0, n = 0, r = 0; //txtarea2.append(Utils.arrayToString(this.target)); for (Object vec1 : vec) { if ("rods".equals(vec1.toString())) { r = r + 1; } if ("punctua".equals(vec1.toString())) { p = p + 1; } if ("networks".equals(vec1.toString())) { n = n + 1; } PrintWriter out = null; try { out = new PrintWriter(this.name3 + "_morphology.txt"); out.println(vec); out.close(); } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(vec.get(i)); } System.out.println("VECTOR-> punctua: " + p + ", rods: " + r + ", networks: " + n); IJ.showMessage( "Your file:" + this.name3 + "arff" + "\nhas been analysed, and it is composed by-> punctua: " + p + ", rods: " + r + ", networks: " + n); //txtarea2.setText("Your file:" + this.name3 + ".arff" //+ "\nhas been analysed, and it is composed by-> punctua: " + p + ", rods: " + r + ", networks: " + n //+ "\n" //+ "\nAnalyse complete"); //txtarea.setText("Analyse complete"); } catch (IOException ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } IJ.showMessage("analysing complete "); // TODO add your handling code here: // TODO add your handling code here: }
From source file:A_AdvanceMachineLearning.java
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed UIManager.put("OptionPane.yesButtonText", "Confirm"); UIManager.put("OptionPane.noButtonText", "Cancel"); int dialogButton = JOptionPane.YES_NO_OPTION; int dialogResult = JOptionPane.showConfirmDialog(this, "The labels must be the same used in the weka model", "Advance Machine learning", dialogButton, JOptionPane.WARNING_MESSAGE); if (dialogResult == 0) { this.list.clear(); //txtcodigo1.setText("hola"); this.valor = txtcodigo1.getText(); this.valor1 = txtcodigo2.getText(); this.valor2 = txtcodigo3.getText(); this.valor3 = txtcodigo4.getText(); this.valor4 = txtcodigo5.getText(); this.valor5 = txtcodigo6.getText(); //IJ.showMessage("your label 1 is = "+valor+", "+valor1+", "+valor2+", "+valor3+", "+valor4); // Array list this.list.add(this.valor); this.list.add(this.valor1); this.list.add(this.valor2); this.list.add(this.valor3); this.list.add(this.valor4); this.list.add(this.valor5); this.list.removeAll(Arrays.asList("", null)); System.out.println(this.list); this.liststring = ""; for (String s : this.list) { this.liststring += s + ","; }//w w w . jav a 2s .co m txtlabel.setText(this.liststring); System.out.println(this.liststring); txtarea.setText("Your labels are = " + this.list + "\nThe labels had been saved"); //txtarea.setText("The labels had been saved"); System.out.println(label); } else { System.out.println("No Option"); } Instances data; try { System.out.println(this.file2 + "arff"); FileReader reader = new FileReader(this.file2 + ".arff"); BufferedReader br = new BufferedReader(reader); data = new Instances(br); System.out.println(data); Instances newData = null; Add filter; newData = new Instances(data); filter = new Add(); filter.setAttributeIndex("last"); filter.setNominalLabels(this.liststring); filter.setAttributeName(txtcodigo7.getText()); filter.setInputFormat(newData); newData = Filter.useFilter(newData, filter); System.out.print("hola" + newData); Vector vec = new Vector(); newData.setClassIndex(newData.numAttributes() - 1); if (!newData.equalHeaders(newData)) { throw new IllegalArgumentException("Train and test are not compatible!"); } Classifier cls = (Classifier) weka.core.SerializationHelper.read(this.model); System.out.println("PROVANT MODEL.classifyInstance"); for (int i = 0; i < newData.numInstances(); i++) { double pred = cls.classifyInstance(newData.instance(i)); double[] dist = cls.distributionForInstance(newData.instance(i)); System.out.print((i + 1) + " - "); System.out.print(newData.classAttribute().value((int) pred) + " - "); //txtarea2.setText(Utils.arrayToString(dist)); System.out.println(Utils.arrayToString(dist)); vec.add(newData.classAttribute().value((int) pred)); classif.add(newData.classAttribute().value((int) pred)); } classif.removeAll(Arrays.asList("", null)); System.out.println(classif); String vecstring = ""; for (Object s : classif) { vecstring += s + ","; } Map<String, Integer> seussCount = new HashMap<String, Integer>(); for (String t : classif) { Integer i = seussCount.get(t); if (i == null) { i = 0; } seussCount.put(t, i + 1); } String s = vecstring; String in = vecstring; int i = 0; Pattern p = Pattern.compile(this.valor1); Matcher m = p.matcher(in); while (m.find()) { i++; } System.out.println("hola " + i); // Prints 2 System.out.println(seussCount); txtarea2.append("Your file:" + this.file2 + "arff" + "\n is composed by" + seussCount); IJ.showMessage("Your file:" + this.file2 + "arff" + "\n is composed by" + seussCount); } catch (Exception ex) { Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex); } //IJ.showMessage("analysing complete ");// TODO add your handling code here: }
From source file:adams.flow.transformer.WekaReorderAttributesToReference.java
License:Open Source License
/** * Executes the flow item.// w w w .ja v a 2 s. co m * * @return null if everything is fine, otherwise error message */ @Override protected String doExecute() { String result; Instances dataOld; Instance instOld; Instances dataNew; Instance instNew; Attribute att; int i; StringBuilder order; List<Add> adds; Add add; int index; StringBuilder labels; int n; List<Filter> filters; Reorder reorder; result = null; if (m_OnTheFly && (m_Reference == null)) { result = setUpReference(); if (result != null) return result; } dataNew = null; instNew = null; // get input data if (m_InputToken.getPayload() instanceof Instance) { instOld = (Instance) m_InputToken.getPayload(); dataOld = instOld.dataset(); } else { instOld = null; dataOld = (Instances) m_InputToken.getPayload(); } // do we need to initialize filter? if (m_InitializeOnce || (m_Reorder == null)) { // check incoming data if (!m_Lenient) { for (i = 0; i < m_Reference.numAttributes(); i++) { att = m_Reference.attribute(i); if (dataOld.attribute(att.name()) == null) { if (result == null) result = "Missing attribute(s) in incoming data: " + att.name(); else result += ", " + att.name(); } } if (result != null) getLogger().severe(result); } if (result == null) { try { // determine indices order = new StringBuilder(); adds = new ArrayList<Add>(); for (i = 0; i < m_Reference.numAttributes(); i++) { att = m_Reference.attribute(i); if (dataOld.attribute(att.name()) == null) { index = dataOld.numAttributes() + adds.size(); add = new Add(); add.setAttributeIndex("last"); add.setAttributeName(att.name()); add.setAttributeType(new SelectedTag(att.type(), Add.TAGS_TYPE)); if (att.isNominal()) { labels = new StringBuilder(); for (n = 0; n < att.numValues(); n++) { if (labels.length() > 0) labels.append(","); labels.append(att.value(n)); } add.setNominalLabels(labels.toString()); } adds.add(add); } else { index = dataOld.attribute(att.name()).index(); } if (order.length() > 0) order.append(","); order.append((index + 1)); } // build reorder filter reorder = new Reorder(); reorder.setAttributeIndices(order.toString()); // build multifilter filters = new ArrayList<Filter>(); filters.addAll(adds); filters.add(reorder); m_Reorder = new MultiFilter(); m_Reorder.setFilters(filters.toArray(new Filter[filters.size()])); // initialize filter m_Reorder.setInputFormat(dataOld); } catch (Exception e) { result = handleException("Failed to initialize reorder filter!", e); } } } // reorder data if (result == null) { try { if (instOld != null) { m_Reorder.input(instOld); m_Reorder.batchFinished(); instNew = m_Reorder.output(); if (m_KeepRelationName) instNew.dataset().setRelationName(dataOld.relationName()); } else { dataNew = Filter.useFilter(dataOld, m_Reorder); if (m_KeepRelationName) dataNew.setRelationName(dataOld.relationName()); } } catch (Exception e) { result = handleException("Failed to reorder data!", e); instNew = null; dataNew = null; } } if (instNew != null) m_OutputToken = new Token(instNew); else if (dataNew != null) m_OutputToken = new Token(dataNew); return result; }
From source file:lu.lippmann.cdb.datasetview.tabs.MDSTabView.java
License:Open Source License
/** * {@inheritDoc}//www . ja v a2s .c o m */ @Override public void update0(final Instances dataSet) throws Exception { this.jxp.removeAll(); if (this.distComboListener != null) distCombo.removeActionListener(this.distComboListener); this.distComboListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!currentDist.equals(distCombo.getSelectedItem())) update(dataSet); currentDist = distCombo.getSelectedItem(); final MDSDistancesEnum mde = MDSDistancesEnum.valueOf(currentDist.toString()); boolean showDistanceParameters = (mde.equals(MDSDistancesEnum.MINKOWSKI)); distanceParameters.setVisible(showDistanceParameters); distanceParametersLabel.setVisible(showDistanceParameters); } }; this.distCombo.addActionListener(this.distComboListener); if (this.distanceParametersListener != null) distanceParameters.removeActionListener(this.distanceParametersListener); this.distanceParameters.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!currentParameter.equals(distanceParameters.getText())) update(dataSet); currentParameter = distanceParameters.getText(); } }); this.distanceParameters.addActionListener(this.distanceParametersListener); if (this.shihListener != null) shihCheckbox.removeActionListener(this.shihListener); this.shihListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { update(dataSet); } }; this.shihCheckbox.addActionListener(this.shihListener); this.shihCheckbox.setEnabled(!WekaDataStatsUtil.areAllAttributesNominal(dataSet)); if (this.ignoreListener != null) ignoreClassCheckbox.removeActionListener(this.ignoreListener); this.ignoreListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { update(dataSet); } }; this.ignoreClassCheckbox.addActionListener(this.ignoreListener); this.ignoreClassCheckbox.setEnabled(dataSet.classIndex() != -1); if (this.maxInstancesListener != null) maxInstances.removeKeyListener(this.maxInstancesListener); this.maxInstancesListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { final int cCode = e.getKeyCode(); if (cCode == KeyEvent.VK_ENTER) { update(dataSet); e.consume(); } } }; this.maxInstances.addKeyListener(maxInstancesListener); if (this.normalizeListener != null) normalizeCheckbox.removeActionListener(this.normalizeListener); this.normalizeListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { update(dataSet); } }; this.normalizeCheckbox.addActionListener(this.normalizeListener); //TODO : use proper layout ... final JXPanel northPanel = new JXPanel(); northPanel.setLayout(new GridBagLayout()); final GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.weightx = 1; gbc.fill = GridBagConstraints.BOTH; northPanel.add(this.distCombo, gbc); gbc.weightx = 0; gbc.gridwidth = 1; gbc.gridy = 1; northPanel.add(this.distanceParametersLabel, gbc); gbc.gridx = 1; northPanel.add(this.distanceParameters, gbc); this.jxp.add(northPanel, BorderLayout.NORTH); final MDSDistancesEnum mde = MDSDistancesEnum.valueOf(distCombo.getSelectedItem().toString()); final String strOrder = distanceParameters.getText(); if (mde.equals(MDSDistancesEnum.MINKOWSKI)) { mde.setParameters(new String[] { strOrder }); } Instances usedDataSet = dataSet; if (shihCheckbox.isSelected()) { //Modify instance using SHIH Algorithm final Shih2010 shih = new Shih2010(dataSet); usedDataSet = shih.getModifiedInstances(); } this.kmeansButton = new JButton("K-means"); this.maxKField = new JTextField("10"); //Create whole panel final JXPanel southPanel = new JXPanel(); southPanel.add(shihCheckbox); southPanel.add(ignoreClassCheckbox); southPanel.add(normalizeCheckbox); southPanel.add(maxInstances); southPanel.add(new JLabel("Maximum K")); southPanel.add(maxKField); southPanel.add(kmeansButton); this.jxp.add(southPanel, BorderLayout.SOUTH); //Compute MDS final MDSResult mdsResult = ClassicMDS.doMDS(usedDataSet, mde, 2, Integer.valueOf(maxInstances.getText()), ignoreClassCheckbox.isSelected(), normalizeCheckbox.isSelected()); final JXPanel mdsView = MDSViewBuilder.buildMDSViewFromDataSet(dataSet, mdsResult, Integer.valueOf(maxInstances.getText()), new Listener<Instances>() { @Override public void onAction(final Instances parameter) { pushDataChange(new DataChange(parameter, TabView.DataChangeTypeEnum.Selection)); } }); this.jxp.add(mdsView, BorderLayout.CENTER); this.kmeansButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { //List of coordinates (x,y) of collapsed instances final Instances coordsInstances = mdsResult.buildInstancesFromMatrix(); //FIXME dangerous : K-means on ordered collapsedInstance coordinates final KmeansImproved km = new KmeansImproved(coordsInstances, Integer.valueOf(maxKField.getText())); final double[] ass = km.getClusteredInstances(); int usedK = km.getUsedKmeans().getNumClusters(); final StringBuilder labels = new StringBuilder(); for (int i = 0; i < usedK; i++) { labels.append("cluster").append((i + 1)); if (i < usedK - 1) labels.append(","); } //Build modified dataset String attributeName = "cluster_proj"; while (dataSet.attribute(attributeName) != null) attributeName += "_proj"; final Add addFilter = new Add(); addFilter.setAttributeIndex("last"); addFilter.setAttributeName(attributeName); addFilter.setNominalLabels(labels.toString()); addFilter.setInputFormat(dataSet); final Instances modDataset = Filter.useFilter(dataSet, addFilter); final int nbInstances = modDataset.numInstances(); final int nbAttributes = modDataset.numAttributes(); if (mdsResult.getCInstances().isCollapsed()) { // final KmeansResult kmr = mdsResult.getCInstances().getCentroidMap(); final List<Instances> clusters = kmr.getClusters(); int nbClusters = clusters.size(); //Build a map between any instance and it's cluster's centroid final Map<ComparableInstance, Integer> mapCentroid = new HashMap<ComparableInstance, Integer>(); for (int i = 0; i < nbClusters; i++) { final Instances cluster = clusters.get(i); final int clusterSize = cluster.size(); for (int k = 0; k < clusterSize; k++) { mapCentroid.put(new ComparableInstance(cluster.instance(k)), i); } } //Use the previous map to add the additionnal feature for every element ! for (int i = 0; i < nbInstances; i++) { final int centroidIndex = mapCentroid.get(new ComparableInstance(dataSet.instance(i))); final String value = "cluster" + (int) (ass[centroidIndex] + 1); modDataset.instance(i).setValue(nbAttributes - 1, value); } } else { for (int i = 0; i < nbInstances; i++) { final String value = "cluster" + (int) (ass[i] + 1); modDataset.instance(i).setValue(nbAttributes - 1, value); } } pushDataChange(new DataChange(modDataset, TabView.DataChangeTypeEnum.Update)); } catch (Exception e1) { e1.printStackTrace(); } } }); this.jxp.repaint(); }