Python opt.minimize
Python opt.minimize is routine at Python programming language that searches the minimum of a given function.
Example of the code with single variabe
import scipy.optimize as opt def func(x): return (x-123)**2 x0 = 0 res = opt.minimize(func, x0) print(res)
Output generated:
status: 0 success: True njev: 4 nfev: 12 hess_inv: array([[ 0.5]]) fun: 5.553105828993429e-17 x: array([ 122.99999999]) message: 'Optimization terminated successfully.' jac: array([ -2.67164069e-12])
The sixth element of the returned array seems to contain the array, and the zeroth element of the array is extremum (123) that realizes the minimal value (zero) of the function func.
Example of the code with 2 variables
import scipy.optimize as opt def func(x): return ( x[0]-123)**2 + (x[1]-3.14159)**2 x0 = [0,0] res = opt.minimize(func, x0) print(res.x)
Expected output:
[ 123.00000006 3.14159 ]
Example of the code with function of 3 variables
import scipy.optimize as opt def func(x): return x[0]**4 + x[1]**4 + 8*x[0]*x[1] + x[2]**2 x0 = [0.,0.,0.] res = opt.minimize(func, x0) print(res.x, res.fun) x1 = [1.,-1.,1.] res1 = opt.minimize(func, x1) print(res1.x, res1.fun) x2 = [-1.,1.,2.] res2 = opt.minimize(func, x2) print(res2.x, res2.fun)
Output:
(array([ 0., 0., 0.]), 0.0) (array([ 1.41421355e+00, -1.41421356e+00, -1.38110636e-08]), -7.999999999999997) (array([ -1.41421367e+00, 1.41421367e+00, 3.97624677e-07]), -7.999999999999657)
References
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)[source] Minimization of scalar function of one or more variables. Parameters: funcallable The objective function to be minimized. fun(x, *args) -> float where x is a 1-D array with shape (n,) and args is a tuple of the fixed parameters needed to completely specify the function. ..
Keywords
«Python»