# -*- coding: cp936 -*-
import numpy as np
import math
import random
class DE():
def __init__(self,PN,dim,F,CR):
self.F = F
self.CR = CR
self.x_max = 5.12
self.x_min = -5.12
self.PN = PN #种群数量
self.dim = dim #基因个数
self.fit = np.zeros(self.PN)
self.X = np.zeros((self.PN,self.dim))
self.V = np.zeros((self.PN,self.dim))
self.U = np.zeros((self.PN, self.dim))
# Rastrigr 函数
def function(self,X):
f = 0
for i in range(0, len(X)):
f = f + (X[i] ** 2 - (10 * math.cos(2 * np.pi * X[i])) + 10)
return f
#----------------------------初始化种群-------------------------------------
def initpolulation(self):
for i in range(self.PN):
for j in range(self.dim):
self.X[i][j] = self.x_max +random.random()*(self.x_max-self.x_min)
# ----------------------------变异-------------------------------------
def mutation(self):
for i in range(self.PN):
r1 = random.randint(0,self.PN-1)
while i == r1:
r1 = random.randint(0, self.PN - 1)
r2 = random.randint(0, self.PN - 1)
while i == r2 | r1 == r2:
r2 = random.randint(0, self.PN - 1)
r3 = random.randint(0, self.PN - 1)
while i == r1 | r1 == r3 | r2 ==r3:
r3 = random.randint(0, self.PN - 1)
self.V[i] = self.X[r1] + self.F*(self.X[r2]-self.X[r3])
# ----------------------------交叉-------------------------------------
def cross(self):
for i in range(self.PN):
for j in range(self.dim):
if (self.CR >= random.random()) | (j == random.randint(0,self.dim-1)):
self.U[i][j] = self.V[i][j]
else:
self.U[i][j] = self.X[i][j]
# ----------------------------选择-------------------------------------
def select(self):
for i in range(self.PN):
if self.function(self.U[i]) <= self.function(self.X[i]):
self.X[i] = self.U[i]
else:
self.X[i] = self.X[i]
self.fit[i] = self.function(self.X[i])
print(min(self.fit))
return self.fit
if __name__ == '__main__':
DE = DE(100,10,0.6,0.7)
DE.initpolulation()
for t in range(2000):
DE.mutation()
DE.cross()
DE.select()
有错请指出,勿喷!