MEALPY is the largest python library in the world for most of the cutting-edge meta-heuristic algorithms (nature-inspired algorithms, black-box optimization, global search optimizers, iterative learning algorithms, continuous optimization, derivative free optimization, gradient free optimization, zeroth order optimization, stochastic search optimization, random search optimization). These algorithms belong to population-based algorithms (PMA), which are the most popular algorithms in the field of approximate optimization.
Please include these citations if you plan to use this library:
@article{van2023mealpy, title={MEALPY: An open-source library for latest meta-heuristic algorithms in Python}, author={Van Thieu, Nguyen and Mirjalili, Seyedali}, journal={Journal of Systems Architecture}, year={2023}, publisher={Elsevier}, doi={10.1016/j.sysarc.2023.102871} } @article{van2023groundwater, title={Groundwater level modeling using Augmented Artificial Ecosystem Optimization}, author={Van Thieu, Nguyen and Barma, Surajit Deb and Van Lam, To and Kisi, Ozgur and Mahesha, Amai}, journal={Journal of Hydrology}, volume={617}, pages={129034}, year={2023}, publisher={Elsevier}, doi={https://doi.org/10.1016/j.jhydrol.2022.129034} } @article{ahmed2021comprehensive, title={A comprehensive comparison of recent developed meta-heuristic algorithms for streamflow time series forecasting problem}, author={Ahmed, Ali Najah and Van Lam, To and Hung, Nguyen Duy and Van Thieu, Nguyen and Kisi, Ozgur and El-Shafie, Ahmed}, journal={Applied Soft Computing}, volume={105}, pages={107282}, year={2021}, publisher={Elsevier}, doi={10.1016/j.asoc.2021.107282} }
Our goals are to implement all classical as well as the state-of-the-art nature-inspired algorithms, create a simple interface that helps researchers access optimization algorithms as quickly as possible, and share knowledge of the optimization field with everyone without a fee. What you can do with mealpy:
$ pip install mealpy==3.0.1
$ pip install mealpy==2.5.4a6
$ git clone https://github.com/thieu1995/mealpy.git $ cd mealpy $ python setup.py install
$ pip install git+https://github.com/thieu1995/permetrics
After installation, you can import Mealpy as any other Python module:
</details>$ python >>> import mealpy >>> mealpy.__version__ >>> print(mealpy.get_all_optimizers()) >>> model = mealpy.get_optimizer_by_name("OriginalWOA")(epoch=100, pop_size=50)
Before dive into some examples, let me ask you a question. What type of problem are you trying to solve? Additionally, what would be the solution for your specific problem? Based on the table below, you can select an appropriate type of decision variables to use.
<div align="center">Class | Syntax | Problem Types |
---|---|---|
FloatVar | FloatVar(lb=(-10., )*7, ub=(10., )*7, name="delta") | Continuous Problem |
IntegerVar | IntegerVar(lb=(-10., )*7, ub=(10., )*7, name="delta") | LP, IP, NLP, QP, MIP |
StringVar | StringVar(valid_sets=(("auto", "backward", "forward"), ("leaf", "branch", "root")), name="delta") | ML, AI-optimize |
BinaryVar | BinaryVar(n_vars=11, name="delta") | Networks |
BoolVar | BoolVar(n_vars=11, name="delta") | ML, AI-optimize |
PermutationVar | PermutationVar(valid_set=(-10, -4, 10, 6, -2), name="delta") | Combinatorial Optimization |
MixedSetVar | MixedSetVar(valid_sets=(("auto", 2, 3, "backward", True), (0, "tournament", "round-robin")), name="delta") | MIP, MILP |
TransferBoolVar | TransferBoolVar(n_vars=11, name="delta", tf_func="sstf_02") | ML, AI-optimize, Feature |
TransferBinaryVar | TransferBinaryVar(n_vars=11, name="delta", tf_func="vstf_04") | Networks, Feature Selection |
Let's go through a basic and advanced example.
Using Problem dict
from mealpy import FloatVar, SMA import numpy as np def objective_function(solution): return np.sum(solution**2) problem = { "obj_func": objective_function, "bounds": FloatVar(lb=(-100., )*30, ub=(100., )*30), "minmax": "min", "log_to": None, } ## Run the algorithm model = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) g_best = model.solve(problem) print(f"Best solution: {g_best.solution}, Best fitness: {g_best.target.fitness}")
Define a custom Problem class
Please note that, there is no more generate_position
, amend_solution
, and fitness_function
in Problem class.
We take care everything under the DataType Class above. Just choose which one fit for your problem.
We recommend you define a custom class that inherit Problem
class if your decision variable is not FloatVar
from mealpy import Problem, FloatVar, BBO import numpy as np # Our custom problem class class Squared(Problem): def __init__(self, bounds=None, minmax="min", data=None, **kwargs): self.data = data super().__init__(bounds, minmax, **kwargs) def obj_func(self, solution): x = self.decode_solution(solution)["my_var"] return np.sum(x ** 2) ## Now, we define an algorithm, and pass an instance of our *Squared* class as the problem argument. bound = FloatVar(lb=(-10., )*20, ub=(10., )*20, name="my_var") problem = Squared(bounds=bound, minmax="min", name="Squared", data="Amazing") model = BBO.OriginalBBO(epoch=100, pop_size=20) g_best = model.solve(problem)
You can set random seed number for each run of single optimizer.
model = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) g_best = model.solve(problem=problem, seed=10) # Default seed=None
from mealpy import FloatVar, SHADE import numpy as np def objective_function(solution): return np.sum(solution**2) problem = { "obj_func": objective_function, "bounds": FloatVar(lb=(-1000., )*10000, ub=(1000.,)*10000), # 10000 dimensions "minmax": "min", "log_to": "console", } ## Run the algorithm optimizer = SHADE.OriginalSHADE(epoch=10000, pop_size=100) g_best = optimizer.solve(problem) print(f"Best solution: {g_best.solution}, Best fitness: {g_best.target.fitness}")
Please read the article titled MEALPY: An open-source library for latest meta-heuristic algorithms in Python to gain a clear understanding of the concept of parallelization (distributed optimization) in metaheuristics. Not all metaheuristics can be run in parallel.
from mealpy import FloatVar, SMA import numpy as np def objective_function(solution): return np.sum(solution**2) problem = { "obj_func": objective_function, "bounds": FloatVar(lb=(-100., )*100, ub=(100., )*100), "minmax": "min", "log_to": "console", } ## Run distributed SMA algorithm using 10 threads optimizer = SMA.OriginalSMA(epoch=10000, pop_size=100, pr=0.03) optimizer.solve(problem, mode="thread", n_workers=10) # Distributed to 10 threads print(f"Best solution: {optimizer.g_best.solution}, Best fitness: {optimizer.g_best.target.fitness}") ## Run distributed SMA algorithm using 8 CPUs (cores) optimizer.solve(problem, mode="process", n_workers=8) # Distributed to 8 cores print(f"Best solution: {optimizer.g_best.solution}, Best fitness: {optimizer.g_best.target.fitness}")
In this example, we use SMA optimize to optimize the hyper-parameters of SVC model.
from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn import datasets, metrics from mealpy import FloatVar, StringVar, IntegerVar, BoolVar, MixedSetVar, SMA, Problem # Load the data set; In this example, the breast cancer dataset is loaded. X, y = datasets.load_breast_cancer(return_X_y=True) # Create training and test split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1, stratify=y) sc = StandardScaler() X_train_std = sc.fit_transform(X_train) X_test_std = sc.transform(X_test) data = { "X_train": X_train_std, "X_test": X_test_std, "y_train": y_train, "y_test": y_test } class SvmOptimizedProblem(Problem): def __init__(self, bounds=None, minmax="max", data=None, **kwargs): self.data = data super().__init__(bounds, minmax, **kwargs) def obj_func(self, x): x_decoded = self.decode_solution(x) C_paras, kernel_paras = x_decoded["C_paras"], x_decoded["kernel_paras"] degree, gamma, probability = x_decoded["degree_paras"], x_decoded["gamma_paras"], x_decoded["probability_paras"] svc = SVC(C=C_paras, kernel=kernel_paras, degree=degree, gamma=gamma, probability=probability, random_state=1) # Fit the model svc.fit(self.data["X_train"], self.data["y_train"]) # Make the predictions y_predict = svc.predict(self.data["X_test"]) # Measure the performance return metrics.accuracy_score(self.data["y_test"], y_predict) my_bounds = [ FloatVar(lb=0.01, ub=1000., name="C_paras"), StringVar(valid_sets=('linear', 'poly', 'rbf', 'sigmoid'), name="kernel_paras"), IntegerVar(lb=1, ub=5, name="degree_paras"), MixedSetVar(valid_sets=('scale', 'auto', 0.01, 0.05, 0.1, 0.5, 1.0), name="gamma_paras"), BoolVar(n_vars=1, name="probability_paras"), ] problem = SvmOptimizedProblem(bounds=my_bounds, minmax="max", data=data) model = SMA.OriginalSMA(epoch=100, pop_size=20) model.solve(problem) print(f"Best agent: {model.g_best}") print(f"Best solution: {model.g_best.solution}") print(f"Best accuracy: {model.g_best.target.fitness}") print(f"Best parameters: {model.problem.decode_solution(model.g_best.solution)}")
Traveling Salesman Problem (TSP)
In the context of the Mealpy for the Traveling Salesman Problem (TSP), a solution is a possible route that represents a tour of visiting all the cities exactly once and returning to the starting city. The solution is typically represented as a permutation of the cities, where each city appears exactly once in the permutation.
For example, let's consider a TSP instance with 5 cities labeled as A, B, C, D, and E. A possible solution could be
represented as the permutation [A, B, D, E, C]
, which indicates the order in which the cities are visited. This
solution suggests that the tour starts at city A, then moves to city B, then D, E, and finally C before returning to city A.
import numpy as np from mealpy import PermutationVar, WOA, Problem # Define the positions of the cities city_positions = np.array([[60, 200], [180, 200], [80, 180], [140, 180], [20, 160], [100, 160], [200, 160], [140, 140], [40, 120], [100, 120], [180, 100], [60, 80], [120, 80], [180, 60], [20, 40], [100, 40], [200, 40], [20, 20], [60, 20], [160, 20]]) num_cities = len(city_positions) data = { "city_positions": city_positions, "num_cities": num_cities, } class
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多 个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供 海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。
openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。
高分辨率纹理 3D 资产生成
Hunyuan3D-2 是腾讯开发的用于 3D 资产生成的强大工具,支持从文本描述、单张图片或多视角图片生成 3D 模型,具备快速形状生成能力,可生成带纹理的高质量 3D 模型,适用于多个领域,为 3D 创作提供了高效解决方案。
一个具备存储、管理和客户端操作等多种功能的分布式文件系统相关项目。
3FS 是一个功能强大的分布式文件系统项目,涵盖了存储引擎、元数据管理、客户端工具等多个模块。它支持多种文件操作,如创建文件和目录、设置布局等,同时具备高效的事件循环、节点选择和协程池管理等特性。适用于需要大规模数据存储和管理的场景,能够提高系统的性能和可靠性,是分布式存储领域的优质解决方案。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号