zoukankan      html  css  js  c++  java
  • 进化策略-python实现

    ESIndividual.py

     1 import numpy as np
     2 import ObjFunction
     3 
     4 
     5 class ESIndividual:
     6 
     7     '''
     8     individual of evolutionary strategy
     9     '''
    10 
    11     def __init__(self,  vardim, bound):
    12         '''
    13         vardim: dimension of variables
    14         bound: boundaries of variables
    15         '''
    16         self.vardim = vardim
    17         self.bound = bound
    18         self.fitness = 0.
    19         self.trials = 0
    20 
    21     def generate(self):
    22         '''
    23         generate a random chromsome for evolutionary strategy
    24         '''
    25         len = self.vardim
    26         rnd = np.random.random(size=len)
    27         self.chrom = np.zeros(len)
    28         for i in xrange(0, len):
    29             self.chrom[i] = self.bound[0, i] + 
    30                 (self.bound[1, i] - self.bound[0, i]) * rnd[i]
    31 
    32     def calculateFitness(self):
    33         '''
    34         calculate the fitness of the chromsome
    35         '''
    36         self.fitness = ObjFunction.GrieFunc(
    37             self.vardim, self.chrom, self.bound)

    ES.py

      1 import numpy as np
      2 from ESIndividual import ESIndividual
      3 import random
      4 import copy
      5 import matplotlib.pyplot as plt
      6 
      7 
      8 class EvolutionaryStrategy:
      9 
     10     '''
     11     the class for evolutionary strategy
     12     '''
     13 
     14     def __init__(self, sizepop, vardim, bound, MAXGEN, params):
     15         '''
     16         sizepop: population sizepop
     17         vardim: dimension of variables
     18         bound: boundaries of variables
     19         MAXGEN: termination condition
     20         params: algorithm required parameters, it is a list which is consisting of[delta_max, delta_min]
     21         '''
     22         self.sizepop = sizepop
     23         self.vardim = vardim
     24         self.bound = bound
     25         self.MAXGEN = MAXGEN
     26         self.params = params
     27         self.population = []
     28         self.fitness = np.zeros(self.sizepop)
     29         self.trace = np.zeros((self.MAXGEN, 2))
     30 
     31     def initialize(self):
     32         '''
     33         initialize the population of es
     34         '''
     35         for i in xrange(0, self.sizepop):
     36             ind = ESIndividual(self.vardim, self.bound)
     37             ind.generate()
     38             self.population.append(ind)
     39 
     40     def evaluation(self):
     41         '''
     42         evaluation the fitness of the population
     43         '''
     44         for i in xrange(0, self.sizepop):
     45             self.population[i].calculateFitness()
     46             self.fitness[i] = self.population[i].fitness
     47 
     48     def solve(self):
     49         '''
     50         the evolution process of the evolutionary strategy
     51         '''
     52         self.t = 0
     53         self.initialize()
     54         self.evaluation()
     55         bestIndex = np.argmax(self.fitness)
     56         self.best = copy.deepcopy(self.population[bestIndex])
     57         while self.t < self.MAXGEN:
     58             self.t += 1
     59             tmpPop = self.mutation()
     60             self.selection(tmpPop)
     61             best = np.max(self.fitness)
     62             bestIndex = np.argmax(self.fitness)
     63             if best > self.best.fitness:
     64                 self.best = copy.deepcopy(self.population[bestIndex])
     65 
     66             self.avefitness = np.mean(self.fitness)
     67             self.trace[self.t - 1, 0] = 
     68                 (1 - self.best.fitness) / self.best.fitness
     69             self.trace[self.t - 1, 1] = (1 - self.avefitness) / self.avefitness
     70             print("Generation %d: optimal function value is: %f; average function value is %f" % (
     71                 self.t, self.trace[self.t - 1, 0], self.trace[self.t - 1, 1]))
     72         print("Optimal function value is: %f; " % self.trace[self.t - 1, 0])
     73         print "Optimal solution is:"
     74         print self.best.chrom
     75         self.printResult()
     76 
     77     def mutation(self):
     78         '''
     79         mutate the population by a random normal distribution
     80         '''
     81         tmpPop = []
     82         for i in xrange(0, self.sizepop):
     83             ind = copy.deepcopy(self.population[i])
     84             delta = self.params[0] + self.t * 
     85                 (self.params[1] - self.params[0]) / self.MAXGEN
     86             ind.chrom += np.random.normal(0.0, delta, self.vardim)
     87             for k in xrange(0, self.vardim):
     88                 if ind.chrom[k] < self.bound[0, k]:
     89                     ind.chrom[k] = self.bound[0, k]
     90                 if ind.chrom[k] > self.bound[1, k]:
     91                     ind.chrom[k] = self.bound[1, k]
     92             ind.calculateFitness()
     93             tmpPop.append(ind)
     94         return tmpPop
     95 
     96     def selection(self, tmpPop):
     97         '''
     98         update the population
     99         '''
    100         for i in xrange(0, self.sizepop):
    101             if self.fitness[i] < tmpPop[i].fitness:
    102                 self.population[i] = tmpPop[i]
    103                 self.fitness[i] = tmpPop[i].fitness
    104 
    105     def printResult(self):
    106         '''
    107         plot the result of evolutionary strategy
    108         '''
    109         x = np.arange(0, self.MAXGEN)
    110         y1 = self.trace[:, 0]
    111         y2 = self.trace[:, 1]
    112         plt.plot(x, y1, 'r', label='optimal value')
    113         plt.plot(x, y2, 'g', label='average value')
    114         plt.xlabel("Iteration")
    115         plt.ylabel("function value")
    116         plt.title("Evolutionary strategy for function optimization")
    117         plt.legend()
    118         plt.show()

    运行程序:

    1 if __name__ == "__main__":
    2 
    3     bound = np.tile([[-600], [600]], 25)    
    4     es = ES(60, 25, bound, 1000, [10, 1])
    5     es.solve()

    ObjFunction见简单遗传算法-python实现

  • 相关阅读:
    Yii2.0中文开发向导——Yii2中多表关联查询(join、joinwith)(转)
    yii2权限控制rbac之rule详细讲解(转)
    Yii2提交表单提示无法验证
    php 数组排序以及按照某个字段排序
    Yii 框架里数据库操作详解-[增加、查询、更新、删除的方法 'AR模式']
    Yii2的深入学习--自动加载机制(转)
    YII2 自定义日志路径
    Yii2-Redis使用小记
    windows下安装php5.5的redis扩展
    php json_decode返回null
  • 原文地址:https://www.cnblogs.com/biaoyu/p/4865353.html
Copyright © 2011-2022 走看看