pyswarms使用及SciPy中powell使用整理

pyswarms.single.global_best

原为url:https://pyswarms.readthedocs.io/en/latest/api/pyswarms.single.html#module-pyswarms.single.global_best

一种全局最佳粒子群优化 (gbest PSO) 算法。
它需要一组候选解决方案,并尝试使用位置速度更新方法找到最佳解决方案。 使用星型拓扑,其中每个粒子都被性能最佳的粒子所吸引。

位置更新可以定义为:
xi(t+1)=xi(t)+vi(t+1)
其中当前时间步长 t 处的位置使用计算出的 t+1 处的速度进行更新。 此外,速度更新定义为:
vij(t+1)=w∗vij(t)+c1r1j(t)[yij(t)−xij(t)]+c2r2j(t)[y^j(t)−xij(t)]

这里,c1 和 c2 分别是认知和社会参数。 他们控制粒子的行为有两种选择:(1)跟随其个人最佳位置或(2)跟随群体的全局最佳位置。 总的来说,这决定了蜂群本质上是探索性的还是剥削性的。 此外,参数 w 控制群体运动的惯性。

该算法改编自 J. Kennedy 和 R.C. 的早期作品。 粒子群优化中的 Eberhart [IJCNN1995]。

参数说明

pyswarms.single.global_best.GlobalBestPSO(n_particles, dimensions, options, bounds=None, oh_strategy=None, bh_strategy=‘periodic’, velocity_clamp=None, vh_strategy=‘unmodified’, center=1.0, ftol=-inf, ftol_iter=1, init_pos=None)

n_particles:群中的粒子数。
dimensions:空间中的维数。
options:包含特定优化技术参数的字典。

c1:认知参数
c2:社会参数
w:惯性参数

bounds:一个大小为 2 的元组,其中第一个条目是最小界限,而第二个条目是最大界限。 每个数组必须具有形状(尺寸)。
oh_strategy:每个选项的更新策略字典。
bh_strategy:一种处理越界粒子的策略。
velocity_clamp:大小为 2 的元组,其中第一个条目是最小速度,第二个条目是最大速度。 它设置了速度钳位的限制。
vh_strategy:一种处理越界粒子速度的策略。
center:尺寸维度的数组
ftol:收敛可接受的objective_func(best_pos)中的相对误差。 默认为 -np.inf
ftol_iter:Objective_func(best_pos) 中的相对误差对于收敛是可以接受的迭代次数。 默认为 1
init_pos:显式设置粒子初始位置的选项。 如果您希望随机生成粒子,请设置为无。

optimize(objective_func, iters, n_processes=None, verbose=True, **kwargs)

优化 swarm 进行多次迭代
执行优化以评估多次迭代 iter 的目标函数 f。
objective_func (callable) :要评估的目标函数
iters :迭代次数
n_processes :用于并行粒子评估的进程数(默认值: 无并行化)
verbose :启用或禁用日志和进度条(默认值:True = 启用日志)
kwargs :目标函数的参数

示例:

'''pso测试:求圆的中心 ''' 
def rosenbrock_with_args2(x, a, b):
    f2 = []
    for value in x:
        res = (value[0]-a)**2 + (value[1]-b)**2
        f2.append(res)
    print('\n-----','f2:',f2,'-----')
    return f2

def rosenbrock_with_args(x, a, b):
    # for value in x:
    #     print("value,",value)
    f = (x[:,0]-a)**2 + (x[:,1]-b)**2
    print('\n-----','f:',f,'-----')
    return f

x_max = [2,3]
x_min = [0,1]
bounds = (x_min, x_max)
options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
optimizer = ps.single.GlobalBestPSO(n_particles=3, dimensions=2, options=options, bounds=bounds,ftol=0.5,ftol_iter=5)
cost, pos = optimizer.optimize(rosenbrock_with_args, 50, a=2,b=1)
print(cost)
print(pos)

minimize(method=’Powell’)¶

原为url:

http://scipy.github.io/devdocs/reference/optimize.minimize-powell.html

