0
0
NumPydata~10 mins

Linear regression with np.polyfit() in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to fit a linear model to x and y using np.polyfit.

NumPy
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
coefficients = np.polyfit(x, y, [1])
Drag options to blanks, or click blank then click option'
A1
B3
C2
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using degree 2 or higher for a simple linear fit.
Using degree 0 which fits a constant only.
2fill in blank
medium

Complete the code to predict y values using the fitted coefficients.

NumPy
import numpy as np
x = np.array([1, 2, 3, 4, 5])
coefficients = np.polyfit(x, np.array([2, 4, 5, 4, 5]), 1)
predicted_y = coefficients[[1]] * x + coefficients[1]
Drag options to blanks, or click blank then click option'
A1
B0
C2
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using coefficients[1] as slope.
Using negative indices incorrectly.
3fill in blank
hard

Fix the error in the code to correctly fit a linear model and predict y.

NumPy
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
coefficients = np.polyfit(x, y, [1])
predicted_y = coefficients[0] * x + coefficients[[2]]
Drag options to blanks, or click blank then click option'
A1
B0
C2
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using degree 0 or 2.
Using coefficients[0] as intercept.
4fill in blank
hard

Fill both blanks to create a dictionary of x values and their predicted y values using np.polyfit.

NumPy
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
coeffs = np.polyfit(x, y, [1])
predictions = {val: coeffs[0] * val + coeffs[[2]] for val in x}
Drag options to blanks, or click blank then click option'
A1
B0
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong degree.
Mixing up slope and intercept indices.
5fill in blank
hard

Fill all three blanks to create a list of predicted y values for x using np.polyfit and a list comprehension.

NumPy
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
coeffs = np.polyfit(x, y, [1])
predicted = [coeffs[[2]] * val + coeffs[[3]] for val in x]
Drag options to blanks, or click blank then click option'
A1
B0
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping slope and intercept indices.
Using wrong degree.