How to Use Scikit-Learn for Classification: A Practical Tutorial

Scikit-learn is Python’s most widely used machine learning library, and classification is its most common task. This tutorial builds a working classifier step by step, using the built-in Iris dataset so you can run everything immediately.

1. Install and Import

Install it with pip install scikit-learn, then import the pieces you need:

  • train_test_split — splits data into training and test sets
  • StandardScaler — normalizes feature values
  • RandomForestClassifier — the model itself

Article illustration

2. Prepare the Data

Load a dataset, separate features (X) from labels (y), then split both into training and test sets with a 20% test size. Use stratify=y so each class appears proportionally in both sets. Scaling with StandardScaler keeps features comparable and often improves results.

Why Split First?

Fitting the scaler on test data leaks information and inflates your score. Fit on training data only, then transform the test set.

3. Train the Model

Instantiate the classifier, call fit(X_train, y_train), then call predict(X_test). That’s the whole training loop — scikit-learn handles the math internally.

4. Evaluate Results

Compare predictions against true labels using accuracy_score or classification_report. The report shows precision, recall, and F1 per class, which matters far more than raw accuracy on imbalanced data.

Conclusion

Scikit-learn’s consistent fit-predict-evaluate pattern works across dozens of algorithms. Swap RandomForestClassifier for LogisticRegression or SVC and the rest of your code stays identical.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *