Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using degree 2 or higher for a simple linear fit.
Using degree 0 which fits a constant only.
✗ Incorrect
For a linear regression, the degree of the polynomial is 1.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using coefficients[1] as slope.
Using negative indices incorrectly.
✗ Incorrect
The first coefficient (index 0) is the slope (m) in y = mx + b.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using degree 0 or 2.
Using coefficients[0] as intercept.
✗ Incorrect
Degree must be 1 for linear fit. Intercept is at index 1.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong degree.
Mixing up slope and intercept indices.
✗ Incorrect
Degree 1 for linear fit. Intercept is coefficients[1].
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping slope and intercept indices.
Using wrong degree.
✗ Incorrect
Degree 1 for linear fit. Slope is coeffs[0], intercept is coeffs[1].