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. 第52课 C++中的抽象类和接口

    1. 什么是抽象类 (1)面向对象中的抽象概念 思考:抽象图形中,图形的面积如何计算? (2)现实中:需要知道具体的图形类型,才能求面积. (3)Shape只是一个概念上的类型,没有具体对象 2. 面 ...

  2. Daikon Forge GUI 制作UI面板

    因为是第一次写技术博客,文章的结构和层次估计不标准,但是并不妨碍我想表达的内容. DF-GUI知识 DF-GUI初窥 DF-GUI于今年10月份面世,作为为数不多的unity UI插件,其功能值得一窥 ...

  3. 转: 在创业公司使用C++

    from: http://oicwx.com/detail/827436 在创业公司使用C++ 2016-01-04开发资讯 James Perry和朋友创办了一家公司,主要是做基于云的OLAP多维数 ...

  4. Maven简介与简单使用

    Maven项目对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的软件项目管理工具. Maven 除了以程序构建能力为特色之外,还提供高级项目管理工具.由于 Maven 的缺省构建 ...

  5. WebApi 返回小驼峰式 json 格式,并格式化日期

    from:http://blog.csdn.net/magiccops/article/details/42969363 屏蔽默认返回xml格式:Global文件加:GlobalConfigurati ...

  6. createElement创建标签及appendChild添加到元素的后面

    var p = document.createElement('p'); var box = document.getElementsByTagName('div')[0]; box.appendCh ...

  7. Linux共享库 日志方法

    mylog.h #ifdef __cplusplus extern "C" { #endif //写日志函数 //path:日志文件名 //msg:日志信息 int writelo ...

  8. Oracle的if else if

    前段时间写Oracle存储过程就遇到问题.原来写成这样if 1=2 then  null;elseif 1=3 then  nullend if;在PL/SQL编辑环境下elseif没有变色,说明不是 ...

  9. JS 之继承

    ECMAScript继承是通过原型链来继承的.基本思想是利用原型来让一个引用类型继承另一个引用类型的属性和方法,使原型变为另一个对象的实例.通过原型链实现继承时,不能使用对象字面量创建原型方法,避免重 ...

  10. Android nDrawer

    GitHub上一款流行的侧滑,附上自己as编译过的源码http://download.csdn.net/detail/lj419855402/8559039. 留个纪念,说不定以后用得到. 依赖一个l ...