def main(aim, n, Dim, phase): """===============================实例化问题对象===========================""" # PoolType = 'Process' # 设置采用多进程,若修改为: PoolType = 'Thread',则表示用多线程 problem = MyProblem(aim, n, Dim, phase) # 生成问题对象 """=================================种群设置===============================""" Encoding = 'RI' # 编码方式 NIND = 10 # 种群规模 Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # 创建区域描述器 population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) """===============================算法参数设置=============================""" myAlgorithm = ea.soea_DE_rand_1_bin_templet(problem, population) # 实例化一个算法模板对象 # myAlgorithm.mutOper.Pm = 0.2 # 修改变异算子的变异概率(原模板中breeder GA变异算子的Pm定义为1 / Dim) # myAlgorithm.recOper.XOVR = 0.9 # 修改交叉算子的交叉概率 myAlgorithm.MAXGEN = 15 # 最大进化代数 # myAlgorithm.trappedValue = 1e-6 # “进化停滞”判断阈值 # myAlgorithm.maxTrappedCount = 10 # 进化停滞计数器最大上限值,如果连续maxTrappedCount代被判定进化陷入停滞,则终止进化 myAlgorithm.drawing = 2 # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画) """==========================调用算法模板进行种群进化=======================""" [population, obj_trace, var_trace] = myAlgorithm.run() # 执行算法模板 population.save() # 把最后一代种群的信息保存到文件中 # 输出结果 best_gen = np.argmin(problem.maxormins * obj_trace[:, 1]) # 记录最优种群个体是在哪一代 best_ObjV = obj_trace[best_gen, 1] print('最优的目标函数值为:%.8smm'%(best_ObjV)) if phase == None: phase = [0] + [i*10 for i in var_trace[best_gen, :]] # 第一次算出的所有相位值 res = aim.bias_n_li(phase) find_index = np.where(max(res[n + 1:, 0]) == res[n + 1:, 0])[0][0] + 1 # 第一次最大偏心值的索引位置(此处res内的n+1和最后面的+1表示:不考虑第一级,整体向后偏移一位) else: phase = phase + [i*10 for i in var_trace[best_gen, :]] # 所有相位值(后续几级相位值有更新) res = aim.bias_n_li(phase) find_index = np.where(max(res[n:, 0]) == res[n:, 0])[0][0] # 每次的最大偏心值的索引位置 print('所在位置及相位偏斜角为:第%s级零件末端; %.8s°' % (find_index + 1 + n, res[find_index + n, 1])) if n == 0: for i in range(len(phase)): print('第%s级相位、偏心值及相位偏斜角为:%s°; %.8smm; %.8s°' % (i + 1, phase[i], res[i, 0], res[i, 1])) else: for i in range(var_trace.shape[1]): print('第%s级相位、偏心值及相位偏斜角为:%s°; %.8smm; %.8s°' % (i + (n+1), phase[i + n], res[i + n, 0], res[i + n, 1])) print('有效进化代数:%s' % (obj_trace.shape[0])) print('最优的一代是第 %s 代' % (best_gen + 1)) print('评价次数:%s' % (myAlgorithm.evalsNum)) print('时间已过 %s 分 %.8s 秒' % (int(myAlgorithm.passTime // 60), myAlgorithm.passTime % 60)) n = n + int((find_index + 1)) # 计算累计固定好的级数(此处find_index类型为int64,改为int类型防止后面报错!) return myAlgorithm, obj_trace, var_trace, best_gen, best_ObjV, phase, res, n
def run(): """===============================实例化问题对象===========================""" PoolType = 'Process' # 设置采用多进程,若修改为: PoolType = 'Thread',则表示用多线程 problem = MyProblem(PoolType) # 生成问题对象 """=================================种群设置===============================""" Encoding = 'RI' # 编码方式 NIND = 50 # 种群规模 Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # 创建区域描述器 population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) """===============================算法参数设置=============================""" myAlgorithm = ea.soea_DE_rand_1_bin_templet(problem, population) # 实例化一个算法模板对象 myAlgorithm.MAXGEN = 30 # 最大进化代数 myAlgorithm.trappedValue = 1e-6 # “进化停滞”判断阈值 myAlgorithm.maxTrappedCount = 10 # 进化停滞计数器最大上限值,如果连续maxTrappedCount代被判定进化陷入停滞,则终止进化 """==========================调用算法模板进行种群进化=======================""" [population, obj_trace, var_trace] = myAlgorithm.run() # 执行算法模板 population.save() # 把最后一代种群的信息保存到文件中 problem.pool.close() # 及时关闭问题类中的池,否则在采用多进程运算后内存得不到释放 # 输出结果 best_gen = np.argmin(problem.maxormins * obj_trace[:, 1]) # 记录最优种群个体是在哪一代 best_ObjV = obj_trace[best_gen, 1] print('最优的目标函数值为:%s' % (best_ObjV)) print('最优的控制变量值为:') for i in range(var_trace.shape[1]): print(var_trace[best_gen, i]) print('有效进化代数:%s' % (obj_trace.shape[0])) print('最优的一代是第 %s 代' % (best_gen + 1)) print('评价次数:%s' % (myAlgorithm.evalsNum)) print('时间已过 %s 秒' % (myAlgorithm.passTime)) C = var_trace[best_gen, 0] gamma = var_trace[best_gen, 1] model = SVC(C=C, gamma=gamma) model.fit(x_train_scaled, y_train) return model
if __name__ == '__main__': """================================实例化问题对象===========================""" problemName = 'Pathological' # 问题名称 fileName = problemName # 这里因为目标函数写在与之同名的文件里,所以文件名也是问题名称 MyProblem = getattr(__import__(fileName), problemName) # 获得自定义问题类 problem = MyProblem() # 生成问题对象 """==================================种群设置==============================""" Encoding = 'RI' # 编码方式 NIND = 20 # 种群规模 precisions = [50] * problem.Dim # 编码精度(适用于二进制/格雷编码) Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders, precisions) # 创建区域描述器 population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) """================================算法参数设置============================""" myAlgorithm = ea.soea_DE_rand_1_bin_templet(problem, population) # 实例化一个算法模板对象 myAlgorithm.MAXGEN = 1000 # 最大进化代数 myAlgorithm.mutOper.F = 0.5 # 差分进化中的参数F myAlgorithm.recOper.XOVR = 0.2 # 重组概率 myAlgorithm.drawing = 1 # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画) """===========================调用算法模板进行种群进化======================""" [population, obj_trace, var_trace] = myAlgorithm.run() # 执行算法模板,得到最后一代种群以及进化记录器 population.save() # 把最后一代种群的信息保存到文件中 # 输出结果 best_gen = np.argmin(problem.maxormins * obj_trace[:, 1]) # 记录最优种群个体是在哪一代 best_ObjV = obj_trace[best_gen, 1] print('最优的目标函数值为:%s' % (best_ObjV)) print('最优的控制变量值为:') for i in range(var_trace.shape[1]): print(var_trace[best_gen, i])
def run(date, n, T, ep, c_max_dir, d_dir, s_dir, desc, df_c_max=None, df_d=None, df_s=None, MAXGEN=500, F=0.5, XOVR=0.7, logTras=0, verbose=False, drawing=0, trappedValue=0, maxTrappedCount=1000, save_mode='csv'): if not os.path.exists(data_prefix): os.mkdir(data_prefix) if not os.path.exists(result_prefix): os.mkdir(result_prefix) if not os.path.exists(output_prefix): os.mkdir(output_prefix) date_str = f'{date.year}-{date.month}-{date.day}' output_dir = f'date={date_str} n={n} T={T} ep={ep} desc={desc}.csv' print(output_dir) range_index = range(0, n) if df_c_max is None: c_max_csv = open(f'{data_prefix}/{c_max_dir}') df_c_max = pd.read_csv(c_max_csv, header=None, index_col=None).values if df_d is None: d_csv = open(f'{data_prefix}/{d_dir}') df_d = pd.read_csv(d_csv, header=None, index_col=None).values if df_s is None: s_csv = open(f'{data_prefix}/{s_dir}') df_s_csv = pd.read_csv(s_csv, header=None, index_col=0) str_date = f'{date.year}/{date.month}/{date.day}' s_arr = df_s_csv.loc[str_date].values df_s = {i: s_arr[i] for i in range_index} """================================实例化问题对象===========================""" problem = MyProblem(n, T, ep, df_c_max, df_d, df_s) # 生成问题对象 """==================================种群设置==============================""" Encoding = 'RI' # 编码方式 NIND = 100 # 种群规模 Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # 创建区域描述器 # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化) population = ea.Population(Encoding, Field, NIND) """================================算法参数设置=============================""" myAlgorithm = ea.soea_DE_rand_1_bin_templet(problem, population) # 实例化一个算法模板对象 myAlgorithm.MAXGEN = MAXGEN # 最大进化代数 myAlgorithm.mutOper.F = F # 差分进化中的参数F myAlgorithm.recOper.XOVR = XOVR # 重组概率 myAlgorithm.trappedValue = trappedValue # “进化停滞”判断阈值 # 进化停滞计数器最大上限值,如果连续maxTrappedCount代被判定进化陷入停滞,则终止进化 myAlgorithm.maxTrappedCount = maxTrappedCount myAlgorithm.logTras = logTras # 设置每隔多少代记录日志,若设置成0则表示不记录日志 myAlgorithm.verbose = verbose # 设置是否打印输出日志信息 myAlgorithm.drawing = drawing # 设置绘图方式(0:不绘图;1:绘制结果图;2:绘制目标空间过程动画;3:绘制决策空间过程动画) """===========================调用算法模板进行种群进化========================""" [BestIndi, population] = myAlgorithm.run() # 执行算法模板,得到最优个体以及最后一代种群 # BestIndi.save() # 把最优个体的信息保存到文件中 """==================================输出结果==============================""" print('Number of evaluation:%s' % myAlgorithm.evalsNum) print('Time used in seconds %s' % myAlgorithm.passTime) if BestIndi.sizes != 0: print('Best objective value:%s' % BestIndi.ObjV[0][0]) final_table = np.zeros((10, 10), dtype=int) count = 0 for i in range(10): for j in range(10): if i != j: final_table[i][j] = BestIndi.Phen[0, count] count += 1 if save_mode == 'csv': df = pd.DataFrame(final_table, columns=None, index=None) df.to_csv(f'{output_prefix}/{output_dir}', header=False, index=False, mode='w') elif save_mode == 'json': f = open(f'{output_prefix}/{date_str}.json', 'w', encoding='utf-8') f.write(f'{final_table.tolist()}') f.close() else: print('No feasible solution!') return myAlgorithm
# -*- coding: utf-8 -*- import geatpy as ea # import geatpy if __name__ == '__main__': # 问题对象 problem = ea.benchmarks.Ackley(30) # 构建算法 algorithm = ea.soea_DE_rand_1_bin_templet( problem, ea.Population(Encoding='RI', NIND=20), MAXGEN=1000, # 最大进化代数。 logTras=1) # 表示每隔多少代记录一次日志信息,0表示不记录。 algorithm.mutOper.F = 0.5 # 差分进化中的参数F algorithm.recOper.XOVR = 0.2 # 差分进化中的参数Cr # 求解 res = ea.optimize(algorithm, verbose=True, drawing=1, outputMsg=True, drawLog=True, saveFlag=True, dirName='result') print(res)
本案例和soea_demo6类似,同样是用进化算法来搜索SVM的参数C和Gamma的最佳值。不同的是这里采用SCOOP来 在执行本案例前,需要确保正确安装sklearn以及SCOOP,以保证SVM和SCOOP部分的代码能够正常执行。 SCOOP安装方法:控制台执行命令pip install scoop 分布式加速计算注意事项: 1.当目标函数的计算十分耗时,比如计算单个个体的目标函数值就需要很长时间时, 适合采用分布式计算,否则贸然采用分布式计算反而会大大降低性能。 2.分布式执行方法:python -m scoop -n 10 main.py 其中10表示把计算任务分发给10个workers。 非分布式执行方法:python main.py """ if __name__ == '__main__': # 实例化问题对象 problem = MyProblem() # 构建算法 algorithm = ea.soea_DE_rand_1_bin_templet( problem, ea.Population(Encoding='RI', NIND=20), MAXGEN=30, # 最大进化代数。 logTras=1, # 表示每隔多少代记录一次日志信息,0表示不记录。 trappedValue=1e-6, # 单目标优化陷入停滞的判断阈值。 maxTrappedCount=10) # 进化停滞计数器最大上限值。 # 求解 res = ea.optimize(algorithm, verbose=True, drawing=1, outputMsg=True, drawLog=False, saveFlag=True) # 检验结果 problem.test(C=res['Vars'][0, 0], G=res['Vars'][0, 1])
import geatpy as ea # import geatpy import numpy as np from MyProblem2 import Ackley if __name__ == '__main__': """=========================Instantiate your problem==========================""" problem = Ackley(30) # Instantiate MyProblem class. """===============================Population set==============================""" Encoding = 'RI' # Encoding type. NIND = # Set the number of individuals. Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges, problem.borders) # Create the field descriptor. population = ea.Population(Encoding, Field, NIND) # Instantiate Population class(Just instantiate, not initialize the population yet.) """================================Algorithm set===============================""" myAlgorithm = ea.soea_DE_rand_1_bin_templet(problem, population) # Instantiate a algorithm class. myAlgorithm.MAXGEN = 1000 # Set the max times of iteration. myAlgorithm.mutOper.F = 0.5 # Set the F of DE myAlgorithm.recOper.XOVR = 0.2 # Set the Cr of DE (Here it is marked as XOVR) myAlgorithm.logTras = 1 # Set the frequency of logging. If it is zero, it would not log. myAlgorithm.verbose = True # Set if we want to print the log during the evolution or not. myAlgorithm.drawing = 1 # 1 means draw the figure of the result. """===============================Start evolution==============================""" [BestIndi, population] = myAlgorithm.run() # Run the algorithm templet. """==============================Output the result=============================""" print('The number of evolution is: %s'%(myAlgorithm.evalsNum)) if BestIndi.sizes != 0: print('The objective value of the best solution is: %s' % BestIndi.ObjV[0][0]) else: print('Did not find any feasible solution.')
def __init__(self, X, y, model, drawing, l, u, soea): '''初始化必要的相关参数''' '''===============================实例化问题对象==================================''' self.problem = MyProblem(target=[0], X=X, y=y, model=model, l=l, u=u) '''===========================种群设置==============================''' self.model = model Encoding = 'RI' # 'RI':实整数编码,即实数和整数的混合编码; if self.model == 1: NIND = 100 # 种群规模 elif self.model == 2: NIND = 10 elif self.model == 3: NIND = 30 elif self.model == 4: NIND = 100 else: print(self.model) print('model parameters error!!') Field = ea.crtfld(Encoding, self.problem.varTypes, self.problem.ranges, self.problem.borders) # 创建区域描述器 self.population = ea.Population(Encoding, Field, NIND) '''实例化种群对象(此时种群还没被真正初始化,仅仅是生成一个种群对象)''' """================================算法参数设置=============================""" if soea == 1: self.myAlgorithm = CoDE(self.problem, self.population) # 实例化一个算法模板对象 elif soea == 2: self.myAlgorithm = ea.soea_DE_rand_1_bin_templet( self.problem, self.population) elif soea == 3: self.myAlgorithm = CoDE_toZero(self.problem, self.population) elif soea == 4: self.myAlgorithm = CoDE_10p_toZero(self.problem, self.population) elif soea == 5: self.myAlgorithm = CoDE_20p_toZero(self.problem, self.population) elif soea == 6: self.myAlgorithm = CoDE_10p_lr_toZero(self.problem, self.population) elif soea == 7: self.myAlgorithm = CoDE_20p_lr_toZero(self.problem, self.population) elif soea == 8: self.myAlgorithm = CoDE_random10p_toZero(self.problem, self.population) elif soea == 9: self.myAlgorithm = CoDE_random20p_toZero(self.problem, self.population) elif soea == 10: self.myAlgorithm = CoDE_random30p_toZero(self.problem, self.population) else: print('error soea number!!!!') if self.model == 1: self.myAlgorithm.MAXGEN = 100 # 设置最大遗传代数 elif self.model == 2: self.myAlgorithm.MAXGEN = 30 elif self.model == 3: self.myAlgorithm.MAXGEN = 50 elif self.model == 4: self.myAlgorithm.MAXGEN = 100 else: print(self.model) print('model parameters error!!') self.myAlgorithm.drawing = drawing