Math optimisation with Scipy
Math optimisation examples using scipy
import numpy as np
from scipy import optimize
def f(x):
return -np.exp(-(x-0.7)**2)
result = optimize.minimize_scalar(f)
result.success, type(result)
result
result.x - 0.7
def f(x): # The rosenbrock function
return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
optimize.minimize(f, [2, -1], method="CG")
def jacobian(x):
return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2)))
optimize.minimize(f, [2, 1], method="CG", jac=jacobian)
def f(x): # The rosenbrock function
return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
def jacobian(x):
return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2)))
optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian)
def hessian(x): # Computed with sympy
return np.array(((1 - 4*x[1] + 12*x[0]**2, -4*x[0]), (-4*x[0], 2)))
optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian, hess=hessian)