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

📄 mainentry.java

📁 java neural networkin
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    }

    entry.downSample();
    SampleData sampleData = (SampleData)sample.getData().clone();
    sampleData.setLetter(letter.charAt(0));

    for ( i=0;i<letterListModel.size();i++ ) {
      Comparable str = (Comparable)letterListModel.getElementAt(i);
      if ( str.equals(letter) ) {
        JOptionPane.showMessageDialog(this,
                                      "That letter is already defined, delete it first!","Error",
                                      JOptionPane.ERROR_MESSAGE);
        return;
      }

      if ( str.compareTo(sampleData)>0 ) {
        letterListModel.add(i,sampleData);
        return;
      }
    }
    letterListModel.add(letterListModel.size(),sampleData);
    letters.setSelectedIndex(i);
    entry.clear();
    sample.repaint();

  }

  /**
   * Called when the del button is pressed.
   *
   * @param event The event.
   */
  void del_actionPerformed(java.awt.event.ActionEvent event)
  {
    int i = letters.getSelectedIndex();

    if ( i==-1 ) {
      JOptionPane.showMessageDialog(this,
                                    "Please select a letter to delete.","Error",
                                    JOptionPane.ERROR_MESSAGE);
      return;
    }

    letterListModel.remove(i);
  }

  class SymListSelection implements javax.swing.event.ListSelectionListener {
    public void valueChanged(javax.swing.event.ListSelectionEvent event)
    {
      Object object = event.getSource();
      if ( object == letters )
        letters_valueChanged(event);
    }
  }

  /**
   * Called when a letter is selected from the list box.
   *
   * @param event The event
   */
  void letters_valueChanged(javax.swing.event.ListSelectionEvent event)
  {
    if ( letters.getSelectedIndex()==-1 )
      return;
    SampleData selected =
      (SampleData)letterListModel.getElementAt(letters.getSelectedIndex());
    sample.setData((SampleData)selected.clone());
    sample.repaint();
    entry.clear();

  }

  /**
   * Called when the load button is pressed.
   *
   * @param event The event
   */
  void load_actionPerformed(java.awt.event.ActionEvent event)
  {
    try {
      FileReader f;// the actual file stream
      BufferedReader r;// used to read the file line by line

      f = new FileReader( new File("./sample.dat") );
      r = new BufferedReader(f);
      String line;
      int i=0;

      letterListModel.clear();

      while ( (line=r.readLine()) !=null ) {
        SampleData ds =
          new SampleData(line.charAt(0),MainEntry.DOWNSAMPLE_WIDTH,MainEntry.DOWNSAMPLE_HEIGHT);
        letterListModel.add(i++,ds);
        int idx=2;
        for ( int y=0;y<ds.getHeight();y++ ) {
          for ( int x=0;x<ds.getWidth();x++ ) {
            ds.setData(x,y,line.charAt(idx++)=='1');
          }
        }
      }

      r.close();
      f.close();
      clear_actionPerformed(null);
      JOptionPane.showMessageDialog(this,
                                    "Loaded from 'sample.dat'.","Training",
                                    JOptionPane.PLAIN_MESSAGE);

    } catch ( Exception e ) {
      JOptionPane.showMessageDialog(this,
                                    "Error: " + e,"Training",
                                    JOptionPane.ERROR_MESSAGE);
    }

  }

  /**
   * Called when the save button is clicked.
   *
   * @param event The event
   */
  void save_actionPerformed(java.awt.event.ActionEvent event)
  {
    try {
      OutputStream os;// the actual file stream
      PrintStream ps;// used to read the file line by line

      os = new FileOutputStream( "./sample.dat",false );
      ps = new PrintStream(os);

      for ( int i=0;i<letterListModel.size();i++ ) {
        SampleData ds = (SampleData)letterListModel.elementAt(i);
        ps.print( ds.getLetter() + ":" );
        for ( int y=0;y<ds.getHeight();y++ ) {
          for ( int x=0;x<ds.getWidth();x++ ) {
            ps.print( ds.getData(x,y)?"1":"0" );
          }
        }
        ps.println("");
      }

      ps.close();
      os.close();
      clear_actionPerformed(null);
      JOptionPane.showMessageDialog(this,
                                    "Saved to 'sample.dat'.",
                                    "Training",
                                    JOptionPane.PLAIN_MESSAGE);

    } catch ( Exception e ) {
      JOptionPane.showMessageDialog(this,"Error: " +
                                    e,"Training",
                                    JOptionPane.ERROR_MESSAGE);
    }

  }

  /**
   * Run method for the background training thread.
   */
  public void run()
  {
    try {
      int inputNeuron = MainEntry.DOWNSAMPLE_HEIGHT*
        MainEntry.DOWNSAMPLE_WIDTH;
      int outputNeuron = letterListModel.size();

      TrainingSet set = new TrainingSet(inputNeuron,outputNeuron);
      set.setTrainingSetCount(letterListModel.size());

      for ( int t=0;t<letterListModel.size();t++ ) {
        int idx=0;
        SampleData ds = (SampleData)letterListModel.getElementAt(t);
        for ( int y=0;y<ds.getHeight();y++ ) {
          for ( int x=0;x<ds.getWidth();x++ ) {
            set.setInput(t,idx++,ds.getData(x,y)?.5:-.5);
          }
        }
      }

      net = new KohonenNetwork(inputNeuron,outputNeuron,this);
      net.setTrainingSet(set);
      net.learn();
    } catch ( Exception e ) {
      JOptionPane.showMessageDialog(this,"Error: " + e,
                                    "Training",
                                    JOptionPane.ERROR_MESSAGE);
    }

  }

  /**
   * Called to update the stats, from the neural network.
   *
   * @param trial How many tries.
   * @param error The current error.
   * @param best The best error.
   */
  public void update(int retry,double totalError,double bestError)
  {
    if ( (((retry%100)!=0) || (retry==10)) && !net.halt )
      return;

    if ( net.halt ) {
      trainThread = null;
      train.setText("Begin Training");
      JOptionPane.showMessageDialog(this,
                                    "Training has completed.","Training",
                                    JOptionPane.PLAIN_MESSAGE);
    }
    UpdateStats stats = new UpdateStats();
    stats._tries = retry;
    stats._lastError=totalError;
    stats._bestError=bestError;
    try {
      SwingUtilities.invokeAndWait(stats);
    } catch ( Exception e ) {
      JOptionPane.showMessageDialog(this,"Error: " + e,"Training",
                                    JOptionPane.ERROR_MESSAGE);
    }
  }

  /**
   * Called when the train button is pressed.
   *
   * @param event The event.
   */
  void train_actionPerformed(java.awt.event.ActionEvent event)
  {
    if ( trainThread==null ) {
      train.setText("Stop Training");
      train.repaint();
      trainThread = new Thread(this);
      trainThread.start();
    } else {
      net.halt=true;
    }
  }

  /**
   * Called when the recognize button is pressed.
   *
   * @param event The event.
   */
  void recognize_actionPerformed(java.awt.event.ActionEvent event)
  {
    if ( net==null ) {
      JOptionPane.showMessageDialog(this,
                                    "I need to be trained first!","Error",
                                    JOptionPane.ERROR_MESSAGE);
      return;
    }
    entry.downSample();

    double input[] = new double[5*7];
    int idx=0;
    SampleData ds = sample.getData();
    for ( int y=0;y<ds.getHeight();y++ ) {
      for ( int x=0;x<ds.getWidth();x++ ) {
        input[idx++] = ds.getData(x,y)?.5:-.5;
      }
    }

    double normfac[] = new double[1];
    double synth[] = new double[1];

    int best = net.winner ( input , normfac , synth ) ;
    char map[] = mapNeurons();
    JOptionPane.showMessageDialog(this,
                                  "  " + map[best] + "   (Neuron #"
                                  + best + " fired)","That Letter Is",
                                  JOptionPane.PLAIN_MESSAGE);
    clear_actionPerformed(null);

  }

  /**
   * Used to map neurons to actual letters.
   *
   * @return The current mapping between neurons and letters as an array.
   */
  char []mapNeurons()
  {
    char map[] = new char[letterListModel.size()];
    double normfac[] = new double[1];
    double synth[] = new double[1];

    for ( int i=0;i<map.length;i++ )
      map[i]='?';
    for ( int i=0;i<letterListModel.size();i++ ) {
      double input[] = new double[5*7];
      int idx=0;
      SampleData ds = (SampleData)letterListModel.getElementAt(i);
      for ( int y=0;y<ds.getHeight();y++ ) {
        for ( int x=0;x<ds.getWidth();x++ ) {
          input[idx++] = ds.getData(x,y)?.5:-.5;
        }
      }

      int best = net.winner ( input , normfac , synth ) ;
      map[best] = ds.getLetter();
    }
    return map;
  }


  public class UpdateStats implements Runnable {
    long _tries;
    double _lastError;
    double _bestError;

    public void run()
    {
      tries.setText(""+_tries);
      lastError.setText(""+_lastError);
      bestError.setText(""+_bestError);
    }
  }


}

⌨️ 快捷键说明

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