⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 boundarypanel.java

📁 代码是一个分类器的实现,其中使用了部分weka的源代码。可以将项目导入eclipse运行
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
  public void setDataGenerator(DataGenerator dataGenerator) {    m_dataGenerator = dataGenerator;  }    /**   * Set the x attribute index   *   * @param xatt index of the attribute to use on the x axis   * @exception Exception if an error occurs   */  public void setXAttribute(int xatt) throws Exception {    if (m_trainingData == null) {      throw new Exception("No training data set (BoundaryPanel)");    }    if (xatt < 0 ||         xatt > m_trainingData.numAttributes()) {      throw new Exception("X attribute out of range (BoundaryPanel)");    }    if (m_trainingData.attribute(xatt).isNominal()) {      throw new Exception("Visualization dimensions must be numeric "                          +"(BoundaryPanel)");    }    /*if (m_trainingData.numDistinctValues(xatt) < 2) {      throw new Exception("Too few distinct values for X attribute "                          +"(BoundaryPanel)");    }*/ //removed by jimmy. TESTING!    m_xAttribute = xatt;  }  /**   * Set the y attribute index   *   * @param yatt index of the attribute to use on the y axis   * @exception Exception if an error occurs   */  public void setYAttribute(int yatt) throws Exception {    if (m_trainingData == null) {      throw new Exception("No training data set (BoundaryPanel)");    }    if (yatt < 0 ||         yatt > m_trainingData.numAttributes()) {      throw new Exception("X attribute out of range (BoundaryPanel)");    }    if (m_trainingData.attribute(yatt).isNominal()) {      throw new Exception("Visualization dimensions must be numeric "                          +"(BoundaryPanel)");    }    /*if (m_trainingData.numDistinctValues(yatt) < 2) {      throw new Exception("Too few distinct values for Y attribute "                          +"(BoundaryPanel)");    }*/ //removed by jimmy. TESTING!    m_yAttribute = yatt;  }    /**   * Set a vector of Color objects for the classes   *   * @param colors a <code>FastVector</code> value   */  public void setColors(FastVector colors) {    synchronized (m_Colors) {      m_Colors = colors;    }    //replot(); //commented by jimmy    update(); //added by jimmy  }  /**   * Set whether to superimpose the training data   * plot   *   * @param pg a <code>boolean</code> value   */  public void setPlotTrainingData(boolean pg) {    m_plotTrainingData = pg;  }  /**   * Returns true if training data is to be superimposed   *   * @return a <code>boolean</code> value   */  public boolean getPlotTrainingData() {    return m_plotTrainingData;  }    /**   * Get the current vector of Color objects used for the classes   *   * @return a <code>FastVector</code> value   */  public FastVector getColors() {    return m_Colors;  }    /**   * Quickly replot the display using cached probability estimates   */  public void replot() {    if (m_probabilityCache[0][0] == null) {      return;    }    m_stopReplotting = true;    m_pausePlotting = true;    // wait 300 ms to give any other replot threads a chance to halt    try {      Thread.sleep(300);    } catch (Exception ex) {}    final Thread replotThread = new Thread() {        public void run() {          m_stopReplotting = false;	  int size2 = m_size / 2;          finishedReplot: for (int i = 0; i < m_panelHeight; i += m_size) {            for (int j = 0; j < m_panelWidth; j += m_size) {              if (m_probabilityCache[i][j] == null || m_stopReplotting) {                break finishedReplot;              }	      boolean update = (j == 0 && i % 2 == 0);	      if (i < m_panelHeight && j < m_panelWidth) {		// Draw the three new subpixel regions or single course tiling		if (m_initialTiling || m_size == 1) {		  if (m_probabilityCache[i][j] == null) {		    break finishedReplot;		  }		  plotPoint(j, i, m_size, m_size, 			    m_probabilityCache[i][j], update);		} else {		  if (m_probabilityCache[i+size2][j] == null) {		    break finishedReplot;		  }		  plotPoint(j, i + size2, size2, size2, 			    m_probabilityCache[i + size2][j], update);		  if (m_probabilityCache[i+size2][j+size2] == null) {		    break finishedReplot;		  }		  plotPoint(j + size2, i + size2, size2, size2, 			    m_probabilityCache[i + size2][j + size2], update);		  if (m_probabilityCache[i][j+size2] == null) {		    break finishedReplot;		  }		  plotPoint(j + size2, i, size2, size2, 			    m_probabilityCache[i + size2][j], update);		}	      }	    }          }	  update();          if (m_plotTrainingData) {            plotTrainingData();          }	  m_pausePlotting = false;	  if (!m_stopPlotting) {	    synchronized (m_dummy) {	      m_dummy.notifyAll();	    }	  }        }      };        replotThread.start();        }  protected void saveImage(String fileName) {    try {      BufferedOutputStream out =         new BufferedOutputStream(new FileOutputStream(fileName));            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);      BufferedImage bi = new BufferedImage(m_panelWidth, m_panelHeight,                                           BufferedImage.TYPE_INT_RGB);      Graphics2D gr2 = bi.createGraphics();      gr2.drawImage(m_osi, 0, 0, m_panelWidth, m_panelHeight, null);      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);      param.setQuality(1.0f, false);      encoder.setJPEGEncodeParam(param);      encoder.encode(bi);      out.flush();      out.close();    } catch (Exception ex) {      ex.printStackTrace();    }  }    /** Adds a training instance to our dataset, based on the coordinates of the mouse on the panel.      This method sets the x and y attributes and the class (as defined by classAttIndex), and sets      all other values as Missing.   *  @param mouseX the x coordinate of the mouse, in pixels.   *  @param mouseY the y coordinate of the mouse, in pixels.   *  @param classAttIndex the index of the attribute that is currently selected as the class attribute.   *  @param classValue the value to set the class to in our new point.   */  public void addTrainingInstanceFromMouseLocation(int mouseX, int mouseY, int classAttIndex, double classValue) {  	//convert to coordinates in the training instance space.	double x = convertFromPanelX(mouseX);	double y = convertFromPanelY(mouseY);		//build the training instance	Instance newInstance = new Instance(m_trainingData.numAttributes());	for (int i = 0; i < newInstance.numAttributes(); i++) {		if (i == classAttIndex) {			newInstance.setValue(i,classValue);		}		else if (i == m_xAttribute)			newInstance.setValue(i,x);		else if (i == m_yAttribute)			newInstance.setValue(i,y);		else newInstance.setMissing(i);	}		//add it to our data set.	addTrainingInstance(newInstance);  }    /** Deletes all training instances from our dataset.  */  public void removeAllInstances() {  	if (m_trainingData != null)	{  		m_trainingData.delete();		try { initialize();} catch (Exception e) {};	}	  }    /** Removes a single training instance from our dataset, if there is one that is close enough      to the specified mouse location.  */  public void removeTrainingInstanceFromMouseLocation(int mouseX, int mouseY) {  		//convert to coordinates in the training instance space.	double x = convertFromPanelX(mouseX);	double y = convertFromPanelY(mouseY);		int bestIndex = -1;	double bestDistanceBetween = Integer.MAX_VALUE;		//find the closest point.	for (int i = 0; i < m_trainingData.numInstances(); i++) {		Instance current = m_trainingData.instance(i);		double distanceBetween = (current.value(m_xAttribute) - x) * (current.value(m_xAttribute) - x) + (current.value(m_yAttribute) - y) * (current.value(m_yAttribute) - y); // won't bother to sqrt, just used square values.				if (distanceBetween < bestDistanceBetween)		{			bestIndex = i;			bestDistanceBetween = distanceBetween;		}	}	if (bestIndex == -1)		return;	Instance best = m_trainingData.instance(bestIndex);	double panelDistance = (convertToPanelX(best.value(m_xAttribute)) - mouseX) * (convertToPanelX(best.value(m_xAttribute)) - mouseX)		+ (convertToPanelY(best.value(m_yAttribute)) - mouseY) * (convertToPanelY(best.value(m_yAttribute)) - mouseY);	if (panelDistance < REMOVE_POINT_RADIUS * REMOVE_POINT_RADIUS) {//the best point is close enough. (using squared distances)		m_trainingData.delete(bestIndex);	}  }    /** Starts the plotting thread.  Will also create it if necessary.  */  public void startPlotThread() {  	if (m_plotThread == null) { //jimmy      		m_plotThread = new PlotThread();      		m_plotThread.setPriority(Thread.MIN_PRIORITY);      		m_plotThread.start();    	}  }    /** Adds a mouse listener.  */  public void addMouseListener(MouseListener l) {  	m_plotPanel.addMouseListener(l);  }    /** Gets the minimum x-coordinate bound, in training-instance units (not mouse coordinates).  */  public double getMinXBound() {  	return m_minX;  }    /** Gets the minimum y-coordinate bound, in training-instance units (not mouse coordinates).  */  public double getMinYBound() {  	return m_minY;  }    /** Gets the maximum x-coordinate bound, in training-instance units (not mouse coordinates).  */  public double getMaxXBound() {  	return m_maxX;  }    /** Gets the maximum x-coordinate bound, in training-instance units (not mouse coordinates).  */  public double getMaxYBound() {  	return m_maxY;  }  /**   * Main method for testing this class   *   * @param args a <code>String[]</code> value   */  public static void main (String [] args) {    try {      if (args.length < 8) {	System.err.println("Usage : BoundaryPanel <dataset> "			   +"<class col> <xAtt> <yAtt> "			   +"<base> <# loc/pixel> <kernel bandwidth> "			   +"<display width> "			   +"<display height> <classifier "			   +"[classifier options]>");	System.exit(1);      }      final javax.swing.JFrame jf = 	new javax.swing.JFrame("Weka classification boundary visualizer");      jf.getContentPane().setLayout(new BorderLayout());      System.err.println("Loading instances from : "+args[0]);      java.io.Reader r = new java.io.BufferedReader(			 new java.io.FileReader(args[0]));      final Instances i = new Instances(r);      i.setClassIndex(Integer.parseInt(args[1]));      //      bv.setClassifier(new Logistic());      final int xatt = Integer.parseInt(args[2]);      final int yatt = Integer.parseInt(args[3]);      int base = Integer.parseInt(args[4]);      int loc = Integer.parseInt(args[5]);      int bandWidth = Integer.parseInt(args[6]);      int panelWidth = Integer.parseInt(args[7]);      int panelHeight = Integer.parseInt(args[8]);      final String classifierName = args[9];      final BoundaryPanel bv = new BoundaryPanel(panelWidth,panelHeight);      bv.addActionListener(new ActionListener() {	  public void actionPerformed(ActionEvent e) {	    String classifierNameNew = 	      classifierName.substring(classifierName.lastIndexOf('.')+1, 				       classifierName.length());	    bv.saveImage(classifierNameNew+"_"+i.relationName()			 +"_X"+xatt+"_Y"+yatt+".jpg");	  }	});      jf.getContentPane().add(bv, BorderLayout.CENTER);      jf.setSize(bv.getMinimumSize());      //      jf.setSize(200,200);      jf.addWindowListener(new java.awt.event.WindowAdapter() {	  public void windowClosing(java.awt.event.WindowEvent e) {	    jf.dispose();	    System.exit(0);	  }	});      jf.pack();      jf.setVisible(true);      //      bv.initialize();      bv.repaint();            String [] argsR = null;      if (args.length > 10) {	argsR = new String [args.length-10];	for (int j = 10; j < args.length; j++) {	  argsR[j-10] = args[j];	}      }      Classifier c = Classifier.forName(args[9], argsR);      KDDataGenerator dataGen = new KDDataGenerator();      dataGen.setKernelBandwidth(bandWidth);      bv.setDataGenerator(dataGen);      bv.setNumSamplesPerRegion(loc);      bv.setGeneratorSamplesBase(base);      bv.setClassifier(c);      bv.setTrainingData(i);      bv.setXAttribute(xatt);      bv.setYAttribute(yatt);      try {	// try and load a color map if one exists	FileInputStream fis = new FileInputStream("colors.ser");	ObjectInputStream ois = new ObjectInputStream(fis);	FastVector colors = (FastVector)ois.readObject();	bv.setColors(colors);	      } catch (Exception ex) {	System.err.println("No color map file");      }      bv.start();    } catch (Exception ex) {      ex.printStackTrace();    }  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -