算法原理
to-do
Python代码
# -- coding: utf-8 --
import numpy as np
import math
def solve_p(domain):
N = 20
domain = np.asarray(domain)
temp = max(np.max(abs(domain),axis=0))
p = (len(bin(temp))-2)*N
return p
def randInit(p,num,paraNum):
'''随机生成随机数'''
xSum = [None]*paraNum
for i in range(paraNum):
x = [None]*num
for j in range(num):
temp = np.random.randint(0,2,p)
x[j] = ''.join(str(temp[j]) for j in range(p))
xSum[i] = x
return xSum
def bin2dec(p,b,num,paraNum):
maxNumBin = '1'*p
maxNumDec = int(maxNumBin,2)
d = [None]*paraNum
for i in range(paraNum):
temp = [None]*num
for j in range(num):
temp[j] = int(b[i][j],2)/maxNumDec
d[i] = temp
return d
def values(p,x,func,num,paraNum):
x = bin2dec(p,x,num,paraNum) #转换为十进制
v = [None]*num
for j in range(num):
temp = [None]*paraNum
for i in range(paraNum):
temp[i] = x[i][j]
v[j] = func(temp)
return v
def func(t):
y = -20*math.exp(-0.2*math.sqrt(0.5*(t[0]**2+t[1]**2)))-math.exp(0.5*(math.cos(2*math.pi*t[0])+math.cos(2*math.pi*t[1])))+22.71282
# y = t[0]**2+t[1]**2
return y
def copy(x,v,num,paraNum):
#轮盘赌算法
v = np.asarray(v)/sum(v)
cumV = [0]*num
for i in range(num):
cumV[i] = cumV[i-1] + v[i]
someList = [y for y in range(num)]
n = [0]*num
for i in range(num):
temp = np.random.random()
for j in range(num):
if temp < cumV[j]:
n[j] += 1
break
#生成复制
x2 = [None]*paraNum
for i in range(paraNum):
temp = [None]*num
for j in range(num):
temp[j] = x[i][j]
x2[i] = temp
return x2
def cross(x2,num,paraNum):
x3 = [None]*paraNum
flag = np.random.randint(0,num)
s = np.random.permutation(num) #partnership
for i in range(paraNum):
temp = [None]*num
for j in range(0,num-1,2):
temp[s[j]],temp[s[j+1]] = x2[i][s[j]][:flag]+x2[i][s[j+1]][flag:],x2[i][s[j+1]][:flag]+x2[i][s[j]][flag:]
for k in range(j+1,num):
temp[s[k]] = x2[i][s[k]]
x3[i] = temp
return x3
def heter(x3,p,pro,num,paraNum):
x4 = [None]*paraNum
for i in range(paraNum):
temp2 = [None]*num
for j in range(num):
temp = list(x3[i][j])
for k in range(p):
if np.random.random() < pro:
temp[k] = str((int(temp[k])+1)%2)
temp2[j] = ''.join(temp)
x4[i] = temp2
return x4
def dieOut(x5,v2,num,paraNum):
vS = list(enumerate(v2))
def takeSecond(elem):
return elem[1]
vS.sort(key=takeSecond,reverse=True)
xNext = [None]*paraNum
for i in range(paraNum):
temp = [None]*num
for j in range(num):
temp[j] = x[i][vS[j][0]]
xNext[i] = temp
return xNext
def out(p,x,num,paraNum):
print('最优取值为:',end='')
temp = [None]*paraNum
for i in range(paraNum):
temp[i] = bin2dec(p,x[i][0],1,1)
print(temp)
for j in range(paraNum):
for i in range(paraNum):
temp[i] = temp[i][0]
print('最优解为',func(temp))
num = 50 #种群个数
paraNum = 2 #变量个数
domain = [[-5,5],[-5,5]] #定义域
p = solve_p(domain)
x = randInit(p,num,paraNum)
iterTimes = 50
for i in range(iterTimes):
v = values(p,x,func,num,paraNum)
x2 = copy(x,v,num,paraNum)
x3 = cross(x2,num,paraNum)
x4 = heter(x3,p,0.001,num,paraNum)
v2 = values(p,x4,func,num,paraNum)
x5 = x+x4
x = dieOut(x5,v2,num,paraNum)
out(p,x,num,paraNum)