typestar

Minimizing a function in Python

minimize walks downhill from a starting point, with or without gradients.

import numpy as np
from scipy import optimize


def rosenbrock(v):
    x, y = v
    return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2


result = optimize.minimize(rosenbrock, x0=np.array([-1.0, 2.0]))
print(result.success, result.x.round(4), round(result.fun, 8))
print(result.nit, result.message[:32])

scalar = optimize.minimize_scalar(lambda x: (x - 3.5) ** 2 + 1,
                                  bounds=(0, 10), method="bounded")
print(round(scalar.x, 4), round(scalar.fun, 4))

How it works

  1. x0 is the guess, and it matters for non-convex problems.
  2. res.x is the minimizer, res.fun the value there.
  3. method picks the algorithm; the default is usually fine.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
437
Tokens
156
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 1 of 4 in Optimization, step 10 of 23 in Scientific computing with SciPy.

← Previous Next →