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 thenumpy
library asnp
from scipy.optimize import minimize
: import theminimize
function from thescipy.optimize
librarydef f(x):
: define the functionf(x)
to be minimizedx0 = np.array([1.0, 1.0])
: create anumpy
array with the initial guess for the parametersres = minimize(f, x0, method='SLSQP')
: call theminimize
function with the functionf
, the initial guessx0
, and the optimization methodSLSQP
print(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 Python XlsxWriter to write a NumPy array to an Excel file?
- How can I use Python Scipy to perform a wavelet transform?
- How can I check if a certain version of Python is compatible with SciPy?
- How can I use Python and SciPy to generate a uniform distribution?
- How do I use the NumPy transpose function in Python?
- How do I use the scipy ttest_ind function in Python?
- How do I use Python and SciPy to create a tutorial PDF?
- How can I use Python and SciPy to visualize data?
- How do I use the trapz function in Python SciPy?
See more codes...