本文共 1932 字,大约阅读时间需要 6 分钟。
#随机搜索domain是序列,costf是定义的成本函数def randomoptimize(domain,costf): best=999999999 bestr=None for i in range(0,1000): # 创建一个随机解 r=[float(random.randint(domain[i][0],domain[i][1])) for i in range(len(domain))] # Get the cost cost=costf(r) # Compare it to the best one so far if cost
#爬山法,从一个随机解开始,到临近找更好的方法,不会随机浪费时间def hillclimb(domain,costf): # Create a random solution sol=[random.randint(domain[i][0],domain[i][1]) for i in range(len(domain))] # Main loop while 1: # Create list of neighboring solutions neighbors=[] for j in range(len(domain)): # One away in each direction if sol[j]>domain[j][0]: neighbors.append(sol[0:j]+[sol[j]+1]+sol[j+1:]) if sol[j]
(开始阶段可以接受较差的解,随着温度减少,只会接受更好的解)
#模拟退火算法,爬山法可能只是局部最优解,退火会接受较差的解,但是差异越大,概率越低,最后抛弃**
#模拟退火算法,爬山法可能只是局部最优解,退火会接受较差的解,但是差异越大,概率越低,最后抛弃def annealingoptimize(domain,costf,T=10000.0,cool=0.95,step=1): # Initialize the values randomly vec=[float(random.randint(domain[i][0],domain[i][1])) for i in range(len(domain))] while T>0.1: # Choose one of the indices i=random.randint(0,len(domain)-1) # Choose a direction to change it dir=random.randint(-step,step) # Create a new list with one of the values changed vecb=vec[:] vecb[i]+=dir if vecb[i]domain[i][1]: vecb[i]=domain[i][1] # Calculate the current cost and the new cost ea=costf(vec) eb=costf(vecb) p=pow(math.e,(-eb-ea)/T) # Is it better, or does it make the probability # cutoff? if (eb
先随机生成一组解,称为种群。计算整个种群的成本函数。创建新种群:1精英选拔最好的解;2修改题解(变异:微小变化)(交叉配对:题解组合)
#遗传算法def geneoptimize(domain,costf,popsize=50,step=1,mutprob=0.2,elite=0.2,maxiter=100):#maxiter代数,mutprob变异的概率,elite遗传概率 # Mutation Operation def mutate(vec): i=random.randint(0,len(domain)-1) if random.random()<0.5 and vec[i]>domain[i][0]: return vec[0:i]+[vec[i]-step]+vec[i+1:] elif vec[i]
转载地址:http://rlhdi.baihongyu.com/