CodeBlanks Logo Icon CodeBlanks

Prediction

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 array

The 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: careful

That 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

model.py
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 yaz

Sample solution

model.py
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.

Question
p = m.predict(____)
Answer
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

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation