【算法】第二代遗传算法NSGA-II优化SVR超参数模型

news/2025/2/21 18:48:54/

NSGA-II介绍

NSGA-II(Non-dominated Sorting Genetic Algorithm II)是一种多目标优化算法,用于解决具有多个冲突目标的优化问题。它通过模拟进化过程中的自然选择和遗传操作,逐步改进种群中的解,以找到一组尽可能好的解,这些解在多个目标下都是非支配的(Pareto优解)。

建模目的

用NSGA-II实现对SVR超参数的寻优,找到SVR最优的超参数C和对应的评价指标RMSE,超参数C范围(0.01, 10),迭代次数5,种群大小5。
ps:超参数范围、迭代次数、种群大小可自定义

模型源码

import random
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from sklearn.svm import SVRfrom sklearn.metrics import mean_squared_error
# 设置参数
pop_size = 5  # 种群大小
gen_size = 5  # 进化代数
pc = 1  # 交叉概率
pm = 0.3  # 变异概率
num_obj = 1  # 目标函数个数
x_range = (0.01, 10)  # 自变量取值范围
data = pd.read_excel('C:/Users/孙海涛/Desktop/x.xlsx', sheet_name='Sheet1')  # 读取数据
target = pd.read_excel('C:/Users/孙海涛/Desktop/y.xlsx', sheet_name='Sheet1')  # 读取数据
x_train, x_test, y_train, y_test = train_test_split(data, target, random_state=22, test_size=0.25)# 定义自变量的类
class Individual:def __init__(self, x):self.x = xself.objs = [None] * num_objself.rank = Noneself.distance = 0.0# 计算目标函数的值def evaluate(self):c = self.xmodel_svr = SVR(C=c)model_svr.fit(x_train, y_train)predict_results = model_svr.predict(x_test)#rmseself.objs[0] =np.sqrt(mean_squared_error(y_test, predict_results))# 初始化种群
pop = [Individual(random.uniform(*x_range)) for _ in range(pop_size)]# 进化
for _ in range(gen_size):print(f"第{_}次迭代")# 计算目标函数的值for ind in pop:ind.evaluate()# 非支配排序fronts = [set()]for ind in pop:ind.domination_count = 0ind.dominated_set = set()for other in pop:if ind.objs[0] < other.objs[0] :ind.dominated_set.add(other)elif ind.objs[0] > other.objs[0] :ind.domination_count += 1if ind.domination_count == 0:ind.rank = 1fronts[0].add(ind)rank = 1while fronts[-1]:next_front = set()for ind in fronts[-1]:ind.rank = rankfor dominated_ind in ind.dominated_set:dominated_ind.domination_count -= 1if dominated_ind.domination_count == 0:next_front.add(dominated_ind)fronts.append(next_front)rank += 1# 计算拥挤度距离pop_for_cross=set()for front in fronts:if len(front) == 0:continuesorted_front = sorted(list(front), key=lambda ind: ind.rank)for i in range(num_obj):sorted_front[0].objs[i] = float('inf')sorted_front[-1].objs[i] = float('inf')for j in range(1, len(sorted_front) - 1):delta = sorted_front[j + 1].objs[i] - sorted_front[j - 1].objs[i]if delta == 0:continuesorted_front[j].distance += delta / (x_range[1] - x_range[0])front_list = list(sorted_front)front_list.sort(key=lambda ind: (-ind.rank, -ind.distance))selected_inds =front_listif len(pop_for_cross) + len(selected_inds)<=pop_size:pop_for_cross.update(selected_inds)elif len(pop_for_cross)+len(selected_inds)>=pop_size and len(pop_for_cross)<pop_size:part_selected_inds=selected_inds[:(pop_size-len(pop_for_cross))]pop_for_cross.update(part_selected_inds)break# 交叉new_pop=set()while len(new_pop) < len(pop_for_cross):x1, x2 = random.sample(pop_for_cross, 2)if random.random() < pc:new_x = (x1.x + x2.x) / 2delta_x = abs(x1.x - x2.x)new_x += delta_x * random.uniform(-1, 1)new_x = max(x_range[0], min(x_range[1], new_x))new_pop.add(Individual(new_x))# 变异for ind in new_pop:if random.random() < pm:delta_x = random.uniform(-1, 1) * (x_range[1] - x_range[0])ind.x += delta_xind.x = max(x_range[0], min(x_range[1], ind.x))# 更新种群,把原来的精英(pop_for_cross)保留下来pop = list(new_pop)+list(pop_for_cross)# 输出最优解集合
for ind in pop:ind.evaluate()pareto_front = set()
for ind in pop:dominated = Falsefor other in pop:if other.objs[0] < ind.objs[0] :dominated = Truebreakif not dominated:pareto_front.add(ind)print("Pareto front:")
for ind in pareto_front:print(f"x={ind.x:.4f}, y1={ind.objs[0]:.4f}")

