0
0
SciPydata~20 mins

Least squares (least_squares) in SciPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Least Squares Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of scipy.optimize.least_squares with linear residuals
What is the output of the following code snippet using scipy.optimize.least_squares to fit a line y = mx + b to data points?
SciPy
import numpy as np
from scipy.optimize import least_squares

def residuals(params, x, y):
    m, b = params
    return m * x + b - y

x_data = np.array([0, 1, 2, 3])
y_data = np.array([1, 3, 5, 7])

result = least_squares(residuals, x0=[0, 0], args=(x_data, y_data))
print(result.x)
A[3.0, 0.0]
B[1.0, 2.0]
C[0.5, 1.0]
D[2.0, 1.0]
Attempts:
2 left
💡 Hint
Think about the line that fits points (0,1), (1,3), (2,5), (3,7) exactly.
data_output
intermediate
2:00remaining
Number of iterations in least_squares optimization
After running the following code, what is the value of result.nfev (number of function evaluations)?
SciPy
import numpy as np
from scipy.optimize import least_squares

def residuals(p, x, y):
    return p[0] * x + p[1] - y

x = np.linspace(0, 10, 5)
y = 3 * x + 4 + np.random.normal(0, 0.1, size=x.size)

result = least_squares(residuals, x0=[0, 0], args=(x, y))
print(result.nfev)
A10
B4
C6
D1
Attempts:
2 left
💡 Hint
The solver usually needs multiple evaluations to converge, but not too many for a simple linear fit.
🔧 Debug
advanced
2:00remaining
Identify the error in least_squares residual function
What error will this code raise when run?
SciPy
import numpy as np
from scipy.optimize import least_squares

def residuals(params, x, y):
    m, b = params
    return m * x + b + y  # Incorrect sign here

x = np.array([1, 2, 3])
y = np.array([2, 4, 6])

result = least_squares(residuals, x0=[0, 0], args=(x, y))
ANo error, but wrong fit result
BTypeError due to incompatible operations
CValueError due to shape mismatch
DRuntimeWarning due to overflow
Attempts:
2 left
💡 Hint
Check the residuals formula carefully for correctness.
🧠 Conceptual
advanced
2:00remaining
Effect of jac='3-point' in least_squares
What does setting jac='3-point' do in scipy.optimize.least_squares?
AUses an analytical Jacobian provided by the user
BUses a numerical approximation of the Jacobian using three points per variable
CDisables Jacobian calculation for faster runtime
DUses a random Jacobian matrix for stochastic optimization
Attempts:
2 left
💡 Hint
Think about numerical differentiation methods.
🚀 Application
expert
2:00remaining
Predict parameter values from least_squares output
Given this output from least_squares: result.x = [1.5, -0.5], and residuals defined as m * x + b - y, what is the predicted y value for x=4?
A5.5
B6.5
C7.5
D4.5
Attempts:
2 left
💡 Hint
Use the formula y = m*x + b with given parameters.