0
0
NumPydata~30 mins

Linear regression with np.polyfit() in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Linear regression with np.polyfit()
📖 Scenario: You are a data analyst at a small store. You want to understand how the number of hours spent advertising affects the number of sales. You have collected data for 7 days.
🎯 Goal: Build a simple linear regression model using np.polyfit() to find the relationship between advertising hours and sales. Then, display the slope and intercept of the line.
📋 What You'll Learn
Create two lists: hours and sales with given values
Create a variable degree to set the polynomial degree
Use np.polyfit() with hours, sales, and degree to find the slope and intercept
Print the slope and intercept values
💡 Why This Matters
🌍 Real World
Linear regression helps businesses understand relationships between variables, like advertising time and sales, to make better decisions.
💼 Career
Data analysts and scientists use linear regression to build predictive models and explain trends in data.
Progress0 / 4 steps
1
Create the data lists
Create a list called hours with these exact values: [1, 2, 3, 4, 5, 6, 7]. Create another list called sales with these exact values: [3, 4, 2, 5, 6, 7, 8].
NumPy
Need a hint?

Use square brackets to create lists. Separate numbers with commas.

2
Set the polynomial degree
Create a variable called degree and set it to 1 to indicate a linear fit.
NumPy
Need a hint?

Set degree to 1 because linear regression fits a line.

3
Apply np.polyfit() to find slope and intercept
Import numpy as np. Use np.polyfit() with hours, sales, and degree to create a variable called coefficients. This will hold the slope and intercept.
NumPy
Need a hint?

Use import numpy as np first. Then call np.polyfit(hours, sales, degree).

4
Print the slope and intercept
Print the slope and intercept from coefficients. The slope is the first element, and the intercept is the second element. Use print() to show them with labels.
NumPy
Need a hint?

Use coefficients[0] for slope and coefficients[1] for intercept. Use print() with f-strings.