0
$\begingroup$

I'm trying to monitor the progress of FindMinimum[] using StepMonitor. I'd specifically like to have the code print out the value of the objective function and the variable values. For example,

FindMinimum[{objF = objFunc[x, y], x >0, y>0}, {{x, 1}, {y, 1}},
  StepMonitor:> {Print[{objF, x, y}]}
]

where I've been careful to restrict calculation of objFunc[] to only the cases where it has numerical values for x and y. That is,

 objF[x_?NumericQ, y_?NumericQ] := Module[{}, ....]

When I try running the FindMinimum[] above, my output looks like this.

 {objFunc[x, y], 0.235, 1.875}
 {objFunc[x, y], 0.244, 1.654}

I've tried using

  • StepMonitor:> {Print[{Evaluate[objF], x, y}]}
  • StepMonitor:> {Print[{objF/.{x->x, y->y}, x, y}]}
  • StepMonitor:> {Print[{objF/.{Hold[x]->x, Hold[y]->y}, x, y}]}

But none of them give the desired results.

Confusingly, to me anyway, EvaluationMonitor behaves the way I expect. That is,

EvaluationMonitor:> {Print[{objF, x, y}]}

Produces,

{33.456, 1.000, 1.000}
{32.456, 0.235, 1.875}
{31.555, 0.244, 1.654}

How do I solve this issue?

ps. Perhaps these problems would be solved using Reap[] and Sow[], but I'd like to monitor the progress of the optimization in real time, not after the fact.

$\endgroup$
2
$\begingroup$

It is because FindMinimum has the attribute HoldAll and you need to inject the expression objFunc[x, y] or objF[x, y] (it appears both ways in the OP currently) into the StepMonitor code. Injection can be accomplished with With. What appears to happen is this:

  • At each step, any appearances of x and y in the literal code {objF, x, y} passed to StepMonitor are replaced by their numeric values at the current step.
  • The resulting expression is evaluated. At this point the symbol objF evaluates to objFunc[x, y], which appears as is when printed, since objFunc does not evaluate on symbolic input.

I could show how on a minimal working example, but there isn't one.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.