Prediction
- Machine Learning course
- Beginner
- Lesson 95/112
- 7 min
Make predictions with the model.
Prediction
With the chosen model we predict for the patients in the test set. Seeing predictions next to the true values shows in which range the model struggles:
p = model.predict(X_test)
for gercek, tahmin in zip(y_test[:5], p[:5]):
print(f"{gercek:6.0f} {tahmin:8.1f}")Linear models tend to pull extreme values towards the mean: they predict very high progression lower than it is.
Examining residuals
The mean of the residuals should be close to 0 and show no clear pattern. The largest absolute residuals are the patients the model got most wrong:
kalinti = y_test - p
print(kalinti.mean().round(1))
en_kotu = np.argsort(np.abs(kalinti))[-3:]
print(y_test[en_kotu], p[en_kotu].round(0))np.argsort gives the indices sorted from smallest to largest; the last three are the biggest errors.
Practice Prediction and residual
Get the test predictions with model. Print the first 3 predictions with np.round(..., 1), then the largest absolute residual with round(..., 1).
Starter code
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
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)
from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(X_train, y_train)
# buraya yazSample solution
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
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)
from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(X_train, y_train)
p = model.predict(X_test)
print(np.round(p[:3], 1))
kalinti = y_test - p
print(round(np.abs(kalinti).max(), 1))Expected output
[238.5 248.9 164.1] 162.7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is a residual?
- The size of the test set
- The true value minus the prediction Correct answer
- The mean of the predictions
- A model weight
Explanation: Residual = y - ŷ; if positive the model under-predicted, if negative it over-predicted.
2 Get the indices sorting the absolute residuals from smallest to largest.
sira = np.____(np.abs(kalinti))
sira = np.argsort(np.abs(kalinti))
Explanation: argsort returns indices, not values.
3 Match the expressions.
| Term | Meaning |
|---|---|
y_test - p |
Residuals |
np.abs(kalinti) |
Absolute error |
np.argsort(...)[-3:] |
Three largest errors |
kalinti.mean() |
Systematic bias |