Prediction
- Machine Learning course
- Beginner
- Lesson 44/112
- 5 min
A trained model makes predictions on new data with predict().
predict
predict always takes two-dimensional input and returns a one-dimensional array. Even a single example needs double square brackets:
m.predict([[90]]) # one example
m.predict([[90], [110], [130]]) # three examples -> three predictions
# m.predict([90]) ValueError: expected a 2D arrayThe prediction is the value of the learned line at the input point: coef_ · x + intercept_.
Extrapolation
The model produces a number outside the training data's range too, but trusting it is risky. A model trained on 50-150 m² houses gives a linear result for 1000 m²; the real price may be very different.
print(X.min(), X.max()) # training range
print(m.predict([[1000]])) # out of range: carefulThat inputs for prediction resemble the training data is one of ML's core assumptions.
Practice Predict by hand and with the model
Train the model. Get the predictions for 6 and 7 with predict and print them with np.round(..., 2). Then compute the prediction for 6 by hand (coef_[0] * 6 + intercept_), round it to 2 digits and print it.
Starter code
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([3.1, 4.9, 7.2, 8.8, 11.0])
# buraya yazSample solution
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([3.1, 4.9, 7.2, 8.8, 11.0])
m = LinearRegression().fit(X, y)
print(np.round(m.predict([[6], [7]]), 2))
print(round(m.coef_[0] * 6 + m.intercept_, 2))Expected output
[12.91 14.88] 12.91
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a model with <code>coef_ = [2]</code> and <code>intercept_ = 1</code> predict for 5?
- 12
- 11 Correct answer
- 10
- 7
Explanation: 2 · 5 + 1 = 11.
2 Get predictions for two examples.
p = m.predict(____)
p = m.predict([[3], [7]])
Explanation: Each example must be a separate inner list; [[3, 7]] is one example with two features.
3 Match the inputs.
| Term | Meaning |
|---|---|
[[5]] |
One example, one feature |
[[5], [6]] |
Two examples |
[[5, 6]] |
One example, two features |
[5] |
Invalid input |