Python 遗传算法库 Geatpy 深入

为了应对更加复杂的问题,不同的编码方式的问题,对此进行代码讲解,个人觉得这个遗传算法库做的很好,上手比较快,适用性很强,强烈推荐,用的很顺手。

示例说明:
a = [0~30连续数] * _num
b = [1 ~ num num个数排列排序] 即数列 1~num 不重复排列
c = [0~30离散数(整数)] * _num
score 设置为a,b,c进行运算后数列的最大值

import geatpy as ea
import numpy as np


# 示例说明:
# a = [0~30连续数] * _num
# b = [1 ~ num num个数排列排序] 即数列 1~num 不重复排列
# c = [0~30离散数(整数)] * _num
def func(a, b, c):
    return np.sin(np.pi * a * b) * np.cos(np.pi * c * b) * np.tan(np.pi * a * b * c)


# 初始化文件num大小
_num = 10


# 自定义 GA
class My_nsga(ea.Problem):
    def __init__(self):
        global _num
        name = 'GEATPY Facilitate Learning'
        # 只优化func一个变量
        M = 1
        # 最大化变量
        maxormins = [-1] * M
        # 一共有 a.size + b.size + c.size 个数
        Dim = _num + _num + _num
        # a 连续, b and c 离散
        varTypes = [0] * _num + [1] * _num + [1] * _num
        # a ∈ [0,30],  b ∈ [1,_num], c ∈ [0,30]
        lb = [0] * _num + [1] * _num + [0] * _num
        ub = [30] * _num + [_num] * _num + [30] * _num
        # 下限可取
        lbin = [1] * Dim
        # 上限可取
        ubin = [1] * Dim
        # 保存最大数据
        self.max_ans = 0
        # epoch
        self.epoch = 0
        # super
        ea.Problem.__init__(self, name, M, maxormins, Dim, varTypes, lb, ub, lbin, ubin)

    # 目标函数即神经网络返回值
    def evalVars(self, Vars):
        # init ans
        ans = np.zeros(len(Vars), dtype=float).reshape(len(Vars), 1)
        for i in range(len(Vars)):
            # 一定要确定区域选择是否正确
            a = Vars[i][:_num]
            # 可以选择int类型防止特定错误,因为正常输出时为float,具体问题可能会出错
            b = list(map(int, Vars[i][_num: _num + _num]))
            c = Vars[i][-_num:]
            score = func(a, b, c)
            ans[i] = score.max()
        self.max_ans = (now_max := ans.max())
        print(f"Epoch: {self.epoch + 1}, Epoch Max: {now_max}, Global Max: {self.max_ans}")
        self.epoch += 1
        return ans


# 运行 GA
def Run_nsga(ndind=10, maxgen=100, *args, **kwargs):
    global _num
    # init problem
    problem = My_nsga()
    # 染色体编码方式为[格雷编码,排列编码,格雷编码]
    encodings = ["RI", "P", "RI"]
    # 设置具体field,一定要多加这一部,geatpy还没有具体到能直接输入encoding: List[str],需要进行转换才能使用
    # 一定要注意数组范围,报错的话一定要仔细检查!!!
    field1 = ea.crtfld(encodings[0], problem.varTypes[:_num], problem.ranges[:, :_num], problem.borders[:, :_num])
    field2 = ea.crtfld(encodings[1], problem.varTypes[_num: _num + _num], problem.ranges[:, _num: _num + _num], problem.borders[:, _num: _num + _num])
    field3 = ea.crtfld(encodings[2], problem.varTypes[-_num:], problem.ranges[:, -_num:], problem.borders[:, -_num:])
    # 合并field
    fields = [field1, field2, field3]
    # 代入模板
    myAlgorithm = ea.soea_psy_EGA_templet(problem, ea.PsyPopulation(Encodings=encodings, Fields=fields, NIND=ndind), MAXGEN=maxgen, logTras=0)
    # 是否画图
    myAlgorithm.drawing = 0
    # 进行优化
    res = ea.optimize(myAlgorithm, seed=1, verbose=False, drawing=0, outputMsg=True, drawLog=False, saveFlag=False, dirName='result')
    return res['Vars'][0]


if __name__ == "__main__":
    Run_nsga(50, 1000)

如果你的问题还要复杂,需要对数据进行初始化,对种群进行初始化,使得模型训练更加可靠,可以在 ea.optimize 添加 prophet=prophet 。示例如下

def getProphet(dim, ndind, *args, **kwargs):
    prophet = np.zeros(shape=(ndind, dim), dtype=int)
    for i in range(ndind):
        prophet[i] = [random.random()] * dim
    return prophet


prophet = getProphet(_num * 3, ndind)
res = ea.optimize(myAlgorithm, prophet=prophet, seed=1, verbose=False, drawing=0, outputMsg=True, drawLog=False, saveFlag=False, dirName='result')

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用sko来实现Python中的遗传算法。在这个中,您可以使用GA类来创建遗传算法的实例,并设置相应的参数,如目标函数、变量维度、种群大小、迭代次数等。通过调用run()方法,您可以运行遗传算法并获取最佳解。 以下是一个使用sko实现遗传算法的示例代码: ``` import numpy as np from sko.GA import GA # 定义目标函数 demo_func = lambda x: x ** 2 + (x - 0.05) ** 2 + (x - 0.5) ** 2 # 创建遗传算法实例 ga = GA(func=demo_func, n_dim=3, size_pop=100, max_iter=500, lb=[-1, -10, -5], ub=[2, 10, 2], precision=[1e-7, 1e-7, 1]) # 运行遗传算法 best_x, best_y = ga.run() # 打印结果 print('best_x:', best_x, '\n', 'best_y:', best_y) ``` 上述代码中,我们首先定义了目标函数`demo_func`,然后使用GA类创建了一个遗传算法实例`ga`。接着通过调用run()方法,运行遗传算法,并获取最佳解`best_x`和最佳值`best_y`。最后,我们将结果打印出来。 请注意,上述代码仅作为示例,您可以根据自己的需求进行相应的修改和调整。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [一个易用、易部署的Python遗传算法](https://blog.csdn.net/yunqiinsight/article/details/108144993)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值