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

📄 boundarypanel.java

📁 代码是一个分类器的实现,其中使用了部分weka的源代码。可以将项目导入eclipse运行
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
      m_plotThread.setPriority(Thread.MIN_PRIORITY);      m_plotThread.start();    }*/  }    // Thread for main plotting operation  protected class PlotThread extends Thread {    double [] m_weightingAttsValues;    boolean [] m_attsToWeightOn;    double [] m_vals;    double [] m_dist;    Instance m_predInst;    public void run() {      m_stopPlotting = false;      try {        initialize();        repaint();                // train the classifier        m_probabilityCache = new double[m_panelHeight][m_panelWidth][];        m_classifier.buildClassifier(m_trainingData);                // build DataGenerator        m_attsToWeightOn = new boolean[m_trainingData.numAttributes()];        m_attsToWeightOn[m_xAttribute] = true;        m_attsToWeightOn[m_yAttribute] = true;	              m_dataGenerator.setWeightingDimensions(m_attsToWeightOn);	              m_dataGenerator.buildGenerator(m_trainingData);        // generate samples        m_weightingAttsValues = new double [m_attsToWeightOn.length];        m_vals = new double[m_trainingData.numAttributes()];        m_predInst = new Instance(1.0, m_vals);        m_predInst.setDataset(m_trainingData);	        m_size = 1 << 4;  // Current sample region size		m_initialTiling = true;        // Display the initial coarse image tiling.      abortInitial:        for (int i = 0; i <= m_panelHeight; i += m_size) {             for (int j = 0; j <= m_panelWidth; j += m_size) {   	    if (m_stopPlotting) {	      break abortInitial;	    }	    if (m_pausePlotting) {	      synchronized (m_dummy) {		try {		  m_dummy.wait();		} catch (InterruptedException ex) {		  m_pausePlotting = false;		}	      }	    }            plotPoint(j, i, m_size, m_size, 		      calculateRegionProbs(j, i), (j == 0));          }        }	if (!m_stopPlotting) {	  m_initialTiling = false;	}                // Sampling and gridding loop        int size2 = m_size / 2;        abortPlot:         while (m_size > 1) { // Subdivide down to the pixel level          for (int i = 0; i <= m_panelHeight; i += m_size) {            for (int j = 0; j <= m_panelWidth; j += m_size) {              if (m_stopPlotting) {                break abortPlot;              }	      if (m_pausePlotting) {		synchronized (m_dummy) {		  try {		    m_dummy.wait();		  } catch (InterruptedException ex) {		    m_pausePlotting = false;		  }		}	      }              boolean update = (j == 0 && i % 2 == 0);              // Draw the three new subpixel regions              plotPoint(j, i + size2, size2, size2, 			calculateRegionProbs(j, i + size2), update);              plotPoint(j + size2, i + size2, size2, size2, 			calculateRegionProbs(j + size2, i + size2), update);              plotPoint(j + size2, i, size2, size2, 			calculateRegionProbs(j + size2, i), update);            }          }          // The new region edge length is half the old edge length          m_size = size2;          size2 = size2 / 2;        }	update();		/*        // Old method without sampling.        abortPlot:         for (int i = 0; i < m_panelHeight; i++) {          for (int j = 0; j < m_panelWidth; j++) {            if (m_stopPlotting) {              break abortPlot;            }            plotPoint(j, i, calculateRegionProbs(j, i), (j == 0));          }        }        */        if (m_plotTrainingData) {          plotTrainingData();        }	            } catch (Exception ex) {        ex.printStackTrace();	JOptionPane.showMessageDialog(null,"Error while plotting: \"" + ex.getMessage() + "\"");      } finally {        m_plotThread = null;        // notify any listeners that we are finished        Vector l;        ActionEvent e = new ActionEvent(this, 0, "");        synchronized(this) {          l = (Vector)m_listeners.clone();        }        for (int i = 0; i < l.size(); i++) {          ActionListener al = (ActionListener)l.elementAt(i);          al.actionPerformed(e);        }      }    }        private double [] calculateRegionProbs(int j, int i) throws Exception {      double [] sumOfProbsForRegion = 	new double [m_trainingData.classAttribute().numValues()];      for (int u = 0; u < m_numOfSamplesPerRegion; u++) {              double [] sumOfProbsForLocation = 	  new double [m_trainingData.classAttribute().numValues()];              m_weightingAttsValues[m_xAttribute] = getRandomX(j);        m_weightingAttsValues[m_yAttribute] = getRandomY(m_panelHeight-i-1);              m_dataGenerator.setWeightingValues(m_weightingAttsValues);              double [] weights = m_dataGenerator.getWeights();        double sumOfWeights = Utils.sum(weights);        int [] indices = Utils.sort(weights);              // Prune 1% of weight mass        int [] newIndices = new int[indices.length];        double sumSoFar = 0;         double criticalMass = 0.99 * sumOfWeights;        int index = weights.length - 1; int counter = 0;        for (int z = weights.length - 1; z >= 0; z--) {          newIndices[index--] = indices[z];          sumSoFar += weights[indices[z]];          counter++;          if (sumSoFar > criticalMass) {            break;          }        }        indices = new int[counter];        System.arraycopy(newIndices, index + 1, indices, 0, counter);              for (int z = 0; z < m_numOfSamplesPerGenerator; z++) {                  m_dataGenerator.setWeightingValues(m_weightingAttsValues);          double [][] values = m_dataGenerator.generateInstances(indices);                  for (int q = 0; q < values.length; q++) {            if (values[q] != null) {              System.arraycopy(values[q], 0, m_vals, 0, m_vals.length);              m_vals[m_xAttribute] = m_weightingAttsValues[m_xAttribute];              m_vals[m_yAttribute] = m_weightingAttsValues[m_yAttribute];                          // classify the instance              m_dist = m_classifier.distributionForInstance(m_predInst);              for (int k = 0; k < sumOfProbsForLocation.length; k++) {                sumOfProbsForLocation[k] += (m_dist[k] * weights[q]);               }            }          }        }              for (int k = 0; k < sumOfProbsForRegion.length; k++) {          sumOfProbsForRegion[k] += (sumOfProbsForLocation[k] * 				     sumOfWeights);         }      }          // average      Utils.normalize(sumOfProbsForRegion);      // cache      if ((i < m_panelHeight) && (j < m_panelWidth)) {        m_probabilityCache[i][j] = new double[sumOfProbsForRegion.length];        System.arraycopy(sumOfProbsForRegion, 0, m_probabilityCache[i][j], 			 0, sumOfProbsForRegion.length);      }		      return sumOfProbsForRegion;    }  }  /** Render the training points on-screen.  */  public void plotTrainingData() {        Graphics2D osg = (Graphics2D)m_osi.getGraphics();    Graphics g = m_plotPanel.getGraphics();    osg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,                         RenderingHints.VALUE_ANTIALIAS_ON);    double xval = 0; double yval = 0;        for (int i = 0; i < m_trainingData.numInstances(); i++) {      if (!m_trainingData.instance(i).isMissing(m_xAttribute) &&          !m_trainingData.instance(i).isMissing(m_yAttribute)) {	  	if (m_trainingData.instance(i).isMissing(m_classIndex)) //jimmy.		continue; //don't plot if class is missing. TODO could we plot it differently instead?	        xval = m_trainingData.instance(i).value(m_xAttribute);        yval = m_trainingData.instance(i).value(m_yAttribute);               int panelX = convertToPanelX(xval);        int panelY = convertToPanelY(yval);        Color ColorToPlotWith =           ((Color)m_Colors.elementAt((int)m_trainingData.instance(i).                                     value(m_classIndex) % m_Colors.size()));	        if (ColorToPlotWith.equals(Color.white)) {          osg.setColor(Color.black);        } else {          osg.setColor(Color.white);        }        osg.fillOval(panelX-3, panelY-3, 7, 7);        osg.setColor(ColorToPlotWith);        osg.fillOval(panelX-2, panelY-2, 5, 5);      }    }    g.drawImage(m_osi,0,0,m_plotPanel);  }    /** Convert an X coordinate from the instance space to the panel space.  */  private int convertToPanelX(double xval) {    double temp = (xval - m_minX) / m_rangeX;    temp = temp * (double) m_panelWidth;    return (int)temp;  }  /** Convert a Y coordinate from the instance space to the panel space.  */  private int convertToPanelY(double yval) {    double temp = (yval - m_minY) / m_rangeY;    temp = temp * (double) m_panelHeight;    temp = m_panelHeight - temp;        return (int)temp;  }    /** Convert an X coordinate from the panel space to the instance space.  */  private double convertFromPanelX(double pX) {    pX /= (double) m_panelWidth;    pX *= m_rangeX;    return pX + m_minX;  }  /** Convert a Y coordinate from the panel space to the instance space.  */  private double convertFromPanelY(double pY) {    pY  = m_panelHeight - pY;    pY /= (double) m_panelHeight;    pY *= m_rangeY;        return pY + m_minY;  }  /** Plot a point in our visualization on-screen.  */  protected  void plotPoint(int x, int y, double [] probs, boolean update) {    plotPoint(x, y, 1, 1, probs, update);  }    /** Plot a point in our visualization on-screen.  */  private void plotPoint(int x, int y, int width, int height, 			 double [] probs, boolean update) {    // draw a progress line    Graphics osg = m_osi.getGraphics();    if (update) {      osg.setXORMode(Color.white);      osg.drawLine(0, y, m_panelWidth-1, y);      update();      osg.drawLine(0, y, m_panelWidth-1, y);    }    // plot the point    osg.setPaintMode();    float [] colVal = new float[3];        float [] tempCols = new float[3];    for (int k = 0; k < probs.length; k++) {      Color curr = (Color)m_Colors.elementAt(k % m_Colors.size());      curr.getRGBColorComponents(tempCols);      for (int z = 0 ; z < 3; z++) {        colVal[z] += probs[k] * tempCols[z];      }    }    for (int z = 0; z < 3; z++) {      if (colVal[z] < 0) {	colVal[z] = 0;      } else if (colVal[z] > 1) {	colVal[z] = 1;      }    }        osg.setColor(new Color(colVal[0],                            colVal[1],                            colVal[2]));    osg.fillRect(x, y, width, height);  }    /** Update the rendered image.  */  private void update() {    Graphics g = m_plotPanel.getGraphics();    g.drawImage(m_osi, 0, 0, m_plotPanel);  }  /**   * Set the training data to use   *   * @param trainingData the training data   * @exception Exception if an error occurs   */  public void setTrainingData(Instances trainingData) throws Exception {    m_trainingData = trainingData;    if (m_trainingData.classIndex() < 0) {      throw new Exception("No class attribute set (BoundaryPanel)");    }    m_classIndex = m_trainingData.classIndex();  }    /** Adds a training instance to the visualization dataset.  */  public void addTrainingInstance(Instance instance) {  	  	if (m_trainingData == null) {		//TODO		System.err.println("Trying to add to a null training set (BoundaryPanel)");	}  	  	m_trainingData.add(instance);  }  /**   * Register a listener to be notified when plotting completes   *   * @param newListener the listener to add   */  public void addActionListener(ActionListener newListener) {    m_listeners.add(newListener);  }    /**   * Remove a listener   *   * @param removeListener the listener to remove   */  public void removeActionListener(ActionListener removeListener) {    m_listeners.removeElement(removeListener);  }    /**   * Set the classifier to use.   *   * @param classifier the classifier to use   */  public void setClassifier(Classifier classifier) {    m_classifier = classifier;  }    /**   * Set the data generator to use for generating new instances   *   * @param dataGenerator the data generator to use   */

⌨️ 快捷键说明

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