模型输出

在这里插入图片描述


http://www.ppmy.cn/news/1206430.html

相关文章

kotlin 基本语法

const val INFO "ZZZ is Success Result" fun main(){ var name: String? "zzz" name null name?.capitalize() //?问号的意思是如果name是null ,后面的方法不执行&#xff0c;如果name不是null&#xff0c;后面方法执行 var name: String? &q…

服务器硬件有哪些组成

服务器是由处理器、硬盘、内存、显卡、主板、网卡等组成&#xff0c;今天小编带大家了解一下服务器有哪些硬件吧&#xff01; 1.最重要的当然就是处理器了&#xff0c;处理器就相当于是服务器的大脑&#xff0c;负责执行各种运算和指令&#xff0c;例如运行程序或者处理数据&am…

解决Jenkins执行git脚本时报错:No such device or address问题

问题现象&#xff1a; Jenkins执行BeanShell脚本时&#xff0c;报错&#xff1a;jenkins fatal: could not read Username for http://112.11.120.1: No such device or address 解决方案&#xff1a; 解决服务器拉取git仓库的代码权限&#xff0c;使用高级子模块克隆功能。…

基于词典的正向最大匹配和逆向最大匹配中文分词

中文分词中基于词典的正向最大匹配和逆向最大匹配 正向最大匹配和逆向最大匹配步骤类似&#xff0c;只是方向不同&#xff0c;我以正向匹配为例&#xff0c;先用一句话去总结它&#xff1a; 在做整个正向成词的过程中&#xff0c;我们做了两个步骤&#xff0c;首先按照字典最…

每日一题 2258. 逃离火灾(手撕困难!!!)

火会扩散&#xff0c;但是我们可以看作火不会扩散到已经着火的格子&#xff0c;这样我们就可以记录每一个为草地的格子的着火时间在代码中&#xff0c;因为数字 2 已经表示墙了&#xff0c;所以我们把当时间为 0 时着火的格子在 gird 中的值设为 3&#xff0c;时间为 1 时着火的…

Python中如何理解这种书写代码的语法??def cracking_passwords(zfile: ZipFile, pwd: str) -> bool:

def cracking_passwords(zfile: ZipFile, pwd: str) -> bool: # Author : 小红牛 # 微信公众号&#xff1a;wdPython这是一种使用Python的函数定义语法。这个函数被命名为cracking_passwords&#xff0c;它接受两个参数&#xff1a;zfile和pwd。参数的类型被标注为ZipFile和…

python- time模块

3种时间格式之间的转换 &#xff1a; 1、时间戳->格式化时间 time.localtime(timestamp)&#xff1a;北京时间 time.gmtime(timestamp) &#xff1a;伦敦时间 2、格式化时间->时间戳时间

URI 和 URL 的区别

URI包括URL和URN两个类别&#xff0c;URL是URI的子集&#xff0c;所以URL一定是URI&#xff0c;而URI不一定是URL URI Universal Resource Identifier 统一资源标志符&#xff0c;用来标识抽象或物理资源的一个紧凑字符串。 通过使用位置&#xff0c;名称或两者来标识Interne…