algorithm - 使用 Golang 的遗传算法中的轮盘赌选择

标签 algorithm go artificial-intelligence

我正在为遗传算法构建一个模拟轮盘赌选择函数。首先,我想在主函数中添加 fitnessScoresum。在添加 fitnessScore 之后,我想使用 Go 中的 math/rand 包从那个 sum 中随机化一个值。在这种情况下我应该如何使用 rand 包如何修复 spin_wheel := rand.sum 以便随机生成一个值?

package main

import(
    "fmt"
    "time"
    "math/rand"
)

func rouletteWheel(fitnessScore []float64) []float64{
    sum := 0.0
    for i := 0; i < len(fitnessScore); i++ {
        sum += fitnessScore[i]
    }

    rand.Seed(time.Now().UnixNano())
    spin_wheel := rand.sum
    partial_sum := 0.0
    for i := 0; i < len(fitnessScore); i++{
        partial_sum += fitnessScore[i]
        if(partial_sum >= spin_wheel){
            return fitnessScore
        }
    }
    return fitnessScore
}

func main(){
    fitnessScore := []float64{0.1, 0.2, 0.3, 0.4}
    fmt.Println(rouletteWheel(fitnessScore))
}

最佳答案

例如,

package main

import (
    "fmt"
    "math/rand"
    "time"
)

// Returns the selected weight based on the weights(probabilities)
// Fitness proportionate selection:
// https://en.wikipedia.org/wiki/Fitness_proportionate_selection
func rouletteSelect(weights []float64) float64 {
    // calculate the total weights
    sum := 0.0
    for _, weight := range weights {
        sum += weight
    }
    // get a random value
    value := rand.Float64() * sum
    // locate the random value based on the weights
    for _, weight := range weights {
        value -= weight
        if value <= 0 {
            return weight
        }
    }
    // only when rounding errors occur
    return weights[len(weights)-1]
}

func main() {
    rand.Seed(time.Now().UnixNano())
    weights := []float64{0.1, 0.2, 0.3, 0.4}
    fmt.Println(rouletteSelect(weights))
}

关于algorithm - 使用 Golang 的遗传算法中的轮盘赌选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33003974/

相关文章:

go - 在 golang 中,为什么我不能将结构用作嵌套结构类型?

artificial-intelligence - 信息挖掘、分类、修改

c++ - 使用递归方式求解子集算法给出错误答案

Beego Controller 中的 JSON 响应

go - 输入密码时是否有 golang 函数来填充特殊字符?

algorithm - 带转置表的 Alpha-beta 剪枝,迭代加深

neural-network - 为什么我们需要人工神经网络中的层?

c++ - 在 vector 中查找不相等的相邻索引

algorithm - 使用 Scala 和算法进行锻炼

algorithm - 如何找到对已知列表进行排序的最小交换集?