Python实现的群体智能算法 (遗传算法、粒子群优化、模拟退火、蚁群算法、免疫算法、人工鱼群算法的Python实现)
pip install scikit-opt
对于当前开发版本:
git clone git@github.com:guofei9987/scikit-opt.git cd scikit-opt pip install .
现在支持UDF(用户自定义函数)!
例如,你刚刚开发了一种新的选择
函数。
现在,你的选择
函数如下所示:
-> 示例代码:examples/demo_ga_udf.py#s1
# 步骤1:定义你自己的操作符: def selection_tournament(algorithm, tourn_size): FitV = algorithm.FitV sel_index = [] for i in range(algorithm.size_pop): aspirants_index = np.random.choice(range(algorithm.size_pop), size=tourn_size) sel_index.append(max(aspirants_index, key=lambda i: FitV[i])) algorithm.Chrom = algorithm.Chrom[sel_index, :] # 下一代 return algorithm.Chrom
导入并构建遗传算法 -> 示例代码:examples/demo_ga_udf.py#s2
import numpy as np from sko.GA import GA, GA_TSP demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + (x[2] - 0.5) ** 2 ga = GA(func=demo_func, n_dim=3, size_pop=100, max_iter=500, prob_mut=0.001, lb=[-1, -10, -5], ub=[2, 10, 2], precision=[1e-7, 1e-7, 1])
将你的自定义函数注册到遗传算法中 -> 示例代码:examples/demo_ga_udf.py#s3
ga.register(operator_name='selection', operator=selection_tournament, tourn_size=3)
scikit-opt还提供了一些操作符 -> 示例代码:examples/demo_ga_udf.py#s4
from sko.operators import ranking, selection, crossover, mutation ga.register(operator_name='ranking', operator=ranking.ranking). \ register(operator_name='crossover', operator=crossover.crossover_2point). \ register(operator_name='mutation', operator=mutation.mutation)
现在像往常一样运行遗传算法 -> 示例代码:examples/demo_ga_udf.py#s5
best_x, best_y = ga.run() print('best_x:', best_x, '\n', 'best_y:', best_y)
目前,udf支持遗传算法的
交叉
、变异
、选择
和排序
scikit-opt提供了十几种操作符,详见这里
对于高级用户:
-> 示例代码:examples/demo_ga_udf.py#s6
class MyGA(GA): def selection(self, tourn_size=3): FitV = self.FitV sel_index = [] for i in range(self.size_pop): aspirants_index = np.random.choice(range(self.size_pop), size=tourn_size) sel_index.append(max(aspirants_index, key=lambda i: FitV[i])) self.Chrom = self.Chrom[sel_index, :] # 下一代 return self.Chrom ranking = ranking.ranking demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + (x[2] - 0.5) ** 2 my_ga = MyGA(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 = my_ga.run() print('best_x:', best_x, '\n', 'best_y:', best_y)
(0.3.6版本新增) 运行算法10次迭代,然后基于前10次迭代再运行20次迭代:
from sko.GA import GA func = lambda x: x[0] ** 2 ga = GA(func=func, n_dim=1) ga.run(10) ga.run(20)
详见 https://github.com/guofei9987/scikit-opt/blob/master/examples/example_function_modes.py
我们正在开发GPU计算功能,将在1.0.0版本稳定发布。 目前已有可用示例:https://github.com/guofei9987/scikit-opt/blob/master/examples/demo_ga_gpu.py
第1步:定义问题
-> 示例代码:examples/demo_de.py#s1
''' 最小化 f(x1, x2, x3) = x1^2 + x2^2 + x3^2 约束条件: x1*x2 >= 1 x1*x2 <= 5 x2 + x3 = 1 0 <= x1, x2, x3 <= 5 ''' def obj_func(p): x1, x2, x3 = p return x1 ** 2 + x2 ** 2 + x3 ** 2 constraint_eq = [ lambda x: 1 - x[1] - x[2] ] constraint_ueq = [ lambda x: 1 - x[0] * x[1], lambda x: x[0] * x[1] - 5 ]
第2步:执行差分进化算法
-> 示例代码:examples/demo_de.py#s2
from sko.DE import DE de = DE(func=obj_func, n_dim=3, size_pop=50, max_iter=800, lb=[0, 0, 0], ub=[5, 5, 5], constraint_eq=constraint_eq, constraint_ueq=constraint_ueq) best_x, best_y = de.run() print('最优解:', best_x, '\n', '最优值:', best_y)
第1步:定义问题
-> 示例代码:examples/demo_ga.py#s1
import numpy as np def schaffer(p): ''' 该函数有大量局部最小值,具有强烈震荡 全局最小值在(0,0)处,取值为0 https://en.wikipedia.org/wiki/Test_functions_for_optimization ''' x1, x2 = p part1 = np.square(x1) - np.square(x2) part2 = np.square(x1) + np.square(x2) return 0.5 + (np.square(np.sin(part1)) - 0.5) / np.square(1 + 0.001 * part2)
第2步:执行遗传算法
-> 示例代码:examples/demo_ga.py#s2
from sko.GA import GA ga = GA(func=schaffer, n_dim=2, size_pop=50, max_iter=800, prob_mut=0.001, lb=[-1, -1], ub=[1, 1], precision=1e-7) best_x, best_y = ga.run() print('最优解:', best_x, '\n', '最优值:', best_y)
-> 示例代码:examples/demo_ga.py#s3
import pandas as pd import matplotlib.pyplot as plt Y_history = pd.DataFrame(ga.all_history_Y) fig, ax = plt.subplots(2, 1) ax[0].plot(Y_history.index, Y_history.values, '.', color='red') Y_history.min(axis=1).cummin().plot(kind='line') plt.show()
只需导入GA_TSP
,它重载了crossover
和mutation
以解决TSP问题
第1步:定义问题。准备好点的坐标和距离矩阵。
这里我随机生成数据作为演示:
-> 示例代码:examples/demo_ga_tsp.py#s1
import numpy as np from scipy import spatial import matplotlib.pyplot as plt num_points = 50 points_coordinate = np.random.rand(num_points, 2) # 生成点的坐标 distance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean') def cal_total_distance(routine): '''目标函数。输入路线,返回总距离。 cal_total_distance(np.arange(num_points)) ''' num_points, = routine.shape return sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])
第2步:执行遗传算法
-> 示例代码:examples/demo_ga_tsp.py#s2
from sko.GA import GA_TSP ga_tsp = GA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=50, max_iter=500, prob_mut=1) best_points, best_distance = ga_tsp.run()
第3步:绘制结果:
-> 示例代码:examples/demo_ga_tsp.py#s3
fig, ax = plt.subplots(1, 2) best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r') ax[1].plot(ga_tsp.generation_best_Y) plt.show()
步骤1:定义你的问题: -> 示例代码:examples/demo_pso.py#s1
def demo_func(x): x1, x2, x3 = x return x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2
步骤2:执行PSO -> 示例代码:examples/demo_pso.py#s2
from sko.PSO import PSO pso = PSO(func=demo_func, n_dim=3, pop=40, max_iter=150, lb=[0, -1, 0.5], ub=[1, 1, 1], w=0.8, c1=0.5, c2=0.5) pso.run() print('最优x为', pso.gbest_x, '最优y为', pso.gbest_y)
步骤3:绘制结果 -> 示例代码:examples/demo_pso.py#s3
import matplotlib.pyplot as plt plt.plot(pso.gbest_y_hist) plt.show()
如果你需要非线性约束,比如 (x[0] - 1) ** 2 + (x[1] - 0) ** 2 - 0.5 ** 2<=0
代码如下:
constraint_ueq = ( lambda x: (x[0] - 1) ** 2 + (x[1] - 0) ** 2 - 0.5 ** 2 , ) pso = PSO(func=demo_func, n_dim=2, pop=40, max_iter=max_iter, lb=[-2, -2], ub=[2, 2] , constraint_ueq=constraint_ueq)
注意,你可以添加多个非线性约束。只需将它们添加到 constraint_ueq
中
此外,我们还有一个动画:
↑查看 examples/demo_pso_ani.py
步骤1:定义你的问题 -> 示例代码:examples/demo_sa.py#s1
demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2
步骤2:执行SA -> 示例代码:examples/demo_sa.py#s2
from sko.SA import SA sa = SA(func=demo_func, x0=[1, 1, 1], T_max=1, T_min=1e-9, L=300, max_stay_counter=150) best_x, best_y = sa.run() print('最优x:', best_x, '最优y', best_y)
步骤3:绘制结果 -> 示例代码:examples/demo_sa.py#s3
import matplotlib.pyplot as plt import pandas as pd plt.plot(pd.DataFrame(sa.best_y_history).cummin(axis=0)) plt.show()
此外,scikit-opt提供了3种类型的模拟退火算法:快速退火、玻尔兹曼退火和柯西退火。查看更多SA信息
步骤1:哦,是的,定义你的问题。太无聊了,就不复制这一步了。
步骤2:对TSP执行SA -> 示例代码:examples/demo_sa_tsp.py#s2
from sko.SA import SA_TSP sa_tsp = SA_TSP(func=cal_total_distance, x0=range(num_points), T_max=100, T_min=1, L=10 * num_points) best_points, best_distance = sa_tsp.run() print(best_points, best_distance, cal_total_distance(best_points))
步骤3:绘制结果 -> 示例代码:examples/demo_sa_tsp.py#s3
from matplotlib.ticker import FormatStrFormatter fig, ax = plt.subplots(1, 2) best_points_ = np.concatenate([best_points, [best_points[0]]]) best_points_coordinate = points_coordinate[best_points_, :] ax[0].plot(sa_tsp.best_y_history) ax[0].set_xlabel("迭代次数") ax[0].set_ylabel("距离") ax[1].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], marker='o', markerfacecolor='b', color='c', linestyle='-') ax[1].xaxis.set_major_formatter(FormatStrFormatter('%.3f')) ax[1].yaxis.set_major_formatter(FormatStrFormatter('%.3f')) ax[1].set_xlabel("经度") ax[1].set_ylabel("纬度") plt.show()
更多:绘制动画:
-> 示例代码:examples/demo_aca_tsp.py#s2
from sko.ACA import ACA_TSP aca = ACA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=50, max_iter=200, distance_matrix=distance_matrix) best_x, best_y = aca.run()
-> 示例代码:examples/demo_ia.py#s2
from sko.IA import IA_TSP ia_tsp = IA_TSP(func=cal_total_distance, n_dim=num_points, size_pop=500, max_iter=800, prob_mut=0.2, T=0.7, alpha=0.95) best_points, best_distance = ia_tsp.run() print('最佳路线:', best_points, '最短距离:', best_distance)
-> 示例 代码:examples/demo_afsa.py#s1
def func(x): x1, x2 = x return 1 / x1 ** 2 + x1 ** 2 + 1 / x2 ** 2 + x2 ** 2 from sko.AFSA import AFSA afsa = AFSA(func, n_dim=2, size_pop=50, max_iter=300, max_try_num=100, step=0.5, visual=0.3, q=0.98, delta=0.5) best_x, best_y = afsa.run() print(best_x, best_y)
一键生成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项目落地
微信扫一扫关注公众号