scipy.optimize.minimize(fun, x0, args=(), method=‘Powell’, bounds=None, tol=None, callback=None, options={‘func’: None, ‘xtol’: 0.0001, ‘ftol’: 0.0001, ‘maxiter’: None, ‘maxfev’: None, ‘disp’: False, ‘direc’: None, ‘return_all’: False})

Minimization of scalar function of one or more variables using the modified Powell algorithm.
使用改进的 Powell 算法最小化一个或多个变量的标量函数。

Options:
disp:bool
Set to True to print convergence messages.设置为 True 以打印收敛消息。

xtol:float
Relative error in solution xopt acceptable for convergence.解决方案 xopt 中的相对误差对于收敛是可以接受的。

ftol:float
Relative error in fun(xopt) acceptable for convergence.收敛可接受的 fun(xopt) 中的相对误差。

maxiter, maxfev:int
Maximum allowed number of iterations and function evaluations. Will default to N1000, where N is the number of variables, if neither maxiter or maxfev is set. If both maxiter and maxfev are set, minimization will stop at the first reached.
允许的最大迭代次数和函数评估次数。如果 maxiter 或 maxfev 均未设置,则默认为 N
1000,其中 N 是变量数。如果同时设置了 maxiter 和 maxfev,则最小化将在第一次达到时停止。

direc:ndarray
Initial set of direction vectors for the Powell method.Powell 方法的初始方向向量集。

return_all:bool, optional
Set to True to return a list of the best solution at each of the iterations.设置为 True 以在每次迭代中返回最佳解决方案列表。

bounds:Bounds
If bounds are not provided, then an unbounded line search will be used. If bounds are provided and the initial guess is within the bounds, then every function evaluation throughout the minimization procedure will be within the bounds. If bounds are provided, the initial guess is outside the bounds, and direc is full rank (or left to default), then some function evaluations during the first iteration may be outside the bounds, but every function evaluation after the first iteration will be within the bounds. If direc is not full rank, then some parameters may not be optimized and the solution is not guaranteed to be within the bounds.
如果未提供边界,则将使用无界线搜索。如果提供了界限并且初始猜测在界限内,那么整个最小化过程中的每个函数评估都将在界限内。如果提供了边界,初始猜测在边界之外,并且 direc 是满秩(或保留默认值),那么第一次迭代期间的某些函数评估可能在边界之外,但第一次迭代后的每个函数评估都将在范围内界限。如果 direc 不是满秩,那么某些参数可能没有被优化,并且不能保证解决方案在范围内。

return_all:bool, optional
Set to True to return a list of the best solution at each of the iterations.
设置为 True 以在每次迭代中返回最佳解决方案列表。

scipy.optimize.minimize

scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)

Minimization of scalar function of one or more variables.
最小化一个或多个变量的标量函数。
Parameters:
fun:callable
The objective function to be minimized.要最小化的目标函数。

fun(x, *args) -> float

where x is a 1-D array with shape (n,) and args is a tuple of the fixed parameters needed to completely specify the function.
其中 x 是形状为 (n,) 的一维数组,args 是完全指定函数所需的固定参数的元组。

x0:ndarray, shape (n,)
Initial guess. Array of real elements of size (n,), where n is the number of independent variables.
初步猜测。 大小为 (n,) 的实数元素数组,其中 n 是自变量的数量。

args:tuple, optional
Extra arguments passed to the objective function and its derivatives (fun, jac and hess functions).
传递给目标函数及其导数(fun、jac 和 hess 函数)的额外参数。

method:str or callable, optional
Type of solver. Should be one of 求解器的类型。 应该是其中之一
‘Nelder-Mead’
‘Powell’
‘CG’
‘BFGS’
‘Newton-CG’
‘L-BFGS-B’
‘TNC’
‘COBYLA’
‘SLSQP’
‘trust-constr’
‘dogleg’
‘trust-ncg’
‘trust-exact’
‘trust-krylov’
custom - a callable object (added in version 0.14.0), see below for description.
custom - 一个可调用对象(在 0.14.0 版本中添加),请参阅下面的描述。

