Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Fitting a Line Using Least Squares
📖 Scenario: You have collected some data points about the hours studied and the scores obtained by students in a test. You want to find the best straight line that fits this data to predict scores based on hours studied.
🎯 Goal: Build a simple linear model using the least_squares function from scipy.optimize to find the best fit line for the data points.
📋 What You'll Learn
Create arrays for hours studied and scores obtained
Define a function to calculate residuals between predicted and actual scores
Use least_squares to find the best fit parameters
Print the best fit slope and intercept
💡 Why This Matters
🌍 Real World
Least squares fitting is used in many fields like economics, biology, and engineering to find trends and make predictions from data.
💼 Career
Data scientists and analysts use least squares methods to build predictive models and understand relationships between variables.
Progress0 / 4 steps
1
Create the data arrays
Create two numpy arrays called hours and scores with these exact values: hours = [1, 2, 3, 4, 5] and scores = [1.5, 3.7, 3.2, 5.5, 6.1].
SciPy
Hint
Use np.array to create arrays from the lists.
2
Define the residuals function
Define a function called residuals that takes a parameter array params and returns the difference between predicted scores and actual scores. Use the formula predicted = params[0] * hours + params[1] inside the function.
SciPy
Hint
The function should return the difference between predicted and actual scores.
3
Use least_squares to find best fit
Import least_squares from scipy.optimize. Then call least_squares with the residuals function and an initial guess [1, 0]. Save the result in a variable called result.
SciPy
Hint
Use from scipy.optimize import least_squares and call least_squares(residuals, [1, 0]).
4
Print the best fit parameters
Print the slope and intercept from result.x using print(f"Slope: {result.x[0]:.2f}, Intercept: {result.x[1]:.2f}").
SciPy
Hint
Use print(f"Slope: {result.x[0]:.2f}, Intercept: {result.x[1]:.2f}") to show the results rounded to two decimals.
Practice
(1/5)
1. What is the main purpose of using scipy.optimize.least_squares in data science?
easy
A. To find the best fit parameters by minimizing the difference between model predictions and data
B. To sort data points in ascending order
C. To calculate the mean of a dataset
D. To generate random numbers for simulations
Solution
Step 1: Understand the purpose of least squares
Least squares is used to find parameters that minimize the error between a model and observed data.
Step 2: Match the purpose with the options
Only To find the best fit parameters by minimizing the difference between model predictions and data describes minimizing differences to find best fit parameters.
Final Answer:
To find the best fit parameters by minimizing the difference between model predictions and data -> Option A
Quick Check:
Least squares = minimize error [OK]
Hint: Least squares minimizes errors to fit data best [OK]
Common Mistakes:
Confusing least squares with sorting or averaging
Thinking it generates random data
Assuming it calculates statistics like mean
2. Which of the following is the correct way to call scipy.optimize.least_squares with a residual function fun and initial guess x0?
easy
A. least_squares(fun=x0, x0=fun)
B. least_squares(x0, fun)
C. least_squares(fun, x0)
D. least_squares(x0)
Solution
Step 1: Recall the function signature
The correct call is least_squares(fun, x0) where fun is the residual function and x0 is the initial guess.
Step 2: Check each option
least_squares(fun, x0) matches the correct order and parameters. Others have wrong order or missing arguments.
Final Answer:
least_squares(fun, x0) -> Option C
Quick Check:
Function first, initial guess second [OK]
Hint: Function first, initial guess second in least_squares call [OK]
Common Mistakes:
Swapping the order of arguments
Passing only one argument
Using keyword arguments incorrectly
3. What will be the output of this code snippet?
import numpy as np
from scipy.optimize import least_squares
def residuals(x):
return np.array([2*x[0] - 4, x[1] + 3])
result = least_squares(residuals, x0=[0, 0])
print(result.x)
medium
A. [-2.0, 3.0]
B. [4.0, 3.0]
C. [0.0, 0.0]
D. [2.0, -3.0]
Solution
Step 1: Understand the residual function
The residuals are [2*x0 - 4, x1 + 3]. We want to find x that makes residuals close to zero.
Step 2: Solve equations for zero residuals
Set 2*x0 - 4 = 0 => x0 = 2; and x1 + 3 = 0 => x1 = -3.
Final Answer:
[2.0, -3.0] -> Option D
Quick Check:
Zero residuals at x=[2, -3] [OK]
Hint: Set residuals to zero and solve for variables [OK]
Common Mistakes:
Not solving residual equations correctly
Confusing signs in equations
Assuming initial guess is the answer
4. Identify the error in this code using least_squares:
import numpy as np
from scipy.optimize import least_squares
def residuals(x):
return 2*x - 5
result = least_squares(residuals, x0=3)
print(result.x)
medium
A. Initial guess x0 should be a list or array, not a scalar
B. Residual function returns a scalar instead of an array
C. Missing import statement for numpy
D. least_squares requires a Jacobian function
Solution
Step 1: Check residual function output
The residual function returns 2*x - 5, which is a scalar, but least_squares expects an array-like residual.
Step 2: Verify other parts
x0 as scalar is allowed; numpy is imported; Jacobian is optional.
Final Answer:
Residual function returns a scalar instead of an array -> Option B
Quick Check:
Residuals must be array-like [OK]
Hint: Residuals must be array, not single number [OK]
Common Mistakes:
Returning scalar residual instead of array
Thinking initial guess must be array
Assuming Jacobian is mandatory
5. You have noisy data points for a line: x = [0,1,2,3], y = [1.1, 2.0, 2.9, 4.2]. Using least_squares, which residual function best fits a line model y = m*x + c to estimate m and c?
hard
A. def residuals(p): return y - (p[0]*x + p[1])
B. def residuals(p): return p[0]*x + p[1]
C. def residuals(p): return (p[0]*x + p[1]) * y
D. def residuals(p): return y / (p[0]*x + p[1])
Solution
Step 1: Understand residuals for least squares
Residuals are differences between observed y and model predictions m*x + c.
Step 2: Check residual function forms
def residuals(p): return y - (p[0]*x + p[1]) returns y - model prediction (m*x + c), the standard residuals to minimize. def residuals(p): return p[0]*x + p[1] returns only the model predictions without subtracting y, so it minimizes the sum of squared model values instead of fitting errors.
Step 3: Eliminate incorrect options
Options C and D multiply or divide, which is incorrect for residuals.
Final Answer:
def residuals(p): return y - (p[0]*x + p[1]) -> Option A
Quick Check:
Residual = observed - predicted [OK]
Hint: Residual = observed minus predicted values [OK]
Common Mistakes:
Using multiplication or division instead of subtraction