示例#1
0
 /**
  * Construct the simulated annealing trainer.
  *
  * @param theAlgorithm The algorithm to optimize.
  * @param theScore The score function.
  * @param theKMax The max number of iterations.
  * @param theStartingTemperature The starting temperature.
  * @param theEndingTemperature The ending temperature.
  */
 public TrainAnneal(
     final MLMethod theAlgorithm,
     final ScoreFunction theScore,
     final int theKMax,
     final double theStartingTemperature,
     final double theEndingTemperature) {
   this.algorithm = theAlgorithm;
   this.score = theScore;
   this.kMax = theKMax;
   this.currentError = score.calculateScore(this.algorithm);
   this.startingTemperature = theStartingTemperature;
   this.endingTemperature = theEndingTemperature;
   this.globalBest = new double[theAlgorithm.getLongTermMemory().length];
   System.arraycopy(
       this.algorithm.getLongTermMemory(), 0, this.globalBest, 0, this.globalBest.length);
 }
示例#2
0
  /** {@inheritDoc} */
  @Override
  public void iteration() {
    final int len = this.algorithm.getLongTermMemory().length;
    k++;

    this.currentTemperature = coolingSchedule();

    for (int cycle = 0; cycle < this.cycles; cycle++) {
      // backup current state
      final double[] oldState = new double[len];
      System.arraycopy(this.algorithm.getLongTermMemory(), 0, oldState, 0, len);

      // randomize the method
      performRandomize(this.algorithm.getLongTermMemory());

      // did we improve it?
      final double trialError = score.calculateScore(this.algorithm);

      // was this iteration an improvement?  If so, always keep.
      boolean keep = false;

      if (trialError < this.currentError) {
        keep = true;
      } else {

        this.lastProbability = calcProbability(currentError, trialError, this.currentTemperature);
        if (this.lastProbability > this.rnd.nextDouble()) {
          keep = true;
        }
      }

      if (keep) {
        this.currentError = trialError;
        // better than global error
        if (trialError < this.globalBestError) {
          this.globalBestError = trialError;
          System.arraycopy(this.algorithm.getLongTermMemory(), 0, oldState, 0, len);
          System.arraycopy(this.algorithm.getLongTermMemory(), 0, this.globalBest, 0, len);
        }
      } else {
        System.arraycopy(oldState, 0, this.algorithm.getLongTermMemory(), 0, len);
      }
    }
  }