Python 实现 遗传算法(GA)
Python Code (GA)
"""遗传算法实现求函数极大值"""
import numpy as np
import matplotlib.pyplot as plt
class GA():
'''genetic algorithm'''
def __init__(self,target_function,pop_size,cross_rate,mutate_rate,generation_n,x_bound,precision):
self.f=target_function
self.size=pop_size
self.cross_rate=cross_rate
self.mutate_rate=mutate_rate
self.generations_n=generation_n
self.x_bound=x_bound
self.precision=precision
self.DNA_length=int(np.log2((x_bound[1]-x_bound[0])/precision))+1
self.DNA_length=10
self.pop=np.random.randint(0,2,size=(self.size,self.DNA_length))
def fitness(self,y): return y-np.min(y)+1e-3
def binary_to_decimal(self,pop):