Java 模拟退火算法(伪代码实现)

我目前正在做一个项目 (TSP),并尝试将一些模拟退火伪代码转换为 Java 代码。 过去我曾成功地将伪代码转换为 Java 代码,但这次却无法成功转换。

伪代码如下:

T0(T and a lowercase 0)    Starting temperatureIter    Number of iterationsλ    The cooling rate1.  Set T = T0 (T and a lowercase 0)2.  Let x = a random solution3.  For i = 0 to Iter-14.  Let f = fitness of x5.  Make a small change to x to make x’6.  Let f’ = fitness of new point7.  If f’ is worse than f then8.      Let p = PR(f’, f, Ti (T with a lowercase i))9.      If p > UR(0,1) then10.         Undo change (x and f)11.     Else12.         Let x = x’13.     End if14.     Let Ti(T with a lowercase i) + 1 = λTi(λ and T with a lowercase i)15. End forOutput:  The solution x

如果有人能展示一下这个在 Java 中的基本实现,我将非常感激 – 我似乎就是搞不明白!

我正在使用多个类和许多函数(我不会列出,因为它与我所问的无关)。我已经有一个 smallChange() 方法和一个 fitness 函数 – 是否有可能需要创建多个不同版本的这些方法? 例如,我有类似这样的:

public static ArrayList<Integer> smallChange(ArrayList<Integer> solution){//Code is here.}

我是否可能需要此方法的另一个版本,该版本接受不同的参数? 类似如下:

public static double smallChange(double d){//Code is here.}

我所需要的只是对如何在 Java 中编写这个有一个基本的了解 – 一旦我知道它在正确的语法中应该是什么样子,我就能够将它应用到我的代码中,但是我似乎无法克服这个障碍。


回答:

基本代码应该像这样:

public class YourClass {  public static Solution doYourStuff(double startingTemperature, int numberOfIterations, double coolingRate) {    double t = startingTemperature;    Solution x = createRandomSolution();    double ti = t;    for (int i = 0; i < numberOfIterations; i ++) {      double f = calculateFitness(x);      Solution mutatedX = mutate(x);      double newF = calculateFitness(mutatedX);      if (newF < f) {        double p = PR(); // no idea what you're talking about here        if (p > UR(0, 1)) { // likewise          // then do nothing        } else {          x = mutatedX;        }        ti = t * coolingRate;      }    }    return x;  }  static class Solution {    // no idea what's in here...  }}

至于想要 smallChange() 方法的不同版本 – 完全可以做到,但你必须阅读一些关于继承的内容。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注