• Deap: 粒子群优化算法


    Source Code

    #!usr/bin/env python
    #-*- coding:utf-8 _*-
    """
    @author:fonttian 
    @file: Particle Swarm Optimization Basics.py 
    @time: 2017/10/15 
    """
    # ----------------------Modules----------------------
    import operator
    import random
    
    import numpy
    
    from deap import base
    from deap import benchmarks
    from deap import creator
    from deap import tools
    
    # ----------------------Representation----------------------
    # 最大化粒子
    # smin,smax 速度极限
    creator.create("FitnessMax", base.Fitness, weights=(1.0,))
    creator.create("Particle", list, fitness=creator.FitnessMax, speed=list,
        smin=None, smax=None, best=None)
    
    # ----------------------Operators----------------------
    # 初始化一个随机的位置,一个随机的速度
    def generate(size, pmin, pmax, smin, smax):
        part = creator.Particle(random.uniform(pmin, pmax) for _ in range(size))
        part.speed = [random.uniform(smin, smax) for _ in range(size)]
        part.smin = smin
        part.smax = smax
        return part
    
    # 首先计算速度,然后限制速度,最后计算粒子位置
    def updateParticle(part, best, phi1, phi2):
        u1 = (random.uniform(0, phi1) for _ in range(len(part)))
        u2 = (random.uniform(0, phi2) for _ in range(len(part)))
        v_u1 = map(operator.mul, u1, map(operator.sub, part.best, part))
        v_u2 = map(operator.mul, u2, map(operator.sub, best, part))
        part.speed = list(map(operator.add, part.speed, map(operator.add, v_u1, v_u2)))
        for i, speed in enumerate(part.speed):
            if speed < part.smin:
                part.speed[i] = part.smin
            elif speed > part.smax:
                part.speed[i] = part.smax
        part[:] = list(map(operator.add, part, part.speed))
    
    # The operators are registered in the toolbox with their parameters.
    # The particle value at the beginning are in the range [-100, 100] (pmin and pmax),
    # and the speed is limited in the range [-50, 50] through all the evolution.
    
    # The evaluation function h1() is from [Knoek2003].
    # The function is already defined in the benchmarks module, so we can register it directly.
    
    # def evaluate(individual):
    #     return sum(individual),
    
    # size 种群大小
    # pmin,pmax 初始值范围
    # smin,smax 速度范围
    toolbox = base.Toolbox()
    toolbox.register("particle", generate, size=2, pmin=-6, pmax=6, smin=-3, smax=3)
    toolbox.register("population", tools.initRepeat, list, toolbox.particle)
    toolbox.register("update", updateParticle, phi1=2.0, phi2=2.0)
    toolbox.register("evaluate", benchmarks.h1)
    # toolbox.register("evaluate", evaluate)
    
    # ----------------------Algorithm----------------------
    
    def main():
        pop = toolbox.population(n=5)
        stats = tools.Statistics(lambda ind: ind.fitness.values)
        stats.register("avg", numpy.mean)
        stats.register("std", numpy.std)
        stats.register("min", numpy.min)
        stats.register("max", numpy.max)
    
        logbook = tools.Logbook()
        logbook.header = ["gen", "evals"] + stats.fields
    
        GEN = 1000
        best = None
    
        for g in range(GEN):
            for part in pop:
                print(part)
                part.fitness.values = toolbox.evaluate(part)
                if not part.best or part.best.fitness < part.fitness:
                    part.best = creator.Particle(part)
                    part.best.fitness.values = part.fitness.values
                if not best or best.fitness < part.fitness:
                    best = creator.Particle(part)
                    best.fitness.values = part.fitness.values
            for part in pop:
                toolbox.update(part, best)
    
            # Gather all the fitnesses in one list and print the stats
            logbook.record(gen=g, evals=len(pop), **stats.compile(pop))
            print(logbook.stream)
    
        return pop, logbook, best
    
    if __name__ == "__main__":
        pop, logbook, best = main()
        print("最终族群 :",pop) # 没什么用
        # print("统计数据 :",logbook)
        print("最佳种群 :",best)
        print("最佳种群的适应度 :",benchmarks.h1(best))
        # print("最佳个体的适应度 :",evaluate(best))

    Output(默认执行时会输出统计数据)

    输出结果

  • 相关阅读:
    Codeforces Round #348 (VK Cup 2016 Round 2, Div. 2 Edition) D. Little Artem and Dance
    HDU 5521 Meeting 最短路
    BZOJ 1051: [HAOI2006]受欢迎的牛 强连通缩点
    P2661 信息传递 强连通分量
    Codeforces Round #343 (Div. 2) C. Famil Door and Brackets
    HDU 4859 海岸线 最小割
    HDU 4162 Shape Number
    Codeforces Round #355 (Div. 2) D. Vanya and Treasure dp+分块
    bzoj 1295: [SCOI2009]最长距离 暴力+bfs最短路
    Codeforces Round #222 (Div. 1) C. Captains Mode 对弈+dp
  • 原文地址:https://www.cnblogs.com/fonttian/p/9162767.html
Copyright © 2020-2023  润新知