我正在使用 scipy.optimize.minimize 库来自定义编写我的损失函数。 https://docs.scipy.org/doc/scipy/reference/ generated/scipy.optimize.minimize.html
def customised_objective_func(x):
global lag1
global lag2
global lag3
global lag4
pred = []
err = []
df_col_others_copy=df_col_others.copy(deep=True)
df_col_others_copy*=np.array(x)
pred=intercept_val+df_col_others_copy.sum(axis=1)
pred=list(pred)
col_sales=list(df_col_sales)
err = np.array(pred) - np.array(col_sales)
#err = pred - col_sales
obj_func_cust=sum(err**2)/len(err) + (lambda_mult* pen_func(x))
# CONDITION CHECK
avg_lags_val=(lag1+lag2+lag3+lag4)/float(4.0)
perc_change=(np.abs(obj_func_cust-avg_lag_val)/float(avg_lags_val))*100
if perc_change>=2.0:
break --###?? Sntax for breaking out here??
# retaining last 4 values
curr=obj_func_cust
lag4=lag3
lag3=lag2
lag2=lag1
lag1=curr
if curr=0:
return obj_func_cust
myoptions={'maxiter':1000}
results = minimize(customised_objective_func,params,method = "BFGS",options = myoptions)
我保留为最后 4 次迭代计算的损失函数的值,并且如果满足该条件,我想检查它们的一些方差我想停止函数调用(退出进一步的函数执行以进行更多迭代,即使 1000 次迭代不完整。
我怎样才能实现这个目标?希望获得有关要使用的关键字/syntx 的帮助?
由于您需要最后四个目标函数值,并且无法终止目标函数内的求解器,因此您可以编写一个包含回调和目标函数的包装器:
class Wrapper:
def __init__(self, obj_fun, cond_fun, threshold):
self.obj_fun = obj_fun
self.cond_fun = cond_fun
self.threshold = threshold
self.last_vals = np.zeros(5)
self.iters = 0
def callback(self, xk):
if self.iters <= 4:
return False
if self.cond_fun(self.last_vals) <= self.threshold:
return True
def objective(self, x):
# evaluate the obj_fun, update the last four objective values
# and return the current objective value
np.roll(self.last_vals, 1)
obj_val = self.obj_fun(x)
self.last_vals[0] = obj_val
self.iters += 1
return obj_val
如果最后四个值评估的
callback
低于给定的 True
,则 cond_fun
方法将返回 threshold
并终止求解器。这里,xk
就是当前点。 objective
方法只是 obj_fun
的包装,并更新最后的目标值。
然后,你可以像这样使用它:
def your_cond_fun(last_obj_vals):
curr = last_obj_vals[0]
last4 = last_obj_vals[1:]
avg_vals = np.sum(last4) / last4.size
return 100*np.abs(curr - avg_vals) / avg_vals
wrapper = Wrapper(your_obj_fun, your_cond_fun, your_threshold)
minimize(wrapper.objective, params, callback = wrapper.callback,
method = "BFGS", options = myoptions)
如果
optimize
返回 True,并非 callback
中的所有方法都会终止。事实上,我记得只有一种方法会按预期终止,但我不确定是哪一种。
签出:https://github.com/scipy/scipy/pull/4384
此外,您可以更改源代码
scipy.optimize._minimize
以在检查回调时终止。
代码快照如下:
if callback is not None:
if unknown_options.get("early_stopping"):
# NEW: update with early stopping
res = callback(xk)
if res:
break
else:
callback(xk)
如果满足停止条件,您可以在目标函数中引发异常。您的目标函数还可以将中间值存储在外部变量中。