文章目录
一、前言
遗传算法是一种借鉴生物界自然选择和进化机制的随机优化法。它在求解一般全局优化问题时具有较好的鲁棒性,而且搜索不依赖梯度信息。本文将详细介绍遗传算法的相关概念,以及如何利用遗传算法寻找二元函数的最值。
二、遗传算法图解
三、遗传算法的基本流程
先为大家呈上完整的代码:
import numpy as np
def decode(population,bounds,pop_size,dna_size):
try:
# 尝试访问第二个元素的第一个子元素
dna_x = population[:, 1::2]
dna_y = population[:, ::2]
except (IndexError, TypeError):
dna_x = population[1::2]
dna_y = population[::2]
x = (dna_x.dot(2 ** np.arange(dna_size)[::-1]) /
float(2 ** dna_size - 1) * (bounds[1] - bounds[0]) + bounds[0])
y = (dna_y.dot(2 ** np.arange(dna_size)[::-1]) /
float(2 ** dna_size - 1) * (bounds[1] - bounds[0]) + bounds[0])
return x, y
class genetic:
def __init__(self,F,bounds,pop_size,dna_size, cross_rate, mtation_rate, method):
self.F = F
self.bounds = bounds
self.pop_size = pop_size
self.dna_size = dna_size
self.cross_rate = cross_rate
self.mtation_rate = mtation_rate
self.method = method
def initialize_population(self):
population = np.random.randint(2, size=(self.pop_size, self.dna_size * 2))
return population
def evaluate_fitness(self,population):
x, y = decode(population,self.bounds,self.pop_size,self.dna_size)
fitness = self.F(x,y)
return fitness
def select(self, population, fitness):
selection = []
for i in range(self.pop_size):
index = np.random.randint(self.pop_size)
if self.method == 'max':
winner = i if fitness[i] >= fitness[index] else index
elif self.method == 'min':
winner = i if fitness[i] <= fitness[index] else index
else:
raise ValueError('method 只能是 max 或 min')
selection.append(population[winner])
return selection
def crossover(self,selection):
child = []
for i in range(0, self.pop_size, 2):
father, mother = selection[i], selection[(i + 1) % len(selection)]
child1 = father.copy()
child2 = mother.copy()
if np.random.rand() < self.cross_rate:
cross_points = np.random.randint(low=0, high=self.dna_size * 2)
child1[cross_points:] = mother[cross_points:]
child2[cross_points:] = father[cross_points:]
child.append(child1)
child.append(child2)
return child
def mutation(self, child):
for i in range(len(child))