设为首页 收藏本站
查看: 345|回复: 0

[经验分享] 和声搜索算法-python实现

[复制链接]

尚未签到

发表于 2015-11-30 07:28:27 | 显示全部楼层 |阅读模式
  HSIndividual.py



1 import numpy as np
2 import ObjFunction
3
4
5 class HSIndividual:
6
7     '''
8     individual of harmony search algorithm
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
20     def generate(self):
21         '''
22         generate a random chromsome for harmony search algorithm
23         '''
24         len = self.vardim
25         rnd = np.random.random(size=len)
26         self.chrom = np.zeros(len)
27         for i in xrange(0, len):
28             self.chrom = self.bound[0, i] + \
29                 (self.bound[1, i] - self.bound[0, i]) * rnd
30
31     def calculateFitness(self):
32         '''
33         calculate the fitness of the chromsome
34         '''
35         self.fitness = ObjFunction.GrieFunc(
36             self.vardim, self.chrom, self.bound)
  HS.py



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



1 if __name__ == "__main__":
2
3     bound = np.tile([[-600], [600]], 25)
4     hs = HS(60, 25, bound, 5000, [0.9950, 0.4])
5     hs.solve()
  ObjFunction见简单遗传算法-python实现。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-145079-1-1.html 上篇帖子: Selenium + python 测试环境搭建 下篇帖子: python调用ice接口
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表