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

[经验分享] 克隆选择算法-python实现

[复制链接]

尚未签到

发表于 2015-12-1 08:51:08 | 显示全部楼层 |阅读模式
  CSAIndividual.py



1 import numpy as np
2 import ObjFunction
3
4
5 class CSAIndividual:
6
7     '''
8     individual of clone selection 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         self.trials = 0
20
21     def generate(self):
22         '''
23         generate a random chromsome for clone selection algorithm
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 = self.bound[0, i] + \
30                 (self.bound[1, i] - self.bound[0, i]) * rnd
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)
  CSA.py



  1 import numpy as np
  2 from CSAIndividual import CSAIndividual
  3 import random
  4 import copy
  5 import matplotlib.pyplot as plt
  6
  7
  8 class CloneSelectionAlgorithm:
  9
10     '''
11     the class for clone selection algorithm
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[beta, pm, alpha_max, alpha_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 ba
34         '''
35         for i in xrange(0, self.sizepop):
36             ind = CSAIndividual(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.calculateFitness()
46             self.fitness = self.population.fitness
47
48     def solve(self):
49         '''
50         the evolution process of the clone selection algorithm
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.reproduction()
60             tmpPop = self.mutation(tmpPop)
61             self.selection(tmpPop)
62             best = np.max(self.fitness)
63             bestIndex = np.argmax(self.fitness)
64             if best > self.best.fitness:
65                 self.best = copy.deepcopy(self.population[bestIndex])
66
67             self.avefitness = np.mean(self.fitness)
68             self.trace[self.t - 1, 0] = \
69                 (1 - self.best.fitness) / self.best.fitness
70             self.trace[self.t - 1, 1] = (1 - self.avefitness) / self.avefitness
71             print("Generation %d: optimal function value is: %f; average function value is %f" % (
72                 self.t, self.trace[self.t - 1, 0], self.trace[self.t - 1, 1]))
73         print("Optimal function value is: %f; " % self.trace[self.t - 1, 0])
74         print "Optimal solution is:"
75         print self.best.chrom
76         self.printResult()
77
78     def reproduction(self):
79         '''
80         reproduction
81         '''
82         tmpPop = []
83         for i in xrange(0, self.sizepop):
84             nc = int(self.params[1] * self.sizepop)
85             for j in xrange(0, nc):
86                 ind = copy.deepcopy(self.population)
87                 tmpPop.append(ind)
88         return tmpPop
89
90     def mutation(self, tmpPop):
91         '''
92         hypermutation
93         '''
94         for i in xrange(0, self.sizepop):
95             nc = int(self.params[1] * self.sizepop)
96             for j in xrange(1, nc):
97                 rnd = np.random.random(1)
98                 if rnd < self.params[0]:
99                     # alpha = self.params[
100                     #     2] + self.t * (self.params[3] - self.params[2]) / self.MAXGEN
101                     delta = self.params[2] + self.t * \
102                         (self.params[3] - self.params[3]) / self.MAXGEN
103                     tmpPop[i * nc + j].chrom += np.random.normal(0.0, delta, self.vardim)
104                     # tmpPop[i * nc + j].chrom += alpha * np.random.random(
105                     # self.vardim) * (self.best.chrom - tmpPop[i * nc +
106                     # j].chrom)
107                     for k in xrange(0, self.vardim):
108                         if tmpPop[i * nc + j].chrom[k] < self.bound[0, k]:
109                             tmpPop[i * nc + j].chrom[k] = self.bound[0, k]
110                         if tmpPop[i * nc + j].chrom[k] > self.bound[1, k]:
111                             tmpPop[i * nc + j].chrom[k] = self.bound[1, k]
112                     tmpPop[i * nc + j].calculateFitness()
113         return tmpPop
114
115     def selection(self, tmpPop):
116         '''
117         re-selection
118         '''
119         for i in xrange(0, self.sizepop):
120             nc = int(self.params[1] * self.sizepop)
121             best = 0.0
122             bestIndex = -1
123             for j in xrange(0, nc):
124                 if tmpPop[i * nc + j].fitness > best:
125                     best = tmpPop[i * nc + j].fitness
126                     bestIndex = i * nc + j
127             if self.fitness < best:
128                 self.population = copy.deepcopy(tmpPop[bestIndex])
129                 self.fitness = best
130
131     def printResult(self):
132         '''
133         plot the result of clone selection algorithm
134         '''
135         x = np.arange(0, self.MAXGEN)
136         y1 = self.trace[:, 0]
137         y2 = self.trace[:, 1]
138         plt.plot(x, y1, 'r', label='optimal value')
139         plt.plot(x, y2, 'g', label='average value')
140         plt.xlabel("Iteration")
141         plt.ylabel("function value")
142         plt.title("Clone selection algorithm for function optimization")
143         plt.legend()
144         plt.show()
  运行程序:



1 if __name__ == "__main__":
2
3     bound = np.tile([[-600], [600]], 25)
4     csa = CSA(50, 25, bound, 500, [0.3, 0.4, 5, 0.1])
5     csa.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-145650-1-1.html 上篇帖子: Python标准库3.4.3-urllib.request-21.6 下篇帖子: Python Udp Socket
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

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

扫描微信二维码查看详情

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


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


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


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



合作伙伴: 青云cloud

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