Classification

Classification

Open In Colab

Linear Discriminant Analysis

import numpy as np
import matplotlib.pyplot as plt

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

# 1) Load Iris data
iris = load_iris()
X = iris.data
y = iris.target
target_names = iris.target_names

# 2) Train/test split (stratify keeps class proportions)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)

# 3) Fit LDA classifier
lda = LinearDiscriminantAnalysis()
lda.fit(X_train, y_train)

# 4) Evaluate
y_pred = lda.predict(X_test)
acc = accuracy_score(y_test, y_pred)
cm = confusion_matrix(y_test, y_pred)

print(f"Accuracy: {acc:.4f}\n")
print("Confusion matrix:\n", cm, "\n")

# 5) Project data to 2D using LDA for visualization
#    (Iris has 3 classes => at most 2 LDA components)
X_lda = lda.fit(X, y).transform(X)

plt.figure(figsize=(7, 5))
for cls in np.unique(y):
    plt.scatter(
        -X_lda[y == cls, 0],
        -X_lda[y == cls, 1],
        label=target_names[cls],
        alpha=0.8
    )

plt.title("Iris projected onto first 2 LDA components")
plt.xlabel("LD1")
plt.ylabel("LD2")
plt.legend()
plt.tight_layout()
plt.show()
Accuracy: 1.0000

Confusion matrix:
 [[12  0  0]
 [ 0 13  0]
 [ 0  0 13]] 

ROC curve

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer

# pip install uv && uv pip install ISLP
from ISLP import load_data

# 1) Load ISL Default dataset
df = load_data('Default')

# 2) Encode target (Yes/No -> 1/0)
df["default"] = df["default"].map({"Yes": 1, "No": 0})

# 3) Separate features and target
X = df[["balance", "income", "student"]]
y = df["default"]

# 4) One-hot encode the 'student' variable
preprocessor = ColumnTransformer(
    transformers=[
        ("cat", OneHotEncoder(drop="first"), ["student"])
    ],
    remainder="passthrough"
)

X = preprocessor.fit_transform(X)

# 5) Train/test split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42, stratify=y
)

# 6) Fit models
model1 = LogisticRegression(max_iter=1000)
model2 = LinearDiscriminantAnalysis()
model3 = GaussianNB()  # Naive Bayes
model4 = QuadraticDiscriminantAnalysis()  # QDA

model1.fit(X_train, y_train)
model2.fit(X_train, y_train)

# GaussianNB expects dense arrays (often); convert if needed
X_train_dense = X_train.toarray() if hasattr(X_train, "toarray") else X_train
X_test_dense  = X_test.toarray()  if hasattr(X_test, "toarray")  else X_test

model3.fit(X_train_dense, y_train)
model4.fit(X_train_dense, y_train)

# 7) Get predicted probabilities
y_prob1 = model1.predict_proba(X_test)[:, 1]
y_prob2 = model2.predict_proba(X_test)[:, 1]
y_prob3 = model3.predict_proba(X_test_dense)[:, 1]
y_prob4 = model4.predict_proba(X_test_dense)[:, 1]

# 8) Compute ROC curve + AUC
fpr1, tpr1, _ = roc_curve(y_test, y_prob1); roc_auc1 = auc(fpr1, tpr1)
fpr2, tpr2, _ = roc_curve(y_test, y_prob2); roc_auc2 = auc(fpr2, tpr2)
fpr3, tpr3, _ = roc_curve(y_test, y_prob3); roc_auc3 = auc(fpr3, tpr3)
fpr4, tpr4, _ = roc_curve(y_test, y_prob4); roc_auc4 = auc(fpr4, tpr4)

# 9) Plot ROC
plt.figure(figsize=(7, 5))
plt.plot(fpr1, tpr1, label=f"Logistic Regression (AUC = {roc_auc1:.3f})")
plt.plot(fpr2, tpr2, label=f"LDA (AUC = {roc_auc2:.3f})")
plt.plot(fpr3, tpr3, label=f"Naive Bayes (AUC = {roc_auc3:.3f})")
plt.plot(fpr4, tpr4, label=f"QDA (AUC = {roc_auc4:.3f})")
plt.plot([0, 1], [0, 1], linestyle="--", label="Chance")

plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("ROC Curve - ISL Default Data")
plt.legend()
plt.tight_layout()
plt.show()

print(f"Logistic Reg. AUC: {roc_auc1:.4f}")
print(f"LDA AUC:          {roc_auc2:.4f}")
print(f"Naive Bayes AUC:  {roc_auc3:.4f}")
print(f"QDA AUC:          {roc_auc4:.4f}")

Logistic Reg. AUC: 0.9511
LDA AUC:          0.9508
Naive Bayes AUC:  0.9440
QDA AUC:          0.9508
import numpy as np
from sklearn.metrics import roc_curve

def best_threshold_youden(y_true, y_prob, decimals=4):
    fpr, tpr, thr = roc_curve(y_true, y_prob)
    j = tpr - fpr
    idx = np.argmax(j)

    return {
        "threshold": round(float(thr[idx]), decimals),
        "sensitivity": round(float(tpr[idx]), decimals),
        "specificity": round(float(1 - fpr[idx]), decimals),
        "youden_J": round(float(j[idx]), decimals)
    }

best1 = best_threshold_youden(y_test, y_prob1)  # Logistic
best2 = best_threshold_youden(y_test, y_prob2)  # LDA
best3 = best_threshold_youden(y_test, y_prob3)  # NB
best4 = best_threshold_youden(y_test, y_prob4)  # QDA

print("Logistic:", best1)
print("LDA:     ", best2)
print("NB:      ", best3)
print("QDA:     ", best4)
Logistic: {'threshold': 0.0512, 'sensitivity': 0.87, 'specificity': 0.9021, 'youden_J': 0.7721}
LDA:      {'threshold': 0.0586, 'sensitivity': 0.87, 'specificity': 0.8993, 'youden_J': 0.7693}
NB:       {'threshold': 0.0437, 'sensitivity': 0.87, 'specificity': 0.8714, 'youden_J': 0.7414}
QDA:      {'threshold': 0.0597, 'sensitivity': 0.87, 'specificity': 0.8962, 'youden_J': 0.7662}