Python演化计算基准函数详解
程序员文章站
2022-04-06 21:01:26
目录基准函数定义代码实现调用方法总结基准函数是测试演化计算算法性能的函数集,由于大部分基准函数集都是c/c++编写,python编写的基准函数比较少,因此本文实现了13个常用基准函数的python版。...
基准函数是测试演化计算算法性能的函数集,由于大部分基准函数集都是c/c++编写,python编写的基准函数比较少,因此本文实现了13个常用基准函数的python版。
基准函数定义
代码实现
benchmark.py
import numpy as np import copy """ author : robin_hua update time : 2021.10.14 version : 1.0 """ class sphere: def __init__(self, x): self.x = x def getvalue(self): res = np.sum(self.x**2) return res class schwefel2_22: def __init__(self, x): self.x = x def getvalue(self): res = np.sum(np.abs(self.x)) + np.prod(np.abs(self.x)) return res class noise: def __init__(self,x): self.x = x def getvalue(self): d = self.x.shape[0] res = np.sum(np.arange(1, d + 1) * self.x ** 4) + np.random.random() return res class schwefel2_21: def __init__(self,x): self.x = x def getvalue(self): res = np.max(np.abs(self.x)) return res class step: def __init__(self,x): self.x = x def getvalue(self): res = np.sum(int(self.x + 0.5) ** 2) return res class rosenbrock: def __init__(self,x): self.x = x def getvalue(self): d = self.x.shape[0] res = np.sum(np.abs(100*(self.x[1:] - self.x[:-1]**2)**2 + (1 - self.x[:-1])**2)) return res class schwefel: def __init__(self,x): self.x = x def getvalue(self): d = self.x.shape[0] res = 418.9829*d - np.sum(self.x * np.sin(np.sqrt(np.abs(self.x)))) return res class rastrigin: def __init__(self,x): self.x = x def getvalue(self): d = self.x.shape[0] res = 10 * d + np.sum(self.x ** 2 - 10 * np.cos(2 * np.pi * self.x)) return res class ackley: def __init__(self,x): self.x = x def getvalue(self): d = self.x.shape[0] res = - 20 * np.exp(-0.2 * np.sqrt(np.mean(self.x ** 2))) res = res - np.exp(np.mean(np.cos(2 * np.pi * self.x))) + 20 + np.exp(1) return res class griewank: def __init__(self,x): self.x = x def getvalue(self): d = self.x.shape[0] i = np.arange(1, d + 1) res = 1 + np.sum(self.x ** 2) / 4000 - np.prod(np.cos(self.x / np.sqrt(i))) return res class generalized_penalized: def __init__(self,x): self.x = x def u(self,a,k,m): temp = copy.deepcopy(self.x) temp[-a <= temp.any() <= a] = 0 temp[temp > a] = k*(temp[temp > a]-a)**m temp[temp < -a] = k * (-temp[temp < -a] - a) ** m """ temp = np.zeros_like(self.x) d = self.x.shape[0] for i in range(d): if self.x[i]>a: temp[i] = k*(self.x[i]-a)**m elif self.x[i]<-a: temp[i] = k * (-self.x[i] - a) ** m else: pass """ return temp def getvalue(self): d = self.x.shape[0] y = 1+1/4*(self.x+1) res = np.pi/d*(10*np.sin(np.pi*y[0])**2+np.sum((y[:-1]-1)**2*(1+10*np.sin(np.pi*y[1:])**2))+(y[-1]-1)**2)+np.sum(self.u(10,100,4)) return res def benchmark_func(x,func_num): func = func_list[func_num] res = func(x) return res func_list = [sphere,schwefel2_22,noise,schwefel2_21,step,rosenbrock,schwefel,rastrigin,ackley,griewank,generalized_penalized]
调用方法
输入为向量x和函数编号func_num
import benchmark import numpy as np vector = np.random.random(30) value = benchmark.benchmark_func(x=vector,func_num=0).getvalue()
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!