9951 explained code solutions for 126 technologies


python-scipyHow can I use Python Scipy to optimize and minimize a function?


Scipy provides a set of powerful tools for optimization and minimization of functions. The scipy.optimize module contains a variety of optimization algorithms and minimization techniques.

For example, the minimize() function can be used to minimize a given function. The following code block shows an example of using the minimize() function to minimize a simple function:

from scipy.optimize import minimize

def objective(x):
    return (x[0] - 1)**2 + (x[1] - 2.5)**2

x0 = [0, 0]
res = minimize(objective, x0)

print(res.x)

Output example

[1. 2.5]

The code above is composed of the following parts:

  1. Import the minimize() function from the scipy.optimize module:

from scipy.optimize import minimize

  1. Define a function to be minimized:
    return (x[0] - 1)**2 + (x[1] - 2.5)**2
  1. Set the initial guess of the solution:

x0 = [0, 0]

  1. Call the minimize() function to find the optimal solution:

res = minimize(objective, x0)

  1. Print the optimal solution:

print(res.x)

For more information, see the following links:

Edit this code on GitHub