search
HomeBackend DevelopmentPython TutorialA brief introduction to the Python genetic algorithm Geatpy toolbox

[Related recommendations: Python3 video tutorial]

1. What is a genetic algorithm?

Genetic algorithm is a type of search algorithm constructed artificially by simulating the mechanism of biological genetics and natural selection. To a certain extent, genetic algorithm is a mathematical simulation of the biological evolution process. The survival process of biological populations generally follows Darwinian evolution principles. Individuals in the population are selected or eliminated by nature based on their ability to adapt to the environment. The result of the evolutionary process is reflected in the structure of the individual. Its chromosome contains several genes. The corresponding connection between phenotype and genotype reflects the logical relationship between the external characteristics and internal mechanism of the individual. Adapt to the natural environment through crossover and mutation between individuals. Biological chromosomes are represented mathematically or computerically as a string of numbers, still called chromosomes, sometimes also called individuals; adaptability is measured by a numerical value corresponding to a chromosome; the selection or elimination of chromosomes is based on the problem faced. Find the maximum or minimum.

2. Genetic Algorithm Library Geatpy

2.1 Introduction to Genetic Algorithm Toolbox Geatpy Parameters

API official reference document

population parameter[Important attributes: Chrom, Phen, Objv, CV, FitnV]

  • sizes: int - population size, that is, population number of individuals.
  • ChromNum: int - The number of chromosomes, that is, how many chromosomes each individual has.
  • Encoding: str - chromosome encoding method, 'BG': binary/Gray encoding; 'RI': real integer encoding, that is, a mixed encoding of real numbers and integers; 'P': permutation encoding
  • Field : array - decoding matrix
  • Chrom : array - population chromosome matrix, each row corresponds to a chromosome of an individual.
  • Lind : int - population chromosome length.
  • ObjV: array - population objective function value matrix, each row corresponds to an individual's objective function value, each column corresponds to a target
  • FitnV: array - population individual fitness column vector, each The element corresponds to the fitness of an individual, and the minimum fitness is 0
  • CV: array - CV (Constraint Violation Value) is a matrix used to quantitatively describe the degree of violation of constraint conditions. Each row corresponds to an individual, and each column corresponds to A constraint
  • Phen: array - the population phenotype matrix (that is, the matrix composed of the decision variables represented by each chromosome of the population after decoding).
  • If constraints are set based on the feasibility rule through the CV matrix, then the inequality constraints need to be ≤, and the equality constraints need to be passed into abs() (because it follows the principle that the larger the value, the smaller the fitness)

  • lbin and ubin (decision variable range) in ea.Problem.init() Boundary matrix) represents the opening and closing of the range interval, 1 closed 0 open interval

Geatpy result parameter introduction

success: True or False, indicates whether the algorithm was successfully solved.

stopMsg: A string that stores the reason for stopping the algorithm.

optPop: Population object that stores the algorithm solution results. If there is no feasible solution, optPop.sizes=0. optPop.Phen is the decision variable matrix, optPop.ObjV is the objective function value matrix.

lastPop: The last generation population object after the algorithm evolution is completed.

Vars: equal to optPop.Phen, here is the optimal solution. If there is no feasible solution, Vars=None.

ObjV: equal to optPop.ObjV, here is the objective function value corresponding to the optimal solution. If there is no feasible solution, ObjV=None.

CV: equal to optPop.CV, here is the constraint violation degree matrix corresponding to the optimal solution. If there is no feasible solution, CV=None.

startTime: Program execution start time.

endTime: Program execution end time.

executeTime: The time taken by the algorithm.

nfev: Number of algorithm evaluations

gd: (Available only when multi-objective optimization is given and the theoretical optimal solution is given) GD index value .

igd: (Available only when multi-objective optimization is given and the theoretical optimal solution is given) IGD indicator value.

hv: (only for multi-objective optimization) HV indicator value.

spacing: (only for multi-objective optimization) Spacing indicator value.

3. Best Practices

3.1 Code Example|Parameter Template

Solution Set:

header_regex = '|'.join(['{}'] * len(headers))
header_str = header_regex.format(*[str(key).center(width) for key, width in zip(headers, widths)])
print("=" * len(header_str))
            print(header_str)
            print("-" * len(header_str))

gen: evolutionary algebra
eval: record number of evaluations
f\_opt: objective function value of the contemporary optimal individual
f \_max=Maximum function value of the contemporary population                              
f\_min  Minimum  f\_avg  :  average                                                                                                                                                                                                            

3.2 Best Practice

