Fitting Your First Scikit-learn Model
What you'll learn: How to train a machine learning model using .fit(), make predictions with .predict(), and understand what these results mean.
The Core Workflow
Training a scikit-learn model follows a simple three-step pattern that you'll use thousands of times in your ML career:
- Create an instance of your chosen model
- Fit it to your training data using
.fit(X_train, y_train) - Predict on new data using
.predict(X_test)
Think of .fit() as the "learning" phase—your model examines the patterns in your training features (X_train) and their corresponding labels (y_train), then adjusts its internal parameters to capture those relationships.
A Simple Example
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# Load data and split
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)
# Step 1: Create the model
model = LogisticRegression(max_iter=200)
# Step 2: Fit (train) the model
model.fit(X_train, y_train)
# Step 3: Make predictions
predictions = model.predict(X_test)
Interpreting Results
The predictions array contains your model's guesses for each test sample. You can compare these to y_test to see how well your model learned. For the iris dataset, predictions are class labels (0, 1, or 2 representing flower species).
The beauty of scikit-learn's API is its consistency—whether you're using LogisticRegression, a decision tree, or any other model, the pattern remains: create, fit, predict.
Key Takeaway: .fit() trains your model on data by finding patterns, .predict() applies those learned patterns to make guesses on new examples—this two-method workflow is the foundation of supervised learning in scikit-learn.