Project Icon

mealpy

元启发式算法优化库实现多种优化算法

MEALPY实现了215种元启发式算法,是当前最全面的Python优化库之一。它可解决连续和离散优化等多种问题,支持参数分析、性能评估和收敛分析。该库设计简洁,提供结果导出和模型导入导出功能,适用于各类优化任务。MEALPY兼容Python 3.7+,依赖numpy等科学计算库。

MEALPY


GitHub release Wheel PyPI version PyPI - Python Version PyPI - Status PyPI - Downloads Downloads Tests & Publishes to PyPI GitHub Release Date Documentation Status Chat Average time to resolve an issue Percentage of issues still open GitHub contributors GitTutorial DOI License: GPL v3

Introduction

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.

  • Free software: GNU General Public License (GPL) V3 license
  • Total algorithms: 215 (190 official (original, hybrid, variants), 25 developed)
  • Documentation: https://mealpy.readthedocs.io/en/latest/
  • Python versions: >=3.7x
  • Dependencies: numpy, scipy, pandas, matplotlib

MEALPY3-0-0

Citation Request

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}
}

Usage

Goals

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:

  • Analyse parameters of meta-heuristic algorithms.
  • Perform Qualitative and Quantitative Analysis of algorithms.
  • Analyse rate of convergence of algorithms.
  • Test and Analyse the scalability and the robustness of algorithms.
  • Save results in various formats (csv, json, pickle, png, pdf, jpeg)
  • Export and import models can also be done with Mealpy.
  • Solve any optimization problem

Installation

$ pip install mealpy==3.0.1
  • Install the alpha/beta version from PyPi
$ pip install mealpy==2.5.4a6
  • Install the pre-release version directly from the source code:
$ git clone https://github.com/thieu1995/mealpy.git
$ cd mealpy
$ python setup.py install
  • In case, you want to install the development version from Github:
$ pip install git+https://github.com/thieu1995/permetrics 

After installation, you can import Mealpy as any other Python module:

$ python
>>> import mealpy
>>> mealpy.__version__

>>> print(mealpy.get_all_optimizers())
>>> model = mealpy.get_optimizer_by_name("OriginalWOA")(epoch=100, pop_size=50)

Examples

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.

ClassSyntaxProblem Types
FloatVarFloatVar(lb=(-10., )*7, ub=(10., )*7, name="delta")Continuous Problem
IntegerVarIntegerVar(lb=(-10., )*7, ub=(10., )*7, name="delta")LP, IP, NLP, QP, MIP
StringVarStringVar(valid_sets=(("auto", "backward", "forward"), ("leaf", "branch", "root")), name="delta")ML, AI-optimize
BinaryVarBinaryVar(n_vars=11, name="delta")Networks
BoolVarBoolVar(n_vars=11, name="delta")ML, AI-optimize
PermutationVarPermutationVar(valid_set=(-10, -4, 10, 6, -2), name="delta")Combinatorial Optimization
MixedSetVarMixedSetVar(valid_sets=(("auto", 2, 3, "backward", True), (0, "tournament", "round-robin")), name="delta")MIP, MILP
TransferBoolVarTransferBoolVar(n_vars=11, name="delta", tf_func="sstf_02")ML, AI-optimize, Feature
TransferBinaryVarTransferBinaryVar(n_vars=11, name="delta", tf_func="vstf_04")Networks, Feature Selection

Let's go through a basic and advanced example.

Simple Benchmark Function

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)

Set Seed for Optimizer (So many people asking for this feature)

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

Large-Scale Optimization

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}")

Distributed Optimization / Parallelization Optimization

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}")

The Benefit Of Using Custom Problem Class (BEST PRACTICE)

Optimize Machine Learning model

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)}")

Solving Combinatorial Problems

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
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号