python - scipy.optimize.differential_evolution 评估要最小化的函数多少次?
问题描述
我正在尝试将此答案应用于我的代码以显示scipy.optimize.differential_evolution方法的进度条。
我认为这differential_evolution
会评估func
(被称为最小化的函数)popsize * maxiter
次,但显然情况并非如此。
下面的代码应该显示一个进度条,最多增加100%
:
[####################] 100%
但实际上这会继续进行,因为DEdist()
函数的评估次数比popsize * maxiter
(我用作函数的total
参数updt()
)要多得多。
如何计算由 执行的函数评估的总数differential_evolution
?这完全可以做到吗?
from scipy.optimize import differential_evolution as DE
import sys
popsize, maxiter = 10, 50
def updt(total, progress, extra=""):
"""
Displays or updates a console progress bar.
Original source: https://stackoverflow.com/a/15860757/1391441
"""
barLength, status = 20, ""
progress = float(progress) / float(total)
if progress >= 1.:
progress, status = 1, "\r\n"
block = int(round(barLength * progress))
text = "\r[{}] {:.0f}% {}{}".format(
"#" * block + "-" * (barLength - block),
round(progress * 100, 0), extra, status)
sys.stdout.write(text)
sys.stdout.flush()
def DEdist(model, info):
updt(popsize * maxiter, info['Nfeval'] + 1)
info['Nfeval'] += 1
res = (1. - model[0])**2 + 100.0 * (model[1] - model[0]**2)**2 + \
(1. - model[1])**2 + 100.0 * (model[2] - model[1]**2)**2
return res
bounds = [[0., 10.], [0., 10.], [0., 10.], [0., 10.]]
result = DE(
DEdist, bounds, popsize=popsize, maxiter=maxiter,
args=({'Nfeval': 0},))
解决方案
来自help(scipy.optimize.differential_evolution)
:
maxiter : int, optional
The maximum number of generations over which the entire population is
evolved. The maximum number of function evaluations (with no polishing)
is: ``(maxiter + 1) * popsize * len(x)``
同样polish=True
默认情况下:
polish : bool, optional
If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B`
method is used to polish the best population member at the end, which
can improve the minimization slightly.
所以你需要改变两件事:
1 在这里使用正确的公式:
updt(popsize * (maxiter + 1) * len(model), info['Nfeval'] + 1)
2 通过polish=False
参数:
result = DE(
DEdist, bounds, popsize=popsize, maxiter=maxiter, polish=False,
args=({'Nfeval': 0},))
之后,您将看到进度条在达到 100% 时完全停止。
推荐阅读
- android - 色调属性导致矢量图形上的像素化
- django - 根据外键过滤模型
- javascript - JavaScript 中的保留函数名
- csv - 使用 dask 将大于内存的 csv 文件存储到 hdf5 文件
- go - 无法分配给结构字段/分配给 nil 映射中的条目
- php - 当表单具有 enctype="text/plain" 时无法从 $_POST 数组中获取字段
- python - ABC中的实现
- javascript - 单击Youtube上的迷你播放器按钮后如何在页面上注入脚本
- php - Magento 支持 7.0.2、7.0.4 和 7.0.6 或更高版本。当运行 php bin/magento cron:run
- javascript - 响应式设计出错了