适应度函数在遗传算法中使用php


Fitness function using php in genetic algorithm

我在GA选择最佳员工职位方面遇到了一些问题。

情况如下:

我有4名雇员(E1, E2, E3, E4),他们在3个群体中:

* Random array ( Population I )= (
    [0] = E1 => 200,
    [1] = E2 => 155,
    [2] = E3 => 130, 
    [3] = E4 => 98 
)
* Random array ( Population II )= (
    [0] = E2 => 155,
    [1] = E3 => 130,
    [2] = E1 => 200, 
    [3] = E4 => 98 
)
* Random array ( Population III )= (
    [0] = E4 => 98,
    [1] = E1 => 200,
    [2] = E3 => 130, 
    [3] = E2 => 155 
)

然后,我想把分数输入到这个函数中:

f =  ( N * score[0] ) + ( (N-1) * score[1] ) + score[2] + score[3] / N)

注意:N是被选中的员工数。

适应度函数示例(手工计算):

Population I : (4*200) + ((4-1)*155) + 130 + 98 / 4 = 373,25
Population II : (4*155) + ((4-1)*130) + 200 + 98 / 4 = 327
Population III : (4*98) + ((4-1)*200) + 130 + 155 / 4 = 319,25
那么如何使用PHP代码实现手动计算呢?

有人能帮帮我吗?我已经尝试了一个星期了,但仍然没有运气:(

这是您的公式的一个示例实现。然而,你的问题有两个明显的问题,所以让我们先看一看:

  1. 你的数组实际上是如何结构的?你的例子不是很清楚-数组只有一个键和一个值。在我的例子中,我把你的例子解释为文字值,我把它们分解成函数中的数字。
  2. 您希望该公式如何根据选择的员工数量进行缩放?我的实现将第一个和第二个条目硬编码,然后通过简单地在前两个值之后为每个值添加"人口",它将自动缩放。
  3. 一个额外的问题/问题:你的公式在末尾有一个括号,乍一看,然后从左到右看公式,似乎暗示你的公式的后半部分被添加并除以N,这是不正确的,因为你的预期输出值发生在整个结果除以N时。

无论如何,这里有一个实现:

function doMyCalculation($selections) {
    // Get number of selected employees
    $num_selected = count($selections);
    // Break up the format of your array - what is it supposed to be?
    array_walk($selections, function(&$employee) {
        list($emp, $val) = explode('=>', $employee);
        $employee = (int) $val;
    });
    // Initialize variable
    $return = 0;
    // Loop through all "employees"
    for($i = 0; $i < $num_selected; $i++) {
        // For the first two, we're going to use N as a multiplier
        if($i < 2) 
             // Use [N - current] as the multiplier (only twice)
            $return += ($num_selected - $i) * $selections[$i];
        else
            // Otherwise, just add it normally
            $return += $selections[$i];
    }
    // Divide the whole lot by N
    $return /= $num_selected;
    return $return;
}
echo doMyCalculation($arr1); // 373.25
echo doMyCalculation($arr2); // 327
echo doMyCalculation($arr3); // 319.25

你应该考虑以上几点,以确定如果你选择超过四个或少于四个员工等,你将如何扩大这一点。没有这些知识,很难给出一个准确的答案。