AIAIndividual.py

 import numpy as np
import ObjFunction class AIAIndividual: '''
individual of artificial immune algorithm
''' def __init__(self, vardim, bound):
'''
vardim: dimension of variables
bound: boundaries of variables
'''
self.vardim = vardim
self.bound = bound
self.fitness = 0.
self.trials = 0
self.concentration = 0 def generate(self):
'''
generate a random chromsome for artificial immune algorithm
'''
len = self.vardim
rnd = np.random.random(size=len)
self.chrom = np.zeros(len)
for i in xrange(0, len):
self.chrom[i] = self.bound[0, i] + \
(self.bound[1, i] - self.bound[0, i]) * rnd[i] def calculateFitness(self):
'''
calculate the fitness of the chromsome
'''
self.fitness = ObjFunction.GrieFunc(
self.vardim, self.chrom, self.bound)

AIA.py

 import numpy as np
from AIAIndividual import AIAIndividual
import random
import copy
import matplotlib.pyplot as plt class ArtificialImmuneAlgorithm: '''
The class for artificial immune algorithm
''' def __init__(self, sizepop, sizemem, vardim, bound, MAXGEN, params):
'''
sizepop: population sizepop
vardim: dimension of variables
bound: boundaries of variables
MAXGEN: termination condition
params: algorithm required parameters, it is a list which is consisting of [mutation rate, cloneNum]
'''
self.sizepop = sizepop
self.sizemem = sizemem
self.MAXGEN = MAXGEN
self.vardim = vardim
self.bound = bound
self.population = []
self.clonePopulation = []
self.memories = []
self.cloneMemories = []
self.popFitness = np.zeros(self.sizepop)
self.popCloneFitness = np.zeros(
int(self.sizepop * self.sizepop * params[1]))
self.memfitness = np.zero(self.sizemem)
self.memClonefitness = np.zero(
int(self.sizemem * self.sizemem * params[1]))
self.trace = np.zeros((self.MAXGEN, 2))
self.params = params def initialize(self):
'''
initialize the population
'''
for i in xrange(0, self.sizepop):
ind = AIAIndividual(self.vardim, self.bound)
ind.generate()
self.population.append(ind)
for i in xrange(0, self.sizemem):
ind = AIAIndividual(self.vardim, self.bound)
ind.generate()
self.memories.append(ind) def evaluatePopulation(self, flag):
'''
evaluation of the population fitnesses
'''
if flag == 1:
for i in xrange(0, self.sizepop):
self.population[i].calculateFitness()
self.popFitness[i] = self.population[i].fitness
else:
for i in xrange(0, self.sizemem):
self.memories[i].calculateFitness()
self.memfitness[i] = self.memories[i].fitness def evaluateClone(self, flag):
'''
evaluation of the clone fitnesses
'''
if flag == 1:
for i in xrange(0, self.sizepop):
self.clonePopulation[i].calculateFitness()
self.popCloneFitness[i] = self.clonePopulation[i].fitness
else:
for i in xrange(0, self.sizemem):
self.cloneMemories[i].calculateFitness()
self.memClonefitness[i] = self.cloneMemories[i].fitness def solve(self):
'''
evolution process of artificial immune algorithm
'''
self.t = 0
self.initialize()
self.best = AIAIndividual(self.vardim, self.bound)
while (self.t < self.MAXGEN):
# evolution of population
self.cloneOperation(1)
self.mutationOperation(1)
self.evaluatePopulation(1)
self.selectionOperation(1) # evolution of memories
self.cloneOperation(2)
self.mutationOperation(2)
self.evaluatePopulation()
self.selectionOperation(2) best = np.max(self.popFitness)
bestIndex = np.argmax(self.popFitness)
if best > self.best.fitness:
self.best = copy.deepcopy(self.population[bestIndex])
self.avefitness = np.mean(self.popFitness)
self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness
self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness
print("Generation %d: optimal function value is: %f; average function value is %f" % (
self.t, self.trace[self.t, 0], self.trace[self.t, 1]))
self.t += 1 print("Optimal function value is: %f; " %
self.trace[self.t - 1, 0])
print "Optimal solution is:"
print self.best.chrom
self.printResult() def cloneOperation(self, individuals):
'''
clone operation for alforithm immune algorithm
'''
newpop = []
sizeInds = len(individuals)
for i in xrange(0, sizeInds):
for j in xrange(0, int(self.params[1] * sizeInds)):
newpop.append(copy.deepcopy(individuals[i]))
return newpop def selectionOperation(self, flag):
'''
selection operation for artificial immune algorithm
'''
if flag == 1:
sortedIdx = np.argsort(-self.clonefit)
for i in xrange(0, int(self.sizepop*self.sizepop*self.params[1]):
tmpInd = individuals[sortedIdx[i]]
if tmpInd.fitness > self.population[i].fitness:
self.population[i] = tmpInd
self.popFitness[i] = tmpInd.fitness
else:
pass
newpop = []
sizeInds = len(individuals)
fitness = np.zeros(sizeInds)
for i in xrange(0, sizeInds):
fitness[i] = individuals[i].fitness
sortedIdx = np.argsort(-fitness)
for i in xrange(0, sizeInds):
tmpInd = individuals[sortedIdx[i]]
if tmpInd.fitness > self.population[i].fitness:
self.population[i] = tmpInd
self.popFitness[i] = tmpInd.fitness def mutationOperation(self, individuals):
'''
mutation operation for artificial immune algorithm
'''
newpop = []
sizeInds = len(individuals)
for i in xrange(0, sizeInds):
newpop.append(copy.deepcopy(individuals[i]))
r = random.random()
if r < self.params[0]:
mutatePos = random.randint(0, self.vardim - 1)
theta = random.random()
if theta > 0.5:
newpop[i].chrom[mutatePos] = newpop[i].chrom[
mutatePos] - (newpop[i].chrom[mutatePos] - self.bound[0, mutatePos]) * (1 - random.random() ** (1 - self.t / self.MAXGEN))
else:
newpop[i].chrom[mutatePos] = newpop[i].chrom[
mutatePos] + (self.bound[1, mutatePos] - newpop[i].chrom[mutatePos]) * (1 - random.random() ** (1 - self.t / self.MAXGEN))
for k in xrange(0, self.vardim):
if newpop.chrom[mutatePos] < self.bound[0, mutatePos]:
newpop.chrom[mutatePos] = self.bound[0, mutatePos]
if newpop.chrom[mutatePos] > self.bound[1, mutatePos]:
newpop.chrom[mutatePos] = self.bound[1, mutatePos]
newpop.calculateFitness()
return newpop def printResult(self):
'''
plot the result of the artificial immune algorithm
'''
x = np.arange(0, self.MAXGEN)
y1 = self.trace[:, 0]
y2 = self.trace[:, 1]
plt.plot(x, y1, 'r', label='optimal value')
plt.plot(x, y2, 'g', label='average value')
plt.xlabel("Iteration")
plt.ylabel("function value")
plt.title("Artificial immune algorithm for function optimization")
plt.legend()
plt.show()

运行程序:

 if __name__ == "__main__":

     bound = np.tile([[-600], [600]], 25)
aia = AIA(100, 25, bound, 100, [0.9, 0.1])
aia.solve()

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

人工免疫算法-python实现的更多相关文章

  1. pageRank算法 python实现

    一.什么是pagerank PageRank的Page可是认为是网页,表示网页排名,也可以认为是Larry Page(google 产品经理),因为他是这个算法的发明者之一,还是google CEO( ...

  2. 常见排序算法-Python实现

    常见排序算法-Python实现 python 排序 算法 1.二分法     python    32行 right = length-  :  ]   ):  test_list = [,,,,,, ...

  3. kmp算法python实现

    kmp算法python实现 kmp算法 kmp算法用于字符串的模式匹配,也就是找到模式字符串在目标字符串的第一次出现的位置比如abababc那么bab在其位置1处,bc在其位置5处我们首先想到的最简单 ...

  4. KMP算法-Python版

                               KMP算法-Python版 传统法: 从左到右一个个匹配,如果这个过程中有某个字符不匹配,就跳回去,将模式串向右移动一位.这有什么难的? 我们可以 ...

  5. 压缩感知重构算法之IRLS算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  6. 压缩感知重构算法之OLS算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  7. 压缩感知重构算法之CoSaMP算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  8. 压缩感知重构算法之IHT算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  9. 压缩感知重构算法之SP算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

随机推荐

  1. 在springmvc中使用hibernate-validate

    在springmvc.xml中加入 <!-- 国际化配置 --> <bean id="localeResolver" class="org.spring ...

  2. Spring 中注入 properties 中的值

    <bean id="ckcPlaceholderProperties" class="org.springframework.beans.factory.confi ...

  3. 对比git rm和rm的使用区别

    在这里说一下git rm和rm的区别,虽然觉得这个问题有点肤浅,但对于刚接触git不久的朋友来说还是有必要的. 用 git rm 来删除文件,同时还会将这个删除操作记录下来:用 rm 来删除文件,仅仅 ...

  4. [5]Telerik Extensions for ASP.NET MVC 开发问题

    1.Controller获取不到checkedNodes的问题 HTML @(Html.Telerik().TreeView()        .Name("TreeView")  ...

  5. Android Studio使用中的异常

    Android studio教程:[4]真机测试 1.连不上手机 Android Studio识别不了手机(最后还是恢复成勾中的状态),重启,Android Studio连接真机没反应? 2.连上手机 ...

  6. C# 单点登录 MVC

    实现sso系统的主要难点: 1:不能直接访问数据库,有安全隐患,而且还容易乱套. 2:多个系统需要进行单点登录,逻辑需要严谨,能支持N多系统.而不只是少数几个系统. 3:代码不能过于复杂,需要简洁,灵 ...

  7. sed 4个功能

    [root@lanny test]# cat test.txt test liyao lanny 经典博文: http://oldboy.blog.51cto.com/2561410/949365 h ...

  8. Linux 网络编程一(TCP/IP协议)

    以前我们讲过进程间通信,通过进程间通信可以实现同一台计算机上不同的进程之间通信. 通过网络编程可以实现在网络中的各个计算机之间的通信. 进程能够使用套接字实现和其他进程或者其他计算机通信. 同样的套接 ...

  9. c语言 动态数组

    C语言中,在声明数组时,必须明确告诉编译器数组的大小,之后编译器就会在内存中为该数组开辟固定大小的内存.有些时候,用户并不确定需要多大的内存,使用多大的数组,为了保险起见,有的用户采用定义一个大数组的 ...

  10. CAS 单点登录流程

    经验:在网上学东西不要指望一篇文章就能让你明白——我在网上学CAS流程,看了五六篇博文,其中三篇是觉得作者表达能力不行,或者作者自己就没明白怎么回事就出来写东西,看到一半就跳过了,剩下两篇每篇看了两遍 ...