Skip to content
v0.1.3latest release121 skills4 categories6 sub-categories247 tested scripts397 reference docsContact us

cluster_profile.py

Helper script for kmeans-cluster-count-finder · 142 lines

AI & Machine Learning / Classical Machine Learningv1.0.0Updated OCT 25 20263 references2 scripts
scripts/cluster_profile.py
#!/usr/bin/env python3
"""Profile clusters so they can be named, checked and acted on.

Input: a CSV with a cluster-label column (from any algorithm; -1 is treated as noise) plus the
features. For each cluster:
  size and share
  numeric features: mean, the standardised difference from the rest of the data
                    (mean_in - mean_out) / pooled_sd, and the most distinctive features ranked by |d|
  categorical features: the level most over-represented relative to the population (lift)
  outcome (--outcome): mean of a business outcome per cluster (churn rate, spend), to check that
                    segments actually behave differently
Warnings: tiny clusters (< --min-share), clusters with no feature |d| >= 0.5 (hard to tell apart), and an
outcome that barely differs across clusters.

Usage:
    python cluster_profile.py segments.csv --label cluster
    python cluster_profile.py segments.csv --label cluster --outcome churned --drop customer_id --top 4
    python cluster_profile.py segments.csv --label cluster --json

Exit codes: 0 profiled, 2 usage or read error.
"""

import argparse
import csv
import json
import math
import sys
from collections import Counter, defaultdict

MISSING = {"", "na", "n/a", "nan", "null", "none", "?"}


def num(v):
    try:
        x = float(v)
        return x if math.isfinite(x) else None
    except (TypeError, ValueError):
        return None


def mean_sd(xs):
    if not xs:
        return None, None
    m = sum(xs) / len(xs)
    return m, math.sqrt(sum((x - m) ** 2 for x in xs) / max(1, len(xs) - 1))


def main():
    ap = argparse.ArgumentParser(description="Profile clusters for naming and validation.", epilog=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("csv")
    ap.add_argument("--label", required=True, help="cluster label column")
    ap.add_argument("--outcome", help="business outcome column to compare across clusters")
    ap.add_argument("--drop", nargs="*", default=[])
    ap.add_argument("--top", type=int, default=3)
    ap.add_argument("--min-share", type=float, default=0.02)
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()
    try:
        with (sys.stdin if a.csv == "-" else open(a.csv, newline="", encoding="utf-8-sig")) as fh:
            rd = csv.DictReader(fh)
            header = rd.fieldnames or []
            rows = list(rd)
        for c in (a.label, a.outcome):
            if c and c not in header:
                raise ValueError(f"column {c!r} not found")
    except (OSError, ValueError) as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    feats = [c for c in header if c not in (a.label, a.outcome) and c not in a.drop]
    numeric = [c for c in feats if all(num(r[c]) is not None for r in rows if (r[c] or "").strip().lower() not in MISSING)]
    categorical = [c for c in feats if c not in numeric and len({r[c] for r in rows}) <= 50]
    groups = defaultdict(list)
    for r in rows:
        groups[r[a.label].strip()].append(r)
    n = len(rows)
    out = {"rows": n, "clusters": []}
    pop_cat = {c: Counter(r[c] for r in rows) for c in categorical}
    outcome_means = []
    for lab in sorted(groups, key=lambda l: (l == "-1", -len(groups[l]))):
        g = groups[lab]
        rest = [r for r in rows if r[a.label].strip() != lab]
        prof = {"label": lab, "size": len(g), "share": len(g) / n, "noise": lab == "-1", "numeric": [], "categorical": []}
        for c in numeric:
            xin = [num(r[c]) for r in g if num(r[c]) is not None]
            xout = [num(r[c]) for r in rest if num(r[c]) is not None]
            mi, si = mean_sd(xin)
            mo, so = mean_sd(xout)
            if mi is None or mo is None:
                continue
            pooled = math.sqrt(((len(xin) - 1) * si ** 2 + (len(xout) - 1) * so ** 2) / max(1, len(xin) + len(xout) - 2)) or 1e-12
            prof["numeric"].append({"feature": c, "mean": mi, "rest_mean": mo, "d": (mi - mo) / pooled})
        prof["numeric"].sort(key=lambda e: -abs(e["d"]))
        for c in categorical:
            cnt = Counter(r[c] for r in g)
            best = max(cnt, key=lambda v: (cnt[v] / len(g)) / (pop_cat[c][v] / n))
            prof["categorical"].append({"feature": c, "level": best, "share_in": cnt[best] / len(g),
                                        "share_pop": pop_cat[c][best] / n,
                                        "lift": (cnt[best] / len(g)) / (pop_cat[c][best] / n)})
        prof["categorical"].sort(key=lambda e: -e["lift"])
        if a.outcome:
            ys = [num(r[a.outcome]) for r in g if num(r[a.outcome]) is not None]
            prof["outcome_mean"] = sum(ys) / len(ys) if ys else None
            if ys and lab != "-1":
                outcome_means.append(prof["outcome_mean"])
        warn = []
        if prof["share"] < a.min_share and lab != "-1":
            warn.append(f"tiny cluster ({prof['share']:.1%})")
        if prof["numeric"] and abs(prof["numeric"][0]["d"]) < 0.5 and not any(e["lift"] > 1.5 for e in prof["categorical"]):
            warn.append("no feature separates it clearly (max |d| < 0.5): hard to name or act on")
        prof["warnings"] = warn
        out["clusters"].append(prof)
    if a.outcome and len(outcome_means) >= 2:
        lo, hi = min(outcome_means), max(outcome_means)
        out["outcome_spread"] = {"min": lo, "max": hi, "ratio": hi / lo if lo else None}
    if a.json:
        print(json.dumps(out, indent=2))
        return 0
    print(f"{n} rows, {len(groups)} clusters; {len(numeric)} numeric, {len(categorical)} categorical features")
    for p in out["clusters"]:
        tag = " (noise)" if p["noise"] else ""
        oc = f", {a.outcome} mean {p['outcome_mean']:.3g}" if a.outcome and p.get("outcome_mean") is not None else ""
        print(f"\ncluster {p['label']}{tag}: {p['size']} rows ({p['share']:.1%}){oc}")
        for e in p["numeric"][:a.top]:
            arrow = "higher" if e["d"] > 0 else "lower"
            print(f"  {e['feature']:<22} mean {e['mean']:.4g} vs {e['rest_mean']:.4g} elsewhere  (d {e['d']:+.2f}, {arrow})")
        for e in p["categorical"][:2]:
            if e["lift"] > 1.2:
                print(f"  {e['feature']}={e['level']:<16} {e['share_in']:.0%} vs {e['share_pop']:.0%} overall (lift {e['lift']:.1f}x)")
        for w in p["warnings"]:
            print(f"  warning: {w}")
    if "outcome_spread" in out:
        sp = out["outcome_spread"]
        print(f"\n{a.outcome} ranges {sp['min']:.3g} .. {sp['max']:.3g} across clusters" + (
            "; segments barely differ on the outcome - check whether they need different actions"
            if sp["ratio"] and sp["ratio"] < 1.2 else ""))
    return 0


if __name__ == "__main__":
    sys.exit(main())
More in Classical Machine Learning

anomaly-detection-model-builder

Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.

catboost-model-builder

Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set).

categorical-encoding-selector

Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC).

classification-model-selector

Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.

clustering-algorithm-selector

Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.

collaborative-filtering-implementer

Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.