If not given, chosen to be one of BFGS, L-BFGS-B, SLSQP, depending on whether or not the problem has constraints or bounds.
如果未给出,则选择 BFGS、L-BFGS-B、SLSQP 之一,具体取决于问题是否有约束或界限。
jac:{callable, ‘2-point’, ‘3-point’, ‘cs’, bool}, optional
Method for computing the gradient vector. Only for CG, BFGS, Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg, trust-krylov, trust-exact and trust-constr. If it is a callable, it should be a function that returns the gradient vector:
计算梯度向量的方法。仅适用于 CG、BFGS、Newton-CG、L-BFGS-B、TNC、SLSQP、dogleg、trust-ncg、trust-krylov、trust-exact 和 trust-constr。如果它是可调用的,它应该是一个返回梯度向量的函数:
jac(x, *args) -> array_like, shape (n,)
where x is an array with shape (n,) and args is a tuple with the fixed parameters. If jac is a Boolean and is True, fun is assumed to return a tuple (f, g) containing the objective function and the gradient. Methods ‘Newton-CG’, ‘trust-ncg’, ‘dogleg’, ‘trust-exact’, and ‘trust-krylov’ require that either a callable be supplied, or that fun return the objective and gradient. If None or False, the gradient will be estimated using 2-point finite difference estimation with an absolute step size. Alternatively, the keywords {‘2-point’, ‘3-point’, ‘cs’} can be used to select a finite difference scheme for numerical estimation of the gradient with a relative step size. These finite difference schemes obey any specified bounds.
其中 x 是一个形状为 (n,) 的数组,而 args 是一个具有固定参数的元组。如果 jac 是一个布尔值并且为 True,则 fun 假定返回一个包含目标函数和梯度的元组 (f, g)。方法“Newton-CG”、“trust-ncg”、“dogleg”、“trust-exact”和“trust-krylov”要求提供可调用对象,或者乐趣返回目标和梯度。如果 None 或 False,梯度将使用绝对步长的 2 点有限差分估计来估计。或者,关键字 {‘2-point’, ‘3-point’, ‘cs’} 可用于选择有限差分方案,用于具有相对步长的梯度数值估计。这些有限差分方案服从任何指定的界限。

hess:{callable, ‘2-point’, ‘3-point’, ‘cs’, HessianUpdateStrategy}, optional
Method for computing the Hessian matrix. Only for Newton-CG, dogleg, trust-ncg, trust-krylov, trust-exact and trust-constr. If it is callable, it should return the Hessian matrix:
计算 Hessian 矩阵的方法。 仅适用于 Newton-CG、dogleg、trust-ncg、trust-krylov、trust-exact 和 trust-constr。 如果它是可调用的,它应该返回 Hessian 矩阵:
hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)
where x is a (n,) ndarray and args is a tuple with the fixed parameters. The keywords {‘2-point’, ‘3-point’, ‘cs’} can also be used to select a finite difference scheme for numerical estimation of the hessian. Alternatively, objects implementing the HessianUpdateStrategy interface can be used to approximate the Hessian. Available quasi-Newton methods implementing this interface are:
其中 x 是 (n,) ndarray,args 是具有固定参数的元组。 关键字 {‘2-point’, ‘3-point’, ‘cs’} 也可用于选择用于 hessian 数值估计的有限差分方案。 或者,实现 HessianUpdateStrategy 接口的对象可用于近似 Hessian。 实现此接口的可用准牛顿方法有:

BFGS;
SR1.
Not all of the options are available for each of the methods; for availability refer to the notes.
并非所有选项都可用于每种方法; 有关可用性,请参阅注释。

hessp:callable, optional
Hessian of objective function times an arbitrary vector p. Only for Newton-CG, trust-ncg, trust-krylov, trust-constr. Only one of hessp or hess needs to be given. If hess is provided, then hessp will be ignored. hessp must compute the Hessian times an arbitrary vector:
目标函数的 Hessian 乘以任意向量 p。 仅适用于 Newton-CG、trust-ncg、trust-krylov、trust-constr。 只需要给出 hessp 或 hess 之一。 如果提供 hess,则 hessp 将被忽略。 hessp 必须计算 Hessian 乘以任意向量:
hessp(x, p, *args) -> ndarray shape (n,)
where x is a (n,) ndarray, p is an arbitrary vector with dimension (n,) and args is a tuple with the fixed parameters.
其中 x 是 (n,) ndarray,p 是维度为 (n,) 的任意向量,args 是具有固定参数的元组。

