StudyAIStudyAI
Pro
Lesson 611 min

Your First ML Script

Train and evaluate a model in a few lines with scikit-learn.

What you will learn
  • The fit / predict pattern
  • Splitting data before training
  • Reading an accuracy score

Explanation

scikit-learn is the friendliest way to do classic ML. Every model follows the same pattern: create it, .fit(X, y) to train, then .predict(...) on new data.

Always split your data into train and test sets first, so you measure performance on data the model has not seen.

The example trains a simple classifier and prints its accuracy on held-out data — your first real model.

Code Example

python
1
from sklearn.linear_model import LogisticRegression
2
from sklearn.model_selection import train_test_split
3
 
4
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2)
5
model = LogisticRegression().fit(Xtr, ytr)
6
print('Test accuracy:', model.score(Xte, yte))
Real-world use

This exact fit/predict pattern scales from a 10-line demo to production fraud-detection systems.

Common mistakes
  • Reporting accuracy on the training data instead of the held-out test set.
Practice

Use scikit-learn to train a LogisticRegression on any small dataset and print the test accuracy.

Knowledge check
0/2 answered

1. Why split data into train and test sets?

2. In scikit-learn, what does .fit(X, y) do?

Answer all questions to check.