Bra*_*ube 3 python optimization scipy
有没有办法在不使用回调和重新执行成本函数的情况下使用 scipy.minimize 在每次迭代的基础上访问成本函数?
options.disp 似乎打算这样做,但只会导致优化器打印终止消息。
将它打印到标准输出并使用contextlib.redirect_stdoutwithio.StringIO收集它并在之后解析数据会很好,但我找不到一种方法来有效地访问每次迭代的成本函数。
小智 6
该方法least_squares使用参数verbose=2. 然而,它不是一个通用的最小化器,它的目的是最小化给定函数的平方和。例子:
least_squares(lambda x: [x[0]*x[1]-6, x[0]+x[1]-5], [0, 0], verbose=2)
Run Code Online (Sandbox Code Playgroud)
对于其他方法,例如minimize,没有这样的选项。您可能希望向函数本身添加一些日志记录,而不是使用回调和重新评估成本函数。例如,这里fun将计算值附加到全局变量cost_values:
def fun(x):
c = x[0]**2 - 2*x[0] + x[1]**4
cost_values.append(c)
return c
cost_values = []
minimize(fun, [3, 2])
print(cost_values)
Run Code Online (Sandbox Code Playgroud)
在这个例子中,每个迭代步骤有 4 个相似的函数值,因为最小化算法环顾四周,计算近似的 Jacobian 和/或 Hessian。因此,print(cost_values[::4])这将是每一步获得一个成本函数值的方法。
但并不总是每步 4 个值(取决于维度和使用的方法)。所以最好使用回调函数来记录每一步之后的成本。当前成本应存储在全局变量中,因此不必重新计算。
def fun(x):
global current_cost
current_cost = x[0]**2 - 2*x[0] + x[1]**4
return current_cost
def log_cost(x):
cost_values.append(current_cost)
cost_values = []
minimize(fun, [3, 2], callback=log_cost)
print(cost_values)
Run Code Online (Sandbox Code Playgroud)
这打印
[3.5058199763814986, -0.2358850818406083, -0.56104822688320077, -0.88774448831043995, -0.96018358963745964, -0.98750765702936738, -0.99588975368993771, -0.99867208501468863, -0.99956795994852465, -0.99985981414137615, -0.99995446605426996, -0.99998521591611178, -0.99999519917089297, -0.99999844105574265, -0.99999949379700426, -0.99999983560485239, -0.99999994662329761, -0.99999998266175671]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1943 次 |
| 最近记录: |