bounds:sequence or Bounds, optional
Bounds on variables for Nelder-Mead, L-BFGS-B, TNC, SLSQP, Powell, and trust-constr methods. There are two ways to specify the bounds:
Nelder-Mead、L-BFGS-B、TNC、SLSQP、Powell 和 trust-constr 方法的变量界限。 有两种方法可以指定边界:
Instance of Bounds class. Bounds 类的实例。
Sequence of (min, max) pairs for each element in x. None is used to specify no bound.
x 中每个元素的 (min, max) 对序列。 None 用于指定无界限。

constraints:{Constraint, dict} or List of {Constraint, dict}, optional
Constraints definition. Only for COBYLA, SLSQP and trust-constr.
约束定义。 仅适用于 COBYLA、SLSQP 和 trust-constr。
Constraints for ‘trust-constr’ are defined as a single object or a list of objects specifying constraints to the optimization problem. Available constraints are:
“trust-constr”的约束被定义为单个对象或指定优化问题约束的对象列表。 可用的约束是:
LinearConstraint 线性约束
NonlinearConstraint 非线性约束
Constraints for COBYLA, SLSQP are defined as a list of dictionaries. Each dictionary with fields:
COBYLA、SLSQP 的约束被定义为字典列表。 每个带有字段的字典:
type:str
Constraint type: ‘eq’ for equality, ‘ineq’ for inequality.约束类型:“eq”表示相等,“ineq”表示不相等。

fun:callable
The function defining the constraint.定义约束的函数。

jac:callable, optional
The Jacobian of fun (only for SLSQP).有趣的雅可比行列式(仅适用于 SLSQP)。

args:sequence, optional
Extra arguments to be passed to the function and Jacobian.要传递给函数和雅可比行列式的额外参数。

Equality constraint means that the constraint function result is to be zero whereas inequality means that it is to be non-negative. Note that COBYLA only supports inequality constraints.
等式约束意味着约束函数结果为零,而不等式意味着它是非负的。 请注意,COBYLA 仅支持不等式约束。

tol:float, optional
Tolerance for termination. When tol is specified, the selected minimization algorithm sets some relevant solver-specific tolerance(s) equal to tol. For detailed control, use solver-specific options.
容忍终止。 当指定 tol 时,选定的最小化算法将一些相关的求解器特定容差设置为等于 tol。 要进行详细控制,请使用特定于求解器的选项。

options:dict, optional
A dictionary of solver options. All methods accept the following generic options:
求解器选项字典。 所有方法都接受以下通用选项:

maxiter:int
Maximum number of iterations to perform. Depending on the method each iteration may use several function evaluations.
要执行的最大迭代次数。 根据方法,每次迭代可能会使用多个函数评估。

disp:bool
Set to True to print convergence messages.设置为 True 以打印收敛消息。

For method-specific options, see show_options.有关特定于方法的选项,请参阅 show_options。

callback:callable, optional
Called after each iteration. For ‘trust-constr’ it is a callable with the signature:
每次迭代后调用。 对于“trust-constr”,它是一个带有签名的可调用对象:
callback(xk, OptimizeResult state) -> bool
where xk is the current parameter vector. and state is an OptimizeResult object, with the same fields as the ones from the return. If callback returns True the algorithm execution is terminated. For all the other methods, the signature is:
其中 xk 是当前参数向量。 state 是一个 OptimizeResult 对象,与返回的字段具有相同的字段。 如果回调返回 True,则终止算法执行。 对于所有其他方法,签名是:
callback(xk)
where xk is the current parameter vector.其中 xk 是当前参数向量。

res:OptimizeResult
The optimization result represented as a OptimizeResult object. Important attributes are: x the solution array, success a Boolean flag indicating if the optimizer exited successfully and message which describes the cause of the termination. See OptimizeResult for a description of other attributes.
优化结果表示为 OptimizeResult 对象。 重要的属性是: x 解决方案数组,success 一个布尔标志,指示优化器是否成功退出,以及描述终止原因的消息。 有关其他属性的描述,请参见 OptimizeResult。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力减肥的小胖子5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值