0

I am using L-BFGS-B optimizer from Scipy package. Here is the documentation.

My code has the following structure. obj_func is the objective function that is used to minimize "a". In order to do so, obj_func should only return "a".

Question: Is there a way to obtain "b" and "c" from obj_func?

Currently I am using function attribute. But I am not sure this is the preferred way.

def obj_func(x, *args)
    a, b, c = compute(x) # compute is where major computation happens
    # I want to access b and c from outside the function
    obj_func.result = [b,c] # use function attribute
    return a

result = optimize.fmin_l_bfgs_b(obj_func, x0, bounds=bounds, args=args)
b, c = obj_func.result
zcadqe
  • 937
  • 2
  • 13
  • 20
  • *"Currently I am using function attribute."* Are you sure that the last call to `obj_func` performed by `fmin_l_bfgs` is with the optimal `x`? – Warren Weckesser Mar 22 '17 at 18:58
  • That is a good point. Is there a way to check that? – zcadqe Mar 22 '17 at 19:07
  • You could save `a`, `b` and `c`, and only reassign the values to the attribute if the old `a` is larger than the new `a`. You could also save `x`, and verify at the end that the saved `x` is the same as the `x` that is returned by `fmin_l_bfgs`. – Warren Weckesser Mar 22 '17 at 20:05
  • Thanks! By the way, is it a good practice to use the attribute to save these items? Are these the only way? – zcadqe Mar 22 '17 at 20:56
  • 1
    An alternative would be to pass in a dictionary as an additional argument in `args`, and save the auxiliary variables in the dictionary instead of in an attribute of the function. – Warren Weckesser Mar 22 '17 at 21:05
  • Oh, I see. So I can send the reference of dictionary object as a function argument, and mutate the dictionary inside the function. Thanks for the suggestion! – zcadqe Mar 23 '17 at 00:09
  • 1
    Have you tried `_, b, c = compute(result.x)`, i. e. just evaluating part of the objective again for the optimal value? – Tristan Mar 23 '17 at 04:35

0 Answers0