CodeBlanks Logo Icon CodeBlanks

Model training

The model learns from training data with the fit() method and updates weights.

What does fit do?

When fit(X, y) is called, the model computes its parameters from the data and stores them inside the object. Because the method returns the object itself, calls can be chained:

m = LinearRegression()
m.fit(X, y)                       # m is now trained
m2 = LinearRegression().fit(X, y)  # one line

Calling fit again on the same model erases the previous learning and trains from scratch.

Using an untrained model

If predict is used without calling fit, scikit-learn raises NotFittedError. Learned attributes (like coef_) also don't exist before fit:

m = LinearRegression()
print(hasattr(m, "coef_"))   # False
m.fit(X, y)
print(hasattr(m, "coef_"))   # True

That's why the trailing underscore convention is useful: everything ending in _ exists after training.

Practice Train and verify

Create a LinearRegression. Print hasattr(m, "coef_") before and after fit.

Starter code

model.py
from sklearn.linear_model import LinearRegression

X = [[1], [2], [3]]
y = [2, 4, 6]

# buraya yaz

Sample solution

model.py
from sklearn.linear_model import LinearRegression

X = [[1], [2], [3]]
y = [2, 4, 6]

m = LinearRegression()
print(hasattr(m, "coef_"))
m.fit(X, y)
print(hasattr(m, "coef_"))

Expected output

False
True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if <code>fit</code> is called again with new data on a trained model?

  • It errors
  • Nothing happens
  • The model is retrained from scratch on the new data only Correct answer
  • Old and new data are combined

Explanation: fit recomputes the parameters from scratch each time.

2 Create and train the model in one line.

Question
m = LinearRegression().____(X, y)
Answer
m = LinearRegression().fit(X, y)

Explanation: fit returns the object itself, so chaining is possible.

3 Match the situations.

Term Meaning
predict before fit NotFittedError
coef_ after fit Learned weight
return value of fit The model itself
second fit Training from scratch

All lessons in Beginner

13 Project: Classification

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