python-scipyHow can I use Python and SciPy to maximize a function?
To maximize a function with Python and SciPy, you can use the scipy.optimize.minimize function. This function requires a function to minimize, an initial guess for the parameters, and a method of optimization. For example, you could use the SLSQP method to maximize the function f(x,y) = x^2 + y^2 with initial guess x=1 and y=1:
import numpy as np
from scipy.optimize import minimize
def f(x):
x1 = x[0]
x2 = x[1]
return x1**2 + x2**2
x0 = np.array([1.0, 1.0])
res = minimize(f, x0, method='SLSQP')
print(res.x)
Output example
[0. 0.]
The code above consists of the following parts:
import numpy as np: import thenumpylibrary asnpfrom scipy.optimize import minimize: import theminimizefunction from thescipy.optimizelibrarydef f(x):: define the functionf(x)to be minimizedx0 = np.array([1.0, 1.0]): create anumpyarray with the initial guess for the parametersres = minimize(f, x0, method='SLSQP'): call theminimizefunction with the functionf, the initial guessx0, and the optimization methodSLSQPprint(res.x): print the optimized parameters
For more information on using Python and SciPy to maximize a function, see the following links:
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I use Scipy zeros in Python?
- How can I use Python and SciPy to find the zeros of a function?
- How do I create a QQ plot using Python and SciPy?
- How can I use the x.shape function in Python Numpy?
- How do I calculate the cross-correlation of two arrays using Python and NumPy?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How do I use scipy.optimize.curve_fit in Python?
- How can I check if a certain version of Python is compatible with SciPy?
See more codes...