Minimizing multivariate functions (minimize) in SciPy - Time & Space Complexity
When we use scipy to find the lowest point of a function with many variables, it takes some steps to get there.
We want to know how the number of steps grows as the problem size grows.
Analyze the time complexity of the following code snippet.
from scipy.optimize import minimize
import numpy as np
def func(x):
return np.sum(x**2)
x0 = np.zeros(100) # start point with 100 variables
result = minimize(func, x0, method='BFGS')
print(result.success)
This code tries to find the minimum of a function with 100 variables using the BFGS method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Each iteration computes the function value and its gradient over all variables.
- How many times: The optimizer repeats these calculations many times until it converges.
As the number of variables grows, each step takes longer because it must check all variables.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Few hundred operations per iteration |
| 100 | Thousands of operations per iteration |
| 1000 | Hundreds of thousands of operations per iteration |
Pattern observation: The work per iteration grows roughly with the square of the number of variables.
Time Complexity: O(n^2)
This means the time to do one iteration grows roughly with the square of the number of variables.
[X] Wrong: "The time to minimize grows linearly with the number of variables."
[OK] Correct: Because methods like BFGS update matrices of size n x n, the work per step grows faster than just the number of variables.
Understanding how optimization time grows helps you explain choices in real problems and shows you know what affects performance.
What if we changed the method from BFGS to a simpler gradient descent? How would the time complexity change?
Practice
scipy.optimize.minimize in data science?Solution
Step 1: Understand the function's goal
scipy.optimize.minimizeis designed to find the lowest point of a function with multiple variables.Step 2: Compare options with the function's purpose
Sorting, calculating mean, or generating random numbers are unrelated to minimizing functions.Final Answer:
To find the minimum value of a multivariate function -> Option AQuick Check:
Minimize means find lowest point [OK]
- Confusing minimize with sorting or statistics
- Thinking it generates random data
- Assuming it calculates averages
scipy.optimize.minimize for a function f with initial guess x0?Solution
Step 1: Recall the function signature
The correct call isminimize(fun, x0)wherefunis the function andx0is the starting guess.Step 2: Check each option
minimize(f, x0) matches the correct order. minimize(x0, f) reverses arguments. minimize(f(x0)) calls the function instead of passing it. minimize(f, x0, method='max') uses an invalid method 'max'.Final Answer:
minimize(f, x0) -> Option BQuick Check:
Function first, guess second [OK]
- Swapping function and initial guess
- Calling function instead of passing it
- Using invalid method names
from scipy.optimize import minimize
def f(x):
return (x[0]-1)**2 + (x[1]+2)**2
result = minimize(f, [0, 0])
print(result.x.round(2))Solution
Step 1: Understand the function to minimize
The function is(x0-1)^2 + (x1+2)^2, which is smallest whenx0=1andx1=-2.Step 2: Check the minimize result
Starting from [0,0], minimize finds the point closest to the minimum, which is [1, -2].Final Answer:
[1.00, -2.00] -> Option DQuick Check:
Minimum at x=1, y=-2 [OK]
- Confusing signs inside the function
- Expecting initial guess as output
- Misreading the function formula
from scipy.optimize import minimize
def f(x):
return x[0]**2 + x[1]**2
result = minimize(f, 0)
print(result.x)Solution
Step 1: Check the initial guess type
The function expects a vector input like [x0, x1], but the initial guess is a single number 0, which is invalid.Step 2: Understand the correct input format
Initial guess must be a list or array with the same dimension as the function input, e.g., [0, 0].Final Answer:
Initial guess should be a list or array, not a single number -> Option AQuick Check:
Input vector must match function variables [OK]
- Passing scalar instead of vector as initial guess
- Thinking function output must be list
- Assuming method must be specified always
f(x, y) = (x-3)^2 + (y+1)^2 but only allow y to be between -2 and 0. Which code correctly applies this constraint using scipy.optimize.minimize?Solution
Step 1: Understand bounds parameter
Bounds are given as a list of (min, max) tuples for each variable. Here, x has no bounds, y is between -2 and 0.Step 2: Match bounds to variables
minimize(lambda v: (v[0]-3)**2 + (v[1]+1)**2, [0, 0], bounds=[(None, None), (-2, 0)]) correctly sets bounds as [(None, None), (-2, 0)] meaning x unbounded, y bounded. minimize(lambda v: (v[0]-3)**2 + (v[1]+1)**2, [0, 0], bounds=[(-2, 0), (None, None)]) reverses bounds. Options A and D use constraints incorrectly for this case.Final Answer:
minimize(lambda v: (v[0]-3)**2 + (v[1]+1)**2, [0, 0], bounds=[(None, None), (-2, 0)]) -> Option CQuick Check:
Bounds list matches variable order [OK]
- Swapping bounds order for variables
- Using constraints instead of bounds incorrectly
- Setting equality constraint instead of bounds
Ready to prove it?
Pass the test and this pattern moves unknown
