Build a Baseline Classifier and Read Its Confusion Matrix
Compare a trainable classifier with a most-frequent baseline using the same held-out flower examples and interpret each cell in the resulting confusion matrices.
Difficulty Beginner
What you will build
You will split a public teaching dataset into training and test partitions, fit two models and compare their mistakes. The baseline answers a practical question: would a trivial decision rule perform nearly as well? The result describes these examples and this split. A real deployment needs a test set that resembles its intended use, including rare but important cases.
Prerequisites
Use Python 3 with venv and pip on a Linux workstation. A CPU is sufficient. Internet access is needed for the initial package download. The Iris dataset is bundled with scikit-learn.
Create an environment
python3 -m venv .venv
. .venv/bin/activate
python -m pip install scikit-learn
python -m pip freeze > requirements-lock.txt
Create this environment in a new project directory. The lock record helps someone identify the versions used for your result. If venv creation reports that ensurepip is missing, install your distribution's Python venv package.
Fit and compare
Save this as baseline.py and run python baseline.py.
from sklearn.datasets import load_iris
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=17
)
models = {
"Most frequent": DummyClassifier(strategy="most_frequent"),
"Logistic regression": make_pipeline(
StandardScaler(), LogisticRegression(max_iter=500)
),
}
for name, model in models.items():
model.fit(X_train, y_train)
print(name)
print(confusion_matrix(y_test, model.predict(X_test), labels=[0, 1, 2]))
Stratify preserves approximate class proportions. The pipeline learns the scaling parameters from training data during fit. In the matrix, each row is an actual class and each column is a predicted class. The diagonal counts correct predictions. Each matrix should sum to 38. The dummy classifier uses a single prediction class, so only one column is populated.
Troubleshooting and practice
If import fails, run python -m pip show scikit-learn inside the activated environment. If all predictions fall into one column for the trainable model, review your training labels and check which model produced the output. Calculate per-class recall by dividing each diagonal entry by its row total. Repeat with a different predeclared seed and compare the results. Avoid picking the seed that gives the best score or presenting a small benchmark as proof of suitability for consequential decisions.