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:
- Import the minimize() function from the scipy.optimize module:
from scipy.optimize import minimize
- Define a function to be minimized:
return (x[0] - 1)**2 + (x[1] - 2.5)**2
- Set the initial guess of the solution:
x0 = [0, 0]
- Call the minimize() function to find the optimal solution:
res = minimize(objective, x0)
- Print the optimal solution:
print(res.x)
For more information, see the following links:
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I check if a certain version of Python is compatible with SciPy?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Python Scipy to perform a Z test?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How do I use Python and SciPy to write a WAV file?
- How do I use the scipy ttest_ind function in Python?
- How do I convert a Python Numpy array to a list?
See more codes...