Optimization seeks to find the best (optimal) value of some function subject to constraints
The function is the objective, and the points that satisfy the constraints form the feasible set.
A feasible point is a global minimizer if for every feasible , and a local minimizer if this holds for every feasible near . SciPy only has minimizers, in order to maximize , you instead minimize .
import numpy as np
import scipy.linalg as la
import scipy.optimize as opt
from scipy.optimize import Bounds, LinearConstraint, NonlinearConstraint
import matplotlib.pyplot as plt
rng = np.random.default_rng(37830)Functions of One Variable¶
An easy example is to minimize a quadratic
f = lambda x: x**2 + 1 # a x^T x + 0*x + 1
x = np.linspace(-2,2,500)
plt.plot(x, f(x))
plt.show()There is a clear minimum at x = 0. You can search for minima using opt.minimize_scalar
sol = opt.minimize_scalar(f)
solThe return type gives you the function value sol.fun, as well as the value of x which achieve the minimum sol.x
x = np.linspace(-2,2,500)
plt.plot(x, f(x))
plt.scatter([sol.x], [sol.fun], label='solution')
plt.legend()
plt.show()If you want to add constraints such as , you can use bounds, along with specifying the bounded method:
sol = opt.minimize_scalar(f, bounds=(1, 1000), method='bounded')
x = np.linspace(-2,2,500)
plt.plot(x, f(x))
plt.scatter([sol.x], [sol.fun], label='solution')
plt.legend()
plt.show()For more complicated functions, there may be multiple solutions
f = lambda x : (x - 2)**2 * (x + 2)**2 - x
x = np.linspace(-3,3,500)
plt.plot(x, f(x))
plt.show()sol = opt.minimize_scalar(f)
plt.plot(x, f(x))
plt.scatter([sol.x], [sol.fun], label='solution')
plt.legend()
plt.show()Note that you will only find one minimum, and this minimum will generally only be a local minimum, not a global minimum.
Functions of Multiple variables¶
You might also wish to minimize functions of multiple variables. In this case, you use opt.minimize
A multivariate quadratic generally has the form x^T A x + b^T x + c, where x is an n-dimensional vector, A is a n x n matrix, b is a n-dimensional vector, and c is a scalar. When A is positive definite (PD), there is a unique minimum.
n = 2
A = rng.standard_normal((n + 1, n))
A = A.T @ A # generates positive-definite matrix
b = rng.random(n)
f = lambda x : np.dot(x - b, A @ (x - b)) # (x - b)^T A (x - b)
sol = opt.minimize(f, np.zeros(n))
solThe solution for the above problem is x = b
print(sol.x)
print(b)
print(np.linalg.norm(sol.x - b))We can increase the dimension of the problem to be much greater:
n = 100
A = rng.standard_normal((n + 1, n))
A = A.T @ A
b = rng.random(n)
f = lambda x : np.dot(x - b, A @ (x - b)) # (x - b)^T A (x - b)
sol = opt.minimize(f, np.zeros(n))
print(la.norm(sol.x - b))What minimize returns¶
The result is an OptimizeResult, which behaves like a dictionary. Besides the minimizer x
and the value fun, it reports whether the method thinks it succeeded (success and
message) and how much work it did (nit iterations and nfev evaluations of ). Check
success before using x, because a method that fails still returns the last point it
reached. Here we allow only two iterations:
sol = opt.minimize(f, np.zeros(n), options={'maxiter': 2})
print(sol.success, sol.message)
print("distance from the minimizer:", la.norm(sol.x - b))Extra arguments and callbacks¶
An objective often depends on parameters of . The entries of the tuple args are
passed to after on every call.
The function callback is called after every iteration with the
current point, which is a simple way to record the path of the method. Here is the Rosenbrock
function , whose minimum at lies at the bottom of a
long curved valley.
def rosenbrock(x, a, b):
return (a - x[0])**2 + b * (x[1] - x[0]**2)**2
path = [np.array([-1.2, 1.0])]
sol = opt.minimize(rosenbrock, path[0], args=(1.0, 100.0),
callback=lambda xk: path.append(xk.copy()))
path = np.array(path)
print(f"{sol.message} {sol.nit} iterations, {sol.nfev} evaluations of f, "
f"{sol.njev} of the gradient, x = {sol.x}")
xx, yy = np.meshgrid(np.linspace(-1.5, 1.5, 300), np.linspace(-0.5, 1.5, 300))
plt.contour(xx, yy, rosenbrock([xx, yy], 1.0, 100.0), levels=np.logspace(-1, 3, 12),
colors='gray', linewidths=0.6)
plt.plot(path[:, 0], path[:, 1], 'o-', ms=3)
plt.plot(1, 1, 'k*', ms=12)
plt.title('iterates of minimize on the Rosenbrock function')
plt.show()Example: Solving a Linear System¶
Recall that solving a linear system means finding so that . We can turn this into an optimization problem by seeking to minimize the residual :
n = 5
A = rng.standard_normal((n, n))
x0 = rng.standard_normal(n) # ground truth x
b = A @ x0
sol = opt.minimize(lambda x : la.norm(b - A @ x), np.zeros(n))
la.norm(sol.x - x0)Exercises¶
Modify the above example to minimize instead of (look at documentation for
la.norm). Is there any difference in the output ofopt.minimize?How fast is
la.solvecompared to the above example?
## Your code here
Constraints¶
Passing in a function to be optimized is fairly straightforward. Constraints are slightly less trivial. These are specified using classes LinearConstraint and NonlinearConstraint
Linear constraints take the form
lb <= A @ x <= ubNonlinear constraints take the form
lb <= fun(x) <= ub
For the special case of a linear constraint with the form lb <= x <= ub, you can use Bounds
Linear Constraints¶
Let’s look at how you might implement the linear constraints on a 2-vector x
where A = np.array([[1,1],[0, 1]], c = -2 * np.ones(2), and d = 2 * np.ones(2)
from scipy.optimize import Bounds, LinearConstraint
# constraint 1
C1 = Bounds(np.array([-1, -np.inf]), np.array([1,np.inf]))
# constraint 2
A = np.array([[1,1],[0,1]])
c = -2 * np.ones(2)
d = 2 * np.ones(2)
C2 = LinearConstraint(A, c, d)here’s a visualization of the constrained region:
n = 100
xx, yy = np.meshgrid(np.linspace(-3,3,n), np.linspace(-3,3,n))
C = np.zeros((n, n))
for i in range(n):
for j in range(n):
x = np.array([xx[i,j], yy[i,j]])
# constraint 1
c1 = -1 <= xx[i,j] <= 1
# constraint 2
c2 = np.all((c <= A@x, A@x <= d))
C[i,j] = c1 and c2
plt.imshow(C, extent=(-3,3,-3,3), origin='lower')
plt.show()Now, let’s say we want to minimize a function f(x) subject to x obeying the constraints given above. We can simply pass in the constraints
f = lambda x : x[0]*x[1]
sol = opt.minimize(f, rng.random(2), bounds=C1, constraints=(C2,))
solLet’s visualize the function in the constrained region:
F = np.zeros((n, n))
for i in range(n):
for j in range(n):
if C[i,j]:
F[i,j] = f([xx[i,j], yy[i,j]])
else:
F[i,j] = np.nan
plt.imshow(F, extent=(-3,3,-3,3), origin='lower')
plt.colorbar()
plt.show()The minimum value is attained at two corners of the feasible set, and
, and which one minimize returns depends on the starting point.
Nonlinear constraints¶
Nonlinear constraints can be used to define more complicated domains. For instance, let’s look at the constraint
from scipy.optimize import NonlinearConstraint
C3 = NonlinearConstraint(lambda x : np.linalg.norm(x), 1, 2)we can visualize this constraint again, and we see that it defines an annulus
n = 200
xx, yy = np.meshgrid(np.linspace(-3,3,n), np.linspace(-3,3,n))
C = np.zeros((n, n))
for i in range(n):
for j in range(n):
x = np.array([xx[i,j], yy[i,j]])
C[i,j] = 1 <= np.linalg.norm(x) <= 2
plt.imshow(C, extent=(-3,3,-3,3), origin='lower')
plt.show()Let’s try minimizing the same function as before:
f = lambda x : x[0]*x[1]
F = np.zeros((n, n))
for i in range(n):
for j in range(n):
if C[i,j]:
F[i,j] = f([xx[i,j], yy[i,j]])
else:
F[i,j] = np.nan
plt.imshow(F, extent=(-3,3,-3,3), origin='lower')
plt.colorbar()
plt.show()sol = opt.minimize(f, rng.random(2), constraints=(C3,))
solThe solution is close to one of the two true minimizers, and , where .
Example: Eigenvalues and Eigenvectors¶
One example of an optimization problem is to find the largest eigenvalue/eigenvector pair of a matrix . If is symmetric, and is the largest eigenvalue pair, then satisfies
And we have . Let’s try encoding this as an optimization problem.
n = 5
A = rng.standard_normal((n, n))
A = 0.5 * (A + A.T) # make symmetric
NormConst = NonlinearConstraint(lambda x : np.linalg.norm(x), 1, 1) # norm constraint
sol = opt.minimize(lambda x : -np.dot(x, A @ x), rng.standard_normal(n), constraints=(NormConst, ))
solLet’s take a look at a solution obtained using eigh:
import scipy.linalg as la
lam, V = la.eigh(A)
lam[-1], V[:,-1] # largest eigenpairprint("error in eigenvalue: {}".format(lam[-1] + sol.fun))
v = V[:, -1] * np.sign(V[:, -1] @ sol.x) # eigenvectors are only defined up to sign
print("error in eigenvector: {}".format(la.norm(sol.x - v)))Optimization Options¶
So far, we haven’t worried too much about the internals of opt.minimize. However, for large problems, you’re often going to want to choose an appropriate solver, and provide Jacobian and Hessian information if you are able to.
A list of available solvers is available in the minimize documentation.
Jacobian¶
The Jacobian of a multi-valued function is the matrix , where
If is scalar-valued (i.e. ), then the Jacobian is the transpose of the gradient
In our examples so far, we only provided the function. If you are able to provide the Jacobian as well, then you can typically solve problems with fewer function evaluations because you have better information about how to decrease the function value. If you don’t provide the Jacobian, many solvers will try to approximate the Jacobian using finite difference approximations, but these are typically less accurate (and slower) than if you can give an explicit formula.
Note that you can also provide a Jacobian to NonlinearConstraint
# function definition
def f(x):
return np.cos(x[0]) + np.sin(x[1])
# Jacobian of function
def Jf(x):
return np.array([-np.sin(x[0]), np.cos(x[1])])
x0 = np.array([2.0, -1.0])
%time sol1 = opt.minimize(f, x0)
sol1%time sol2 = opt.minimize(f, x0, jac=Jf)
sol2We see that when we provide the Jacobian, the number of function evaluations nfev decreases.
Checking derivatives¶
A wrong Jacobian is a common bug, and it raises no error, since the method just gets wrong
information about which way is downhill. opt.check_grad(f, jac, x) compares jac(x) with a finite
difference approximation and returns the norm of the difference, and opt.approx_fprime(x, f) returns
the approximation itself. Here is a Jacobian with a sign error:
def Jf_wrong(x):
return np.array([np.sin(x[0]), np.cos(x[1])]) # sign error in the first entry
x = rng.standard_normal(2)
print("check_grad with the correct Jacobian:", opt.check_grad(f, Jf, x))
print("check_grad with the wrong Jacobian: ", opt.check_grad(f, Jf_wrong, x))
sol = opt.minimize(f, x0, jac=Jf_wrong)
print("Success:", sol.success)
print("Message:", sol.message)
print("solution:", sol.x)Hessian¶
The Hessian of a multivariate function is a matrix of second derivatives:
The Hessian provides information about the curvature of the function , which can be used to accelerate convergence of the optimization algorithm. If you don’t provide the Hessian, many solvers will numerically approximate it, which will typically not work as well as an explicit Hessian.
Again, you can also provide a Hessian to NonlinearConstraint
def Hf(x):
return np.array([[-np.cos(x[0]), 0], [0, -np.sin(x[1])]])
%time sol3 = opt.minimize(f, x0, jac=Jf, hess=Hf)
sol3We see that the default method BFGS does not use the Hessian. Let’s choose one that does, like Newton-CG.
def Hf(x):
return np.array([[-np.cos(x[0]), 0], [0, -np.sin(x[1])]])
%time sol3 = opt.minimize(f, x0, jac=Jf, hess=Hf, method='Newton-CG')
sol3exact = np.array([np.pi, -np.pi / 2])
for name, s in [("BFGS", sol1), ("BFGS with jac", sol2), ("Newton-CG with jac and hess", sol3)]:
print(f"{name:28} nit = {s.nit}, nfev = {s.nfev}, error = {la.norm(s.x - exact):.1e}")Supplying the Jacobian cuts the number of evaluations of from 15 to 5, since BFGS no longer needs finite differences, while the error stays at about , which is set by the default tolerance on the gradient. Newton-CG also uses the Hessian and finds the minimizer to 10-13 in 5 iterations. The savings grow with the number of variables , since a finite difference gradient costs extra evaluations of .
Solvers¶
Here’s a guide to a couple of different solvers. See the notes section of minimize for additional details.
Unconstrained minimization:
BFGS- uses Jacobian evaluations to get a low-rank approximation to the Hessian. This is the default when there are no bounds or constraints.Bound constrained minimization:
L-BFGS-B- Variation of BFGS which uses limited memory (theL). Use with very large problems. Only uses Jacobian (not Hessian). This is the default when there are bounds.Unconstrained minimization with Jacobian/Hessian:
Newton-CG- uses Jacobian and Hessian to exactly solve quadratic approximations to the objective.General constrained minimization:
SLSQP- sequential quadratic programming, which minimizes a quadratic model of the objective subject to linearized constraints at each step. This is the default when there are constraints.General constrained minimization:
trust-constr- a trust region method for constrained optimization problems. Can use the Hessian of both the objective and constraints.No derivatives:
Nelder-Mead- moves a simplex of points around; convenient for a few variables, slow for many.
You can find a lot of information and examples about these different options in the scipy.optimize tutorial
Example: A Hanging Chain¶
A chain hanging between two points settles into the shape that minimizes its potential energy. Model it as rigid links of length , hanging from and .
With the positions of the joints as variables, there is one equality constraint for the length of each link.
With the angles of the links as variables, the joints are at
every link automatically has length , and only the far end needs a constraint, . The potential energy is proportional to the sum of the heights of the midpoints of the links.
n = 40 # number of links
ell = 1.5 / n # total length 1.5, hanging from (0, 0) and (1, 0)
def joints(theta):
"""
positions of the n + 1 joints of a chain whose links make angles theta with the horizontal
"""
x = ell * np.concatenate([[0.0], np.cumsum(np.cos(theta))])
y = ell * np.concatenate([[0.0], np.cumsum(np.sin(theta))])
return x, y
def energy(theta):
x, y = joints(theta)
return np.sum(y[:-1] + y[1:]) / 2 # sum of the heights of the link midpoints
def far_end(theta):
x, y = joints(theta)
return np.array([x[-1], y[-1]])
hang = NonlinearConstraint(far_end, [1.0, 0.0], [1.0, 0.0])
theta0 = np.linspace(-1, 1, n) # an incorrect initial condition
sol = opt.minimize(energy, theta0, constraints=[hang], method='SLSQP')
print(f"{sol.message} ({sol.nit} iterations); far end at {far_end(sol.x)}")The exact shape of a continuous chain is a catenary,
where is fixed by the length of the chain: the arc length must
equal 1.5. That equation for is a job for root_scalar.
a = opt.root_scalar(lambda a: 2 * a * np.sinh(1 / (2 * a)) - 1.5, bracket=(0.1, 10)).root
catenary = lambda x: a * np.cosh((x - 0.5) / a) - a * np.cosh(0.5 / a)
x, y = joints(sol.x)
print(f"a = {a:.4f}; largest vertical distance from a joint to the catenary: "
f"{np.max(np.abs(y - catenary(x))):.1e}")
s = np.linspace(0, 1, 200)
plt.figure(figsize=(8, 8))
plt.plot(s, catenary(s), 'k--', label='catenary')
plt.plot(x, y, 'o-', ms=3, label=f'chain of {n} links')
plt.plot(*joints(theta0), ':', label='first guess')
plt.gca().set_aspect('equal')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()The joints lie within of the catenary. The difference comes from replacing a continuous chain by 40 straight links, and it shrinks as the links get shorter.
Exercise¶
Repeat the hanging chain with links and plot the largest distance from the
catenary against on a log-log plot. How fast does it decrease? How does the number of
iterations of SLSQP change with ?
## Your code hereLinear Programming¶
When the objective and the constraints are all linear, the problem is a linear program:
Linear programs come up in scheduling, transportation, and resource allocation, and can be solved using
opt.linprog.
A workshop makes tables and chairs. A table needs 4 hours of carpentry
and 2 hours of painting and earns a profit of $70, and a chair needs 3 hours of carpentry and 1
hour of painting and earns $50. There are 240 hours of carpentry and 100 hours of painting per
week. To maximize the profit we minimize . The bounds
are the default in linprog; we write them out anyway.
c = np.array([-70.0, -50.0]) # minus the profit per table and per chair
A_ub = np.array([[4.0, 3.0], # hours of carpentry
[2.0, 1.0]]) # hours of painting
b_ub = np.array([240.0, 100.0])
res = opt.linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=[(0, None), (0, None)])
print(res.message)
print(f"tables: {res.x[0]:.1f}, chairs: {res.x[1]:.1f}, profit: {-res.fun:.0f}")Here is the feasible set, with lines of constant profit.
xx, yy = np.meshgrid(np.linspace(0, 70, 400), np.linspace(0, 90, 400))
feasible = (4 * xx + 3 * yy <= 240) & (2 * xx + yy <= 100)
plt.figure(figsize=(6, 5))
plt.contourf(xx, yy, feasible, levels=[0.5, 1.5], colors=['C0'], alpha=0.3)
cs = plt.contour(xx, yy, 70 * xx + 50 * yy, levels=[1000, 2000, 3000, 4100], colors='gray',
linestyles='dashed', linewidths=1)
plt.clabel(cs, fmt='%d', manual=[(7, 10), (14, 20), (21, 30), (50, 12)])
t = np.array([0.0, 70.0])
plt.plot(t, (240 - 4 * t) / 3, 'C0', label='carpentry: $4x + 3y = 240$')
plt.plot(t, 100 - 2 * t, 'C1', label='painting: $2x + y = 100$')
plt.plot(*res.x, 'k*', ms=12)
plt.xlim(0, 70)
plt.ylim(0, 90)
plt.legend()
plt.xlabel('tables')
plt.ylabel('chairs')
plt.title('feasible set and lines of constant profit')
plt.show()The profit grows toward the upper right, and the best feasible point is the corner where both constraints are active, . When a linear program has a solution, one of its solutions is at a corner (a vertex) of the feasible set. The simplex method walks from vertex to vertex, improving the objective at each step, while interior point methods approach the optimal vertex through the inside of the feasible set.
Integer variables¶
Suppose the workshop had 245 hours of carpentry. The linear program then asks for 27.5 tables.
Requiring the variables to be integers gives a mixed-integer linear program, which
opt.milp
solves. It takes the constraints as a LinearConstraint and the bounds as Bounds.
b_ub = np.array([245.0, 100.0])
relaxed = opt.linprog(c, A_ub=A_ub, b_ub=b_ub)
integer = opt.milp(c, constraints=LinearConstraint(A_ub, -np.inf, b_ub),
integrality=[1, 1], bounds=Bounds(0, np.inf))
print(f"linprog: {relaxed.x}, profit {-relaxed.fun:.0f}")
print(f"milp: {integer.x}, profit {-integer.fun:.0f}")The integer solution is not the rounded LP solution: rounding down to
gives a profit of $4140, and needs 247 hours of carpentry, while gives
$4170. Integer programs are much harder than linear programs in general (they are NP-hard),
and milp solves a sequence of linear programs with
extra bounds on the variables.
Global Optimization¶
opt.minimize is good for finding local minima of functions.
What if your function has many local minima, but you want to find the global minimum? You can use one of the global optimization functions.
Note that finding a global minimum is generally a much more difficult problem than finding a local minimum, and these functions are not guaranteed to find the true global minimum, and may not be very fast.
Here’s an example of a function which has a global minimum, but many local minima:
# global minimum at (pi, -pi/2)
def f(x, a=0.1):
return np.cos(x[0]) + np.sin(x[1]) + a*(x[0] - np.pi)**2 + a*(x[1] + np.pi/2)**2f([np.pi, -np.pi/2])Starting from , minimize finds the local minimum nearest the start:
sol = opt.minimize(f, [5.0, 5.0])
print(sol.x, sol.fun, f"({sol.nfev} evaluations of f)")
xx, yy = np.meshgrid(np.linspace(-10, 15, 1000), np.linspace(-12, 10, 1000))
plt.figure(figsize=(6, 5))
plt.contourf(xx, yy, f([xx, yy]), levels=30)
plt.colorbar()
plt.plot(np.pi, -np.pi / 2, 'w*', ms=14, label='global minimum')
plt.plot(*sol.x, 'wo', label='minimize from (5, 5)')
plt.legend()
plt.show()The simplest global strategy is multistart: run a local method from many random starting points and keep the best result.
best, nfev = None, 0
for _ in range(20):
trial = opt.minimize(f, rng.uniform(-10, 10, size=2))
nfev += trial.nfev
if best is None or trial.fun < best.fun:
best = trial
print(f"best of 20 starts: x = {best.x}, f = {best.fun:.6f}, {nfev} evaluations of f")basinhopping
is a multistart that uses what it has found. From the current local minimum it jumps by a
random step, of size stepsize, and minimizes again. It accepts the new local minimum if it is
lower, and otherwise with probability , where is the increase in
and the “temperature” T should be comparable to the differences in between neighboring
local minima. By default it also adjusts stepsize as it goes.
sol = opt.basinhopping(f, [5.0, 5.0], seed=rng)
print(f"x = {sol.x}, f = {sol.fun:.6f}, {sol.nfev} evaluations of f")Basin hopping stayed in the basin where it started. Neighboring local minima of are about apart, and jumps of the default size 0.5 lead back to the same minimum. Jumps of about half the distance between minima can reach the neighboring basins:
sol = opt.basinhopping(f, [5.0, 5.0], stepsize=3.0, seed=rng)
print(f"x = {sol.x}, f = {sol.fun:.6f}, {sol.nfev} evaluations of f")Here’s the same problem using opt.dual_annealing and
opt.differential_evolution,
which search a box given by bounds instead of starting from a point:
%time sol = opt.dual_annealing(f, bounds=[[-100, 100], [-100, 100]], seed=rng)
print(f"dual annealing: x = {sol.x}, f = {sol.fun:.6f}, {sol.nfev} evaluations of f")
%time sol = opt.differential_evolution(f, bounds=[[-100, 100], [-100, 100]], seed=rng)
print(f"differential evolution: x = {sol.x}, f = {sol.fun:.6f}, {sol.nfev} evaluations of f")Both find the global minimum. They need bounds but no starting point. All of these global methods are expensive: differential evolution used about 500 evaluations of , the multistart about 700, basin hopping about 2500, and dual annealing about 4000, against 30 for the local minimization from . None of them can guarantee that the minimum it returns is global. They are a good choice when is cheap to evaluate and there are few variables.
def f(x):
return x + 2*np.cos(x)
sol = opt.root(f, rng.random())
print(sol.x, sol.fun) # root and valuefor scalar functions, you can also use root_scalar
sol = opt.root_scalar(f, x0=-1, x1=1)
sol.rootYou can also find roots of multi-valued functions. E.g. if we want to solve the nonlinear system
we can seek to find a root
def f(x):
return [x[0] * np.cos(x[1]) - 4, x[1]*x[0] - x[1] - 5]
%time sol = opt.root(f, np.ones(2))
solprint(sol.x, sol.fun) # root and valueYou can also specify the Jacobian for faster convergence (in this case, the Jacobian is )
# returns the function and Jacobian as tuple
def f2(x):
f = [x[0] * np.cos(x[1]) - 4,
x[1]*x[0] - x[1] - 5]
df = np.array([[np.cos(x[1]), -x[0] * np.sin(x[1])],
[x[1], x[0] - 1]])
return f, df
%time sol = opt.root(f2, np.ones(2), jac=True, method='lm')
solprint(sol.x, sol.fun) # root and valueWe see that the computed root in this case satisfies the equations more precisely.
Exercise¶
Compute a root of the above example using opt.minimize instead of opt.root. One way to do this is to minimize . Do the results differ if you use a 1-norm vs a 2-norm?
Above examples: find roots of multi-valued functions. E.g. if we want to solve the nonlinear system
## 2-norm:
def f(x):
return la.norm([x[0] * np.cos(x[1]) - 4, x[1]*x[0] - x[1] - 5], ord = 2)
sol1 = opt.minimize(f, np.ones(2))
print(sol1.x)
## 1-norm:
def g(x):
return la.norm([x[0] * np.cos(x[1]) - 4, x[1]*x[0] - x[1] - 5], ord =1)
sol2 = opt.minimize(g, np.ones(2))
print(sol2.x)As we can see from the result, 1-norm result and 2-norm result are slightly different. But they are both very close to the result computed by opt.root.