遗传算法的在python中的实现


一、前言

遗传算法是一种借鉴生物界自然选择和进化机制的随机优化法。它在求解一般全局优化问题时具有较好的鲁棒性,而且搜索不依赖梯度信息。本文将详细介绍遗传算法的相关概念,以及如何利用遗传算法寻找二元函数的最值。

二、遗传算法图解

在这里插入图片描述

三、遗传算法的基本流程

先为大家呈上完整的代码:

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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值