Two common machine learning settings are supervised (you provide labeled outcomes) and unsupervised (the algorithm discovers structure on its own). Within supervised learning, classification predicts discrete categories (will this customer churn, yes or no?) while regression predicts continuous values. Clustering, a common unsupervised technique, groups similar observations without predefined labels. This introductory guide covers selected methods and evaluation questions, and includes a worked comparison on two public datasets with the code, so you can re-run every number.
Explore classification inputs or explore clustering inputs.
Supervised vs. Unsupervised at a Glance
Supervised: You have a target variable (label). The model learns to map inputs to that target. Use cases: churn prediction, fraud detection, demand forecasting, credit scoring.
Unsupervised: No target variable. The model finds patterns, groups, or anomalies in the data. Use cases: customer segmentation, anomaly detection, topic discovery, dimensionality reduction.
Classification and Related Anomaly Methods
Classification algorithms assign observations to discrete categories. The table below introduces candidate methods and their limitations. Anomaly detectors listed alongside classifiers can be used when labels are scarce; they are not interchangeable with supervised classifiers.
| Method | Type | Suited To | Limitations | Typical Use Case |
|---|---|---|---|---|
| XGBoost | Gradient boosting | Tabular data, competitions, mixed feature types | Can overfit, especially on small data; many hyperparameters to tune (see the XGBoost tuning notes) | Churn prediction, credit scoring |
| Random Forest | Bagging ensemble | Robust baseline, feature importance, noisy data | Slow on very high-dimensional data; large model size | Fraud detection, lead scoring |
| LightGBM | Gradient boosting | Large datasets, fast training, categorical features | Leaf-wise growth can overfit small data | Real-time bidding, click prediction |
| CatBoost | Gradient boosting | Native categorical handling, minimal tuning | Slower training than LightGBM; less community support | E-commerce recommendations, marketing mix |
| AdaBoost | Boosting ensemble | Simple boosting baseline, binary classification | Sensitive to noisy data and outliers | Spam detection, sentiment classification |
| SVM | Kernel-based | High-dimensional, clear margin separation | Kernel SVM training time grows fast with row count (scikit-learn's libsvm-based solver: between O(features × n²) and O(features × n³), per its docs); linear SVM solvers scale much better; kernel choice matters | Text classification, image recognition |
| Naive Bayes | Probabilistic | Text data, fast inference, small training sets | Assumes conditional independence of features given the class | Email filtering, document categorization |
| Logistic Regression | Linear | Interpretable coefficients, probability outputs | Cannot capture nonlinear relationships without engineering | Risk scoring, A/B test analysis |
| Decision Trees | Tree-based | Interpretability, mixed types, no scaling needed | High variance; overfits without pruning | Customer segmentation rules, triage logic |
| LDA | Linear | Dimensionality reduction + classification combined | Assumes Gaussian distributions, equal covariance | Multi-class product categorization |
| Neural Networks | Deep learning | Complex patterns, images, text, sequences | Needs large data; black box; expensive to train | Image tagging, NLP, time series |
| One-Class SVM | Anomaly detection | Novelty detection with only normal examples | Hard to tune nu parameter; sensitive to scaling | Fraud detection, defect screening |
| Isolation Forest | Anomaly detection | Fast anomaly detection, high-dimensional data | Scores not true probabilities; struggles with local anomalies | Transaction monitoring, sensor anomalies |
The strengths and limits in this table are short summaries, not measured results. Where a row names a cost or a risk, the linked library documentation is the basis; the rest are general rules of thumb to test on your own data.
When to Pick Which Classifier
Compare a simple baseline such as Logistic Regression with candidates such as Random Forest, XGBoost, or LightGBM. Choose the metric and evaluation split for your task, and inspect each implementation's feature-type and missing-value requirements. No model family is guaranteed to lead on your data.
For anomaly detection: where labeled fraud/defect examples are scarce, Isolation Forest and One-Class SVM learn what "normal" looks like and flag deviations, avoiding the need for balanced labeled data.
Clustering Methods
Clustering groups observations by similarity without requiring labels. The right algorithm depends on cluster shape, dataset size, and whether you know the number of groups in advance.
| Method | Cluster Shape | Needs K? | Scale (scikit-learn guide) | Suited To |
|---|---|---|---|---|
| K-Means | Spherical / convex | Yes | Very large n with the MiniBatch variant | Customer segmentation, RFM tiers |
| DBSCAN | Arbitrary shape | No | Very large n, medium number of clusters | Geographic clustering, noise detection |
| Hierarchical | Any (via linkage) | No (cut dendrogram) | Large n and number of clusters; storing all pairwise distances or a full dendrogram adds memory cost | Taxonomy building, gene expression |
| Spectral | Non-convex, graph-based | Yes | Medium n, small number of clusters | Image segmentation, community detection |
| Gaussian Mixture | Elliptical | Yes (or BIC) | Listed as not scalable | Soft assignments, overlapping segments |
The scale column quotes the overview table in the scikit-learn clustering guide. It describes that library's implementations; it is not a fixed row-count limit. Memory, the number of features and the distance measure all change what is practical.
When to Pick Which Clustering Method
K-Means is a common starting point: fast and easy to explain. Two common aids for choosing K are the elbow method (plot the within-cluster sum of squares, called inertia, against K and look for the bend) and the silhouette score (Rousseeuw, 1987; see the scikit-learn description). Both are heuristics, and they can disagree: in the worked comparison below they point to different K. Switch to DBSCAN when clusters have irregular shapes or you need to identify noise points (outliers that belong to no cluster). Use Hierarchical Clustering when you want to explore cluster structure at multiple granularity levels via dendrograms. Choose Gaussian Mixture Models when observations can belong to multiple clusters with varying probability (soft assignment). Spectral Clustering can suit graph-structured data or clusters that are connected but not compact.
Ensemble Methods & Interpretability
Ensembles combine multiple models to improve accuracy and stability. Interpretability tools explain what those models learned. Neither one guarantees a better or more trusted model. An ensemble has to beat a simpler model on held-out data, and an explanation is useful only after the people who rely on the model have reviewed it.
| Method | Category | What It Does | When to Use |
|---|---|---|---|
| Voting Ensemble | Ensemble | Combines predictions from multiple models via majority vote or averaging | When diverse base models each do reasonably well; check the gain on held-out data |
| Stacking | Ensemble | Trains a meta-model on base model outputs | When base models capture different patterns and you can afford the extra complexity |
| SHAP | Interpretability | Game-theoretic feature attribution for any model | Explaining individual predictions; documenting model behaviour for review |
| LIME | Interpretability | Local surrogate models for per-prediction explanations | Per-prediction explanations; check that they are stable across reruns |
| Feature Importance | Interpretability | Ranks features by contribution to model accuracy | Feature selection, understanding key drivers |
| Cross-Validation | Evaluation | Estimates model performance on unseen data | Model selection, hyperparameter tuning, avoiding overfit |
Checking What a Model Learned
Use SHAP or LIME to investigate what a fitted model uses, while checking explanation stability. Feature attribution does not establish causation or compliance. Keep preprocessing and feature selection inside training folds. Choose cross-validation or a separate test period to respect time order, repeated customers, and the intended use.
Voting ensembles combine model predictions. Stacking trains a second model on base-model predictions, which should be produced without training on the same evaluation observations. Compare the added complexity with any measured improvement; an ensemble does not guarantee a gain.
Worked Comparison on Public Data
Here is a small, reproducible comparison you can run in a few seconds. It uses two datasets that ship with scikit-learn, so there is nothing to download.
- Classification: the Breast Cancer Wisconsin (Diagnostic) data, 569 rows, 30 numeric features, 2 classes (a copy of the UCI dataset).
- Clustering: the iris data, 150 flowers, 4 measurements, 3 species. We hide the species from the clustering and use it only to score the result afterwards.
Evaluation setup. Each classifier is scored with 5-fold stratified cross-validation (the data is split into 5 parts with the same class mix; each part is held out once while the model trains on the other 4). Scaling sits inside the pipeline, so it is learned on the training folds only. We report accuracy (share of rows labelled correctly) and ROC AUC (how well the model ranks positive rows above negative ones; 1.0 is perfect, 0.5 is chance). Default settings are used throughout; nothing was tuned.
from sklearn.datasets import load_breast_cancer, load_iris
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, adjusted_rand_score
# Part 1: classification
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
models = {
"Logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000)),
"Random forest": RandomForestClassifier(n_estimators=300, random_state=0),
"Gradient boosting (HistGB)": HistGradientBoostingClassifier(random_state=0),
"SVM (RBF kernel)": make_pipeline(StandardScaler(), SVC(random_state=0)),
"Gaussian naive Bayes": GaussianNB(),
}
for name, m in models.items():
r = cross_validate(m, X, y, cv=cv, scoring=["accuracy", "roc_auc"])
acc, auc = r["test_accuracy"], r["test_roc_auc"]
print(f"{name:28s} acc {acc.mean():.3f} (sd {acc.std():.3f}) AUC {auc.mean():.3f} (sd {auc.std():.3f})")
# Part 2: clustering (species hidden)
Xi, yi = load_iris(return_X_y=True)
Xs = StandardScaler().fit_transform(Xi)
for k in range(2, 7):
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(Xs)
print(f"K={k} inertia {km.inertia_:7.1f} silhouette {silhouette_score(Xs, km.labels_):.3f} "
f"ARI vs species {adjusted_rand_score(yi, km.labels_):.3f}")
Run with Python 3, scikit-learn 1.8.0 and NumPy 2.4.0 on 2026-11-02. Other versions can shift the last digit.
Classification results (5-fold cross-validation)
| Model | Mean accuracy | Fold SD | Mean ROC AUC | Fold SD |
|---|---|---|---|---|
| Logistic regression (scaled) | 0.979 | 0.014 | 0.995 | 0.006 |
| SVM, RBF kernel (scaled) | 0.977 | 0.007 | 0.996 | 0.005 |
| Gradient boosting (HistGradientBoosting) | 0.970 | 0.009 | 0.994 | 0.004 |
| Random forest (300 trees) | 0.958 | 0.017 | 0.992 | 0.007 |
| Gaussian naive Bayes | 0.939 | 0.020 | 0.989 | 0.006 |
How to read it:
- The simple baseline was not beaten. Plain logistic regression had the highest mean accuracy (0.979). The SVM was within 0.002, and gradient boosting within 0.009. These gaps are smaller than the spread between folds (fold SD 0.007 to 0.020), so on this data the top three are hard to tell apart.
- Naive Bayes was lowest on accuracy (0.939) but still ranked rows well (AUC 0.989). Its independence assumption is a poor fit for features that are strongly related, such as a tumour's radius, perimeter and area.
- This is one small, clean dataset. It says nothing general about which family wins. It shows why you run the baseline first: a more complex model has to earn its place on your own data and metric.
Clustering results (K-Means on scaled iris data)
| K | Inertia | Drop from previous K | Silhouette | Agreement with species (ARI) |
|---|---|---|---|---|
| 2 | 222.4 | - | 0.582 | 0.568 |
| 3 | 139.8 | 82.6 | 0.460 | 0.620 |
| 4 | 114.1 | 25.7 | 0.387 | 0.473 |
| 5 | 90.8 | 23.3 | 0.346 | 0.420 |
| 6 | 80.0 | 10.8 | 0.326 | 0.356 |
Inertia is the within-cluster sum of squared distances (lower means tighter clusters; it generally falls as K grows). The drop column is simple subtraction of the printed inertia values. ARI, the adjusted Rand index, scores agreement with the hidden species: 1 is a perfect match, about 0 is chance.
- The elbow points to K=3. Going from 2 to 3 clusters cuts inertia by 82.6; each step after that cuts it by 25.7 or less.
- The silhouette score points to K=2 (0.582, the highest). Two of the three species overlap in these measurements, so a two-group split is the most cleanly separated one.
- The real species count is 3, and K=3 matches it most closely (ARI 0.620). Even then the match is partial, because K-Means cannot fully separate the two overlapping species.
The lesson: the elbow and the silhouette score are aids, not answers. Check the candidate groupings against what they will be used for before you pick K.
Decision Guide: Choosing the Right Method
Step 1: Do you have a target variable (label)?
Yes → Supervised learning. Go to Step 2.
No → Unsupervised learning. Go to Step 3.
Step 2 (Supervised): Is the target categorical or continuous?
Categorical → Classification. Compare a simple classifier with suitable alternatives using the same evaluation design. Consider Logistic Regression, tree ensembles, SVM or Naive Bayes according to feature types, assumptions and resource needs.
Continuous → Regression. See our Regression Analysis guide for Linear, Ridge, Lasso, and Elastic Net methods.
Step 3 (Unsupervised): What structure are you looking for?
Discrete groups → Clustering. Start with K-Means. Use DBSCAN if clusters have irregular shapes or you need noise detection. Use Gaussian Mixture for soft/overlapping assignments.
Anomalies → Anomaly Detection. Isolation Forest is a common first choice for unlabeled anomaly detection. Use One-Class SVM when you have clean "normal" training data only.
Reduced dimensions → Dimensionality Reduction. See the Related Methods section below for PCA, t-SNE, and UMAP.
Step 4: What evaluation and computing constraints apply?
Sample size alone does not choose a model. Consider the number and type of features, class balance, repeated observations, time order, memory and prediction latency. Compare suitable candidates without assuming a universal row-count cutoff.
Related Methods: Dimensionality Reduction
These methods reduce high-dimensional data to 2-3 dimensions for visualization, or to fewer features for downstream modeling. They are often used as preprocessing before clustering or classification.
| Method | Preserves | Speed | Suited To |
|---|---|---|---|
| PCA | Global variance | Fast | Feature reduction, denoising, preprocessing |
| t-SNE | Local neighborhoods | Slow; the exact method handles thousands of rows, Barnes-Hut hundreds of thousands (scikit-learn docs) | 2D visualization of clusters |
| UMAP | Local + some global | Moderate | Scalable visualization, embedding for ML |
| Autoencoders | Learned nonlinear features | Slower to train; often run on a GPU | Anomaly detection, feature learning |
Use PCA as a first pass to reduce correlated features. It is fast, deterministic, and works well as input to K-Means or classification models. Use t-SNE or UMAP for exploratory visualization. Separation in these projections does not prove that natural clusters exist. Autoencoders learn nonlinear compressed representations and double as anomaly detectors by flagging observations with high reconstruction error.
For a deep comparison, see t-SNE vs PCA vs UMAP: Which Reveals True Clusters and UMAP vs t-SNE: Speed, Scale, and Structure.
Sources
- scikit-learn developers. Support Vector Machines: Complexity. scikit-learn user guide.
- scikit-learn developers. Clustering (overview table and silhouette coefficient). scikit-learn user guide.
- scikit-learn developers. Manifold learning: t-SNE. scikit-learn user guide.
- Chen, T. and Guestrin, C. (2016). XGBoost: A Scalable Tree Boosting System. KDD 2016 (arXiv:1603.02754).
- XGBoost developers. Notes on Parameter Tuning (controlling overfitting).
- Rousseeuw, P. J. (1987). Silhouettes: a graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53-65.
- Breast Cancer Wisconsin (Diagnostic) data: UCI Machine Learning Repository; iris data: scikit-learn load_iris.
Your turn
Bring your own data and the question you actually need answered.
MCP AnalyticsData science by email Send us your data and your question, and we will reply. ds@mcpanalytics.ai
Frequently Asked Questions
Which ML method should I try first for a business classification problem?
Start with a simple baseline and compare suitable candidates on your metric and evaluation design. In the worked comparison on this page, plain logistic regression scored as well as the tree ensembles. Check feature encoding, missing-value handling and calibration where relevant. Complexity and model family do not establish which model will perform well on your data.
How is clustering different from classification?
Classification requires labeled data. You tell the model which category each observation belongs to, and it learns to predict categories for new data. Clustering has no labels; the algorithm discovers groups based on similarity. Classification answers "which known group?" while clustering answers "what groups exist?"
When should I use an ensemble instead of a single model?
Consider an ensemble when combining models gives a useful improvement on separate evaluation data. Voting combines predictions; stacking learns a combination using a second model. Measure any gain against added training, prediction and maintenance costs.
Do I need to understand SHAP and LIME for every ML project?
Use explanation methods when you need to understand the model's predictions. SHAP provides feature attributions and LIME fits local surrogate explanations. Inspect their assumptions and stability; neither by itself establishes that a model is accurate, causal or suitable for a consequential decision.
Machine Learning for Business Decisions
Classification and clustering are used for questions such as which customers may churn and which segments behave alike. On MCP Analytics you upload a CSV and tested statistical methods run on it; the same data gives the same numbers. See how these methods apply to business data:
- Marketing Analytics, Use classification to predict customer behavior and clustering to discover audience segments for targeted campaigns.
- Revenue Forecasting, Combine ML feature engineering with time series methods, and compare the forecasts on held-out periods.