Linear Classification
Iris + logistic regression — the canonical classification pipeline
The template for every classification notebook in the course. If you can narrate this one cell by cell, you can narrate all of them.
The pipeline in one picture
load -> inspect -> plot -> select features -> split -> fit -> predict -> evaluate
Every subsequent notebook (k-NN, SVM, trees, ensembles) is this same skeleton with the model swapped.
Cell-by-cell
1. Imports and data
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris() # returns a dict-like Bunch
iris.keys()
Output: dict_keys(['data','target','frame','target_names','DESCR','feature_names','filename','data_module'])
What to say: load_iris() returns a Bunch, not an array. The two keys that matter are data (the feature matrix) and target (the labels). The others are metadata.
2. Extract and verify
features = iris['data'] # (150, 4)
labels = iris['target'] # (150,)
features.shape, labels.shape
# ((150, 4), (150,))
Why this is a graded step: the assignment rubric awards marks for verifying that the shapes are consistent — 150 rows in both, 4 columns of features. A mismatch means you paired the wrong arrays.
3. Inspect the label distribution
plt.hist(labels)
plt.xticks([0,1,2], iris.target_names)
plt.xlabel('Species label'); plt.ylabel('Count')
Three equal bars of 50. This is the check that tells you accuracy is a fair metric here — there is no class imbalance to correct for. On the diabetes dataset the same plot is 91.5/8.5 and accuracy becomes misleading; that contrast is worth stating.
4. Look at the metadata
iris.feature_names # ['sepal length (cm)', ..., 'petal width (cm)']
iris.target_names # array(['setosa','versicolor','virginica'])
The feature names are what make the plot axes readable, and they are what you cite when explaining why a split works.
5. Visualise before modelling
iris_plot = plt.scatter(features[:,0], features[:,1], c=labels)
plt.legend(iris_plot.legend_elements()[0], iris.target_names, title='Species')
Sepal length vs sepal width. Setosa is cleanly separated; versicolor and virginica overlap. That single observation predicts everything downstream: a linear model will get setosa perfect and make its errors between the other two.
6. Select two features
X = features[:, 0:2] # (150, 2)
Y = labels
Two features are chosen deliberately: with $d=2$ you can draw the decision boundary, which is the pedagogical point. A 4-D boundary cannot be plotted.
7. Split
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.25)
X_train.shape, X_test.shape # (112, 2), (38, 2)
Note there is no random_state in this notebook and no stratify — so the result is not reproducible and the class proportions are not guaranteed. That is exactly what the next notebook (model-evaluation) fixes, and what Assignment 2 explicitly requires.
8. Fit
from sklearn.linear_model import LogisticRegression
LR_model = LogisticRegression()
LR_model.fit(X_train, Y_train)
Y_pred = LR_model.predict(X_test)
Three lines, and the whole fit/predict contract of scikit-learn: the estimator learns parameters from (X_train, Y_train), then maps unseen X_test to predictions.
9. Draw the boundary
from sklearn.inspection import DecisionBoundaryDisplay
DecisionBoundaryDisplay.from_estimator(
LR_model, X_train[:, :2], response_method="predict",
cmap="RdBu_r", alpha=0.5)
plt.scatter(X_test[:,0], X_test[:,1], c=Y_test)
Two things to explain. (i) The grid for the boundary is built from X_train, not X_test — the boundary is a property of the model, not the test data. (ii) response_method="predict" draws hard regions; "predict_proba" would draw a smooth gradient instead. (iii) The points plotted are X_test: with a single linear boundary on two features, a straight line is all you will see.
10. Accuracy and confusion matrix
print('LR accuracy: ', 100*accuracy_score(Y_pred, Y_test))
# 100.0
print('LR:\n', confusion_matrix(Y_pred, Y_test))
# [[14 0]
# [ 0 24]]
Argument-order bug to notice: accuracy_score(Y_pred, Y_test) puts the predictions first. Accuracy is symmetric so it does not matter here, but roc_auc_score and classification_report are not symmetric — the convention is (y_true, y_pred).
The 2×2 matrix on 3-class data. Only 14+24 = 38 samples, and only two classes appear. The split happened to put no virginica in the test fold. That is the unstratified-split failure mode in the wild.
11. The TP/FP/FN/TN decomposition
conf = confusion_matrix(Y_pred, Y_test)
FP = conf.sum(axis=0) - np.diag(conf)
FN = conf.sum(axis=1) - np.diag(conf)
TP = np.diag(conf)
TN = conf.sum() - (FP + FN + TP)
F1 = (2*PPV*TPR) / (PPV+TPR) # -> array([1., 1.])
This block is the single most dangerous code in all nine notebooks. np.diag returns the diagonal in class order [class0, class1, ...]. The formula FP = colsum - diag is only correct if class 0 is the positive class. In binary problems where you care about class 1 — which is the case on the diabetes assignment — TP and TN are swapped and every derived metric is wrong while looking perfectly plausible. Always unpack with TN, FP, FN, TP = confusion_matrix(y_true, y_pred, labels=[0,1]).ravel().
12. Classification report
print(classification_report(Y_test, Y_pred, target_names=iris.target_names[:2]))
# precision recall f1-score support
# setosa 1.00 1.00 1.00 14
# versicolor 1.00 1.00 1.00 24
support is the number of true instances of that class in y_true — the first thing to check when a metric looks odd.
13. ROC and AUC
fpr, tpr, thresh = roc_curve(Y_test, Y_pred)
plt.plot(fpr, tpr)
roc_auc_score(Y_test, Y_pred) # 1.0
Explain this properly. roc_curve is being fed hard labels, not probabilities. With hard labels there are only three achievable points: (0,0), the operating point, and (1,1). The curve is a staircase through the model's single operating point, and the "AUC" reduces to a rescaled version of that one point. To get a genuine ROC you need LR_model.predict_proba(X_test)[:,1].
Likely question: "In this notebook, what does the ROC cell actually compute?" It computes a three-point staircase because roc_curve receives Y_pred, which are hard 0/1 labels from .predict(), not scores. A proper ROC requires a continuous confidence, so it should be roc_curve(Y_test, LR_model.predict_proba(X_test)[:,1]). The two curves can be plotted together as long as they are labelled — and the lesson is that the hard-label version is not "wrong", it is measuring only one threshold.
What the numbers mean together
| Quantity | Value | Reading |
|---|---|---|
| Accuracy | 1.00 | 38/38 correct on this split |
| Confusion matrix | [[14,0],[0,24]] | zero errors |
| Precision / recall | 1.00 / 1.00 | no false positives or negatives |
| AUC (hard labels) | 1.00 | equal to accuracy here, for the reason above |
Perfect accuracy on Iris with two features is expected — setosa is linearly separable and versicolor/virginica happen not to collide in this 38-sample fold. It is not evidence of a good model; it is evidence of an easy split. Rewriting the cell with test_size=0.9 would give a very different picture.





