0
0
SciPydata~30 mins

Least squares (least_squares) in SciPy - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use print(f"Slope: {result.x[0]:.2f}, Intercept: {result.x[1]:.2f}") to show the results rounded to two decimals.