Exercises
Regression
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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
coef_ is an array with one weight per feature.
from sklearn.linear_model import LinearRegression
X = [[1], [2], [3], [4], [5]]
y = [52, 55, 61, 64, 68]
model = LinearRegression().fit(X, y)
print(round(model.coef_[0], 1))Exercise 2Passed
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
sklearn.metrics has mean_absolute_error(actual, predicted).
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
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(round(mean_absolute_error(y_test, model.predict(X_test)), 1))Exercise 3Passed
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
The mean of those four numbers is 25.
from sklearn.metrics import r2_score
actual = [10, 20, 30, 40]
print(r2_score(actual, [25, 25, 25, 25]))