Roulette Selection in Genetic Algorithms

后端 未结 14 1012
庸人自扰
庸人自扰 2020-11-27 12:19

Can anyone provide some pseudo code for a roulette selection function? How would I implement this:

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 13:07

    Lots of correct solutions already, but I think this code is clearer.

    def select(fs):
        p = random.uniform(0, sum(fs))
        for i, f in enumerate(fs):
            if p <= 0:
                break
            p -= f
        return i
    

    In addition, if you accumulate the fs, you can produce a more efficient solution.

    cfs = [sum(fs[:i+1]) for i in xrange(len(fs))]
    
    def select(cfs):
        return bisect.bisect_left(cfs, random.uniform(0, cfs[-1]))
    

    This is both faster and it's extremely concise code. STL in C++ has a similar bisection algorithm available if that's the language you're using.

提交回复
热议问题