Chapters
Python114 chapters

Exercises

Regression

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Fit a line to the study hours and print the slope, rounded to one place.

Python needs scikit-learn, downloaded on first run
from sklearn.linear_model import LinearRegression

X = [[1], [2], [3], [4], [5]]
y = [52, 55, 61, 64, 68]
# print the slope
Exercise 2

Print the mean absolute error on the test set, rounded to one place.

Python needs scikit-learn, downloaded on first run
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=0
)
model = LinearRegression().fit(X_train, y_train)
# print the MAE
Exercise 3

Show that R2 is 0 for a model that always predicts the mean.

Python needs scikit-learn, downloaded on first run
from sklearn.metrics import r2_score

actual = [10, 20, 30, 40]
# print the R2 of always predicting the mean