Use the geatpy library to solve the shortest path of a directed acyclic graph

Code [Shortest Path] 1: Use the geatpy library

import numpy as np
import geatpy as ea
class MyProblem(ea.Problem):  # 继承Problem父类
    def __init__(self):
        name = 'Shortest_Path'  # 初始化name(函数名称,可以随意设置)
        M = 1  # 初始化M(目标维数)
        maxormins = [1]  # 初始化maxormins(目标最小最大化标记列表,1:最小化该目标;-1:最大化该目标)
        Dim = 10  # 初始化Dim(决策变量维数)
        varTypes = [1] * Dim  # 初始化varTypes(决策变量的类型,元素为0表示对应的变量是连续的;1表示是离散的)
        lb = [0] * Dim  # 决策变量下界
        ub = [9] * Dim  # 决策变量上界
        lbin = [1] * Dim  # 决策变量下边界 1表示闭合区间,0表示开区间
        ubin = [1] * Dim  # 决策变量上边界
        # 调用父类构造方法完成实例化
        ea.Problem.__init__(self, name, M, maxormins, Dim, varTypes, lb, ub, lbin, ubin)
        # 设置每一个结点下一步可达的结点(结点从1开始数,因此列表nodes的第0号元素设为空列表表示无意义)
        self.nodes = [[], [2, 3], [3, 4, 5], [5, 6], [7, 8], [4, 6], [7, 9], [8, 9], [9, 10], [10]]
        # 设置有向图中各条边的权重
        self.weights = {'(1, 2)': 36, '(1, 3)': 27, '(2, 4)': 18, '(2, 5)': 20, '(2, 3)': 13, '(3, 5)': 12,
                        '(3, 6)': 23,
                        '(4, 7)': 11, '(4, 8)': 32, '(5, 4)': 16, '(5, 6)': 30, '(6, 7)': 12, '(6, 9)': 38,
                        '(7, 8)': 20,
                        '(7, 9)': 32, '(8, 9)': 15, '(8, 10)': 24, '(9, 10)': 13}
    def decode(self, priority):  # 将优先级编码的染色体解码得到一条从节点1到节点10的可行路径
        edges = []  # 存储边
        path = [1]  # 结点1是路径起点
        while not path[-1] == 10:  # 开始从起点走到终点
            currentNode = path[-1]  # 得到当前所在的结点编号
            nextNodes = self.nodes[currentNode]  # 获取下一步可达的结点组成的列表
            chooseNode = nextNodes[np.argmax(
                priority[np.array(nextNodes) - 1])]  # 从NextNodes中选择优先级更高的结点作为下一步要访问的结点,因为结点从1数起,而下标从0数起,因此要减去1
            path.append(chooseNode)
            edges.append((currentNode, chooseNode))
        return path, edges
    def aimFunc(self, pop):  # 目标函数
        pop.ObjV = np.zeros((pop.sizes, 1))  # 初始化ObjV
        for i in range(pop.sizes):  # 遍历种群的每个个体,分别计算各个个体的目标函数值
            priority = pop.Phen[i, :]
            path, edges = self.decode(priority)  # 将优先级编码的染色体解码得到访问路径及经过的边
            pathLen = 0
            for edge in edges:
                key = str(edge)  # 根据路径得到键值,以便根据键值找到路径对应的长度
                if not key in self.weights:
                    raise RuntimeError("Error in aimFunc: The path is invalid. (当前路径是无效的。)", path)
                pathLen += self.weights[key]  # 将该段路径长度加入
            pop.ObjV[i] = pathLen  # 计算目标函数值,赋值给pop种群对象的ObjV属性
## 执行脚本
if __name__ == "__main__":
    # 实例化问题对象
    problem = MyProblem()
    # 构建算法
    algorithm = ea.soea_EGA_templet(problem,
                                    ea.Population(Encoding='RI', NIND=4),
                                    MAXGEN=10,  # 最大进化代数
                                    logTras=1)  # 表示每隔多少代记录一次日志信息
    # 求解
    res = ea.optimize(algorithm, verbose=True, drawing=1, outputMsg=False, drawLog=False, saveFlag=True,
                      dirName='result')
    print('最短路程为:%s' % (res['ObjV'][0][0]))
    print('最佳路线为:')
    best_journey, edges = problem.decode(res['Vars'][0])
    for i in range(len(best_journey)):
        print(int(best_journey[i]), end=' ')
    print()

[Related recommendations:

Python3 video tutorial

]

The above is the detailed content of A brief introduction to the Python genetic algorithm Geatpy toolbox. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment