Model training
- Machine Learning course
- Beginner
- Lesson 43/112
- 5 min
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 lineCalling 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_")) # TrueThat'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
from sklearn.linear_model import LinearRegression
X = [[1], [2], [3]]
y = [2, 4, 6]
# buraya yazSample solution
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.
m = LinearRegression().____(X, y)
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 |