3. Supervised Learning: Classification
Logistic Regression & Probability Calibration
Logistic regression is the foundational algorithm for binary classification tasks. Despite its name, it is a classification algorithm rather than a regression tool. It works by computing a linear combination of input features, much like linear regression, and then passing that continuous score through a Sigmoid (logistic) activation function. The Sigmoid function maps any real-valued number into a range between 0 and 1, representing the probability that a given input instance belongs to the positive class (labeled as 1).
In a real-world scenario, predicting a hard binary class (0 or 1) using the .predict() method is often insufficient. For risk management and decision optimization, you should use .predict_proba(). This function outputs a probability distribution over all possible classes. Accessing raw probabilities enables developers and data scientists to adjust decision thresholds according to operational requirements, rather than settling for the default 0.5 threshold.
import numpy as np from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression # Create a mock binary dataset simulating customer churn X, y = make_classification(n_samples=100, n_features=4, n_classes=2, random_state=42) # Train a logistic regression model clf = LogisticRegression() clf.fit(X, y) # Predict class labels predictions = clf.predict(X[:5]) # Predict exact class probabilities probabilities = clf.predict_proba(X[:5]) print("Discrete Class Predictions:", predictions) print("Predicted Probabilities (Class 0 vs Class 1):\n", probabilities)
Decision Tree Mechanics: Splitting Criteria and Pruning
Decision Trees partition the feature space by making recursive binary splits. To select the best split at any node, the algorithm evaluates how much a split reduces impurity. The two primary mathematical criteria for evaluating purity are Gini Impurity and Entropy. Gini Impurity measures the likelihood of an element being incorrectly labeled if it were randomly classified according to the class distribution in the node. Entropy measures the level of disorder or information uncertainty. Both metrics seek to maximize information gain with each split.
Without constraints, Decision Trees will split nodes until every training sample is perfectly isolated, leading to severe overfitting. To limit this behavior, we apply pruning parameters during instantiation. Key parameters include max_depth (which limits the maximum levels of the tree), min_samples_split (the minimum number of samples needed to split a node), and min_samples_leaf (the minimum number of samples required to exist within a terminal leaf).
| Feature | Gini Impurity | Entropy |
|---|---|---|
| Formula | 1 - sum(p_i^2) | -sum(p_i * log2(p_i)) |
| Computation Cost | Low (simple multiplication) | High (logarithmic calculations) |
| Range | 0 to 0.5 (binary) | 0 to 1.0 (binary) |
import numpy as np from sklearn.datasets import make_classification from sklearn.tree import DecisionTreeClassifier # Generate synthetic data X, y = make_classification(n_samples=150, n_features=5, random_state=42) # Instantiate a tree using Entropy as splitting criteria with pruning constraints tree_model = DecisionTreeClassifier(criterion='entropy', max_depth=3, min_samples_leaf=5, random_state=42) tree_model.fit(X, y) # Display the depth and score of the pruned tree print("Pruned Tree Depth:", tree_model.get_depth()) print("Model Train Accuracy:", tree_model.score(X, y))
Establishing Baselines and Feature Importance Analysis
When initiating a machine learning workflow, building a simple baseline model is a critical best practice. A baseline model gives you a benchmark metric to surpass. Decision Trees make exceptional baselines because they require minimal preprocessing, can handle non-linear structures, and are highly interpretable.
Once a tree-based baseline is trained, you can inspect feature importances. Feature importance refers to a score assigned to input features based on how effective they were at reducing impurity (MDI - Mean Decrease in Impurity) across all tree splits. Features that lead to large reductions in impurity are placed higher up in the tree structures and receive a larger importance score. Evaluating these importances helps with feature selection and highlights irrelevant features that can be removed to reduce noise.
import numpy as np import pandas as pd from sklearn.datasets import make_classification from sklearn.tree import DecisionTreeClassifier # Generate fake dataset representing transaction characteristics X, y = make_classification(n_samples=200, n_features=5, random_state=42) feature_names = ['Amount', 'Frequency', 'RiskScore', 'LocationID', 'DeviceID'] # Train baseline decision tree baseline = DecisionTreeClassifier(max_depth=4, random_state=42) baseline.fit(X, y) # Extract and print feature importances in descending order importances = baseline.feature_importances_ importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': importances}) importance_df = importance_df.sort_values(by='Importance', ascending=False) print(importance_df)
Balancing Imbalanced Classes with Class Weights
In real-world applications like fraud detection or rare disease diagnosis, datasets are heavily imbalanced. For instance, only 1% of transactions may be fraudulent. Standard machine learning estimators seek to maximize overall accuracy, which means they can easily achieve 99% accuracy by simply predicting the majority class for all inputs.
To address this class imbalance without manually resampling the dataset, Scikit-learn estimators provide a class_weight parameter. Setting class_weight='balanced' automatically adjusts weights inversely proportional to class frequencies. During training, the loss function assigns higher penalties to misclassifications of minority class instances, forcing the decision boundary to accommodate the rarer class. This simple configuration ensures the model learns robust patterns from the minority class.
import numpy as np from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression # Create an imbalanced dataset: 90% negative, 10% positive X, y = make_classification(n_samples=300, n_features=4, weights=[0.9, 0.1], random_state=42) # Model trained with class weights to penalize minority class errors weighted_clf = LogisticRegression(class_weight='balanced', random_state=42) weighted_clf.fit(X, y) # Notice the automated internal class weights applied print("Target Class Distribution count:", np.bincount(y)) print("Model Intercept:", weighted_clf.intercept_) print("Model Classes:", weighted_clf.classes_)
Knowledge Check
Ready to test your understanding of 3. Supervised Learning: Classification?