人工免疫算法-python实现

AIAIndividual.py

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

AIA.py

  1 import numpy as np
  2 from AIAIndividual import AIAIndividual
  3 import random
  4 import copy
  5 import matplotlib.pyplot as plt
  6 
  7 
  8 class ArtificialImmuneAlgorithm:
  9 
 10     '''
 11     The class for artificial immune algorithm
 12     '''
 13 
 14     def __init__(self, sizepop, sizemem, 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 [mutation rate, cloneNum]
 21         '''
 22         self.sizepop = sizepop
 23         self.sizemem = sizemem
 24         self.MAXGEN = MAXGEN
 25         self.vardim = vardim
 26         self.bound = bound
 27         self.population = []
 28         self.clonePopulation = []
 29         self.memories = []
 30         self.cloneMemories = []
 31         self.popFitness = np.zeros(self.sizepop)
 32         self.popCloneFitness = np.zeros(
 33             int(self.sizepop * self.sizepop * params[1]))
 34         self.memfitness = np.zero(self.sizemem)
 35         self.memClonefitness = np.zero(
 36             int(self.sizemem * self.sizemem * params[1]))
 37         self.trace = np.zeros((self.MAXGEN, 2))
 38         self.params = params
 39 
 40     def initialize(self):
 41         '''
 42         initialize the population
 43         '''
 44         for i in xrange(0, self.sizepop):
 45             ind = AIAIndividual(self.vardim, self.bound)
 46             ind.generate()
 47             self.population.append(ind)
 48         for i in xrange(0, self.sizemem):
 49             ind = AIAIndividual(self.vardim, self.bound)
 50             ind.generate()
 51             self.memories.append(ind)
 52 
 53     def evaluatePopulation(self, flag):
 54         '''
 55         evaluation of the population fitnesses
 56         '''
 57         if flag == 1:
 58             for i in xrange(0, self.sizepop):
 59                 self.population[i].calculateFitness()
 60                 self.popFitness[i] = self.population[i].fitness
 61         else:
 62             for i in xrange(0, self.sizemem):
 63                 self.memories[i].calculateFitness()
 64                 self.memfitness[i] = self.memories[i].fitness
 65 
 66     def evaluateClone(self, flag):
 67         '''
 68         evaluation of the clone fitnesses
 69         '''
 70         if flag == 1:
 71             for i in xrange(0, self.sizepop):
 72                 self.clonePopulation[i].calculateFitness()
 73                 self.popCloneFitness[i] = self.clonePopulation[i].fitness
 74         else:
 75             for i in xrange(0, self.sizemem):
 76                 self.cloneMemories[i].calculateFitness()
 77                 self.memClonefitness[i] = self.cloneMemories[i].fitness
 78 
 79     def solve(self):
 80         '''
 81         evolution process of artificial immune algorithm
 82         '''
 83         self.t = 0
 84         self.initialize()
 85         self.best = AIAIndividual(self.vardim, self.bound)
 86         while (self.t < self.MAXGEN):
 87             # evolution of population
 88             self.cloneOperation(1)
 89             self.mutationOperation(1)
 90             self.evaluatePopulation(1)
 91             self.selectionOperation(1)
 92 
 93             # evolution of memories
 94             self.cloneOperation(2)
 95             self.mutationOperation(2)
 96             self.evaluatePopulation()
 97             self.selectionOperation(2)
 98 
 99             best = np.max(self.popFitness)
100             bestIndex = np.argmax(self.popFitness)
101             if best > self.best.fitness:
102                 self.best = copy.deepcopy(self.population[bestIndex])
103             self.avefitness = np.mean(self.popFitness)
104             self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness
105             self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness
106             print("Generation %d: optimal function value is: %f; average function value is %f" % (
107                 self.t, self.trace[self.t, 0], self.trace[self.t, 1]))
108             self.t += 1
109 
110         print("Optimal function value is: %f; " %
111               self.trace[self.t - 1, 0])
112         print "Optimal solution is:"
113         print self.best.chrom
114         self.printResult()
115 
116     def cloneOperation(self, individuals):
117         '''
118         clone operation for alforithm immune algorithm
119         '''
120         newpop = []
121         sizeInds = len(individuals)
122         for i in xrange(0, sizeInds):
123             for j in xrange(0, int(self.params[1] * sizeInds)):
124                 newpop.append(copy.deepcopy(individuals[i]))
125         return newpop
126 
127     def selectionOperation(self, flag):
128         '''
129         selection operation for artificial immune algorithm
130         '''
131         if flag == 1:
132             sortedIdx = np.argsort(-self.clonefit)
133             for i in xrange(0, int(self.sizepop*self.sizepop*self.params[1]):
134             tmpInd = individuals[sortedIdx[i]]
135             if tmpInd.fitness > self.population[i].fitness:
136                 self.population[i] = tmpInd
137                 self.popFitness[i] = tmpInd.fitness
138         else:
139             pass
140         newpop = []
141         sizeInds = len(individuals)
142         fitness = np.zeros(sizeInds)
143         for i in xrange(0, sizeInds):
144             fitness[i] = individuals[i].fitness
145         sortedIdx = np.argsort(-fitness)
146         for i in xrange(0, sizeInds):
147             tmpInd = individuals[sortedIdx[i]]
148             if tmpInd.fitness > self.population[i].fitness:
149                 self.population[i] = tmpInd
150                 self.popFitness[i] = tmpInd.fitness
151 
152     def mutationOperation(self, individuals):
153         '''
154         mutation operation for artificial immune algorithm
155         '''
156         newpop = []
157         sizeInds = len(individuals)
158         for i in xrange(0, sizeInds):
159             newpop.append(copy.deepcopy(individuals[i]))
160             r = random.random()
161             if r < self.params[0]:
162                 mutatePos = random.randint(0, self.vardim - 1)
163                 theta = random.random()
164                 if theta > 0.5:
165                     newpop[i].chrom[mutatePos] = newpop[i].chrom[
166                         mutatePos] - (newpop[i].chrom[mutatePos] - self.bound[0, mutatePos]) * (1 - random.random() ** (1 - self.t / self.MAXGEN))
167                 else:
168                     newpop[i].chrom[mutatePos] = newpop[i].chrom[
169                         mutatePos] + (self.bound[1, mutatePos] - newpop[i].chrom[mutatePos]) * (1 - random.random() ** (1 - self.t / self.MAXGEN))
170                 for k in xrange(0, self.vardim):
171                     if newpop.chrom[mutatePos] < self.bound[0, mutatePos]:
172                         newpop.chrom[mutatePos] = self.bound[0, mutatePos]
173                     if newpop.chrom[mutatePos] > self.bound[1, mutatePos]:
174                         newpop.chrom[mutatePos] = self.bound[1, mutatePos]
175                 newpop.calculateFitness()
176         return newpop
177 
178     def printResult(self):
179         '''
180         plot the result of the artificial immune algorithm
181         '''
182         x = np.arange(0, self.MAXGEN)
183         y1 = self.trace[:, 0]
184         y2 = self.trace[:, 1]
185         plt.plot(x, y1, 'r', label='optimal value')
186         plt.plot(x, y2, 'g', label='average value')
187         plt.xlabel("Iteration")
188         plt.ylabel("function value")
189         plt.title("Artificial immune algorithm for function optimization")
190         plt.legend()
191         plt.show()

 运行程序:

1 if __name__ == "__main__":
2 
3     bound = np.tile([[-600], [600]], 25)
4     aia = AIA(100, 25, bound, 100, [0.9, 0.1])
5     aia.solve()

 

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

posted on 2015-10-06 22:35  Alex Yu  阅读(5481)  评论(2编辑  收藏  举报

导航