一个python元启发式优化库。目前支持遗传算法、引力搜索和交叉熵。
optimal的Python项目详细描述
最佳(β)
一个python元启发式优化库。易于扩展 以及用法。
警告:最佳是在测试版。API可能会改变。我会尽我最大的努力 此自述文件中的任何中断更改,但不提供任何保证。
支持的元启发式:
- 遗传算法(GA)
- 引力搜索算法(GSA)
- 交叉熵(ce)
安装
pip install optimal
用法
import math from optimal import GenAlg from optimal import Problem from optimal import helpers # The genetic algorithm uses binary solutions. # A decode function is useful for converting the binary solution to real numbers def decode_ackley(binary): # Helpful functions from helpers are used to convert binary to float # x1 and x2 range from -5.0 to 5.0 x1 = helpers.binary_to_float(binary[0:16], -5.0, 5.0) x2 = helpers.binary_to_float(binary[16:32], -5.0, 5.0) return x1, x2 # ackley is our fitness function # This is how a user defines the goal of their problem def ackley_fitness(solution): x1, x2 = solution # Ackley's function # A common mathematical optimization problem output = -20 * math.exp(-0.2 * math.sqrt(0.5 * (x1**2 + x2**2))) - math.exp( 0.5 * (math.cos(2 * math.pi * x1) + math.cos(2 * math.pi * x2))) + 20 + math.e # You can prematurely stop the metaheuristic by returning True # as the second return value # Here, we consider the problem solved if the output is <= 0.01 finished = output <= 0.01 # Because this function is trying to minimize the output, # a smaller output has a greater fitness fitness = 1 / output # First return argument must be a real number # The higher the number, the better the solution # Second return argument is a boolean, and optional return fitness, finished # Define a problem instance to optimize # We can optionally include a decode function # The optimizer will pass the decoded solution into your fitness function # Additional fitness function and decode function parameters can also be added ackley = Problem(ackley_fitness, decode_function=decode_ackley) # Create a genetic algorithm with a chromosome size of 32, # and use it to solve our problem my_genalg = GenAlg(32) best_solution = my_genalg.optimize(ackley) print best_solution
重要注意事项:
- 适应度函数必须以解作为其第一个参数
- 适应度函数必须返回实数作为其第一个返回值
有关更多使用详细信息,请参阅综合文档字符串。
重大变化
2017年8月27日
将多个选项从optimizer移动到optimizer.optimize
2017年7月26日
将common.random_solution_binary重命名为 公共随机二元解和公共随机解 common.random_real_解决方案
2016年10月11日
现在问题是optimizer.optimize的参数,而不是 优化器。
2016年10月11日
max_iterations现在是optimizer.optimize的参数,而不是 优化器。
2016年8月11日
优化器现在接受一个问题实例,而不是一个适应度函数 还有夸格斯。
2016年5月11日
重新组织的库更依赖于init.py。
优化器现在可以导入:
from optimal import GenAlg, GSA, CrossEntropy
等