clustrust 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
clustrust/__init__.py ADDED
File without changes
clustrust/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from clustrust.gui.app import main
2
+
3
+ main()
File without changes
@@ -0,0 +1,17 @@
1
+ """Do different algorithms find the same groups?"""
2
+ from itertools import combinations
3
+ import pandas as pd
4
+ from sklearn.metrics import adjusted_rand_score
5
+
6
+ from clustrust.core.algorithms import get_labels, ALGORITHMS, SEED
7
+
8
+
9
+ def agreement(X, k: int, algorithms=ALGORITHMS, seed: int = SEED) -> pd.DataFrame:
10
+ """Adjusted Rand index between every pair of algorithms at a given k.
11
+ Near 1 = same groups. Low = the groups depend on the method."""
12
+ algos = list(algorithms)
13
+ labels = {a: get_labels(a, X, k, seed) for a in algos}
14
+ M = pd.DataFrame(1.0, index=algos, columns=algos)
15
+ for a, b in combinations(algos, 2):
16
+ M.loc[a, b] = M.loc[b, a] = adjusted_rand_score(labels[a], labels[b])
17
+ return M
@@ -0,0 +1,19 @@
1
+ """Clustering algorithms behind one common function."""
2
+ import numpy as np
3
+ from sklearn.cluster import KMeans, AgglomerativeClustering
4
+ from sklearn.mixture import GaussianMixture
5
+
6
+ SEED = 42 # one global seed used for every random step
7
+
8
+ ALGORITHMS = ("kmeans", "agglomerative", "gmm")
9
+
10
+
11
+ def get_labels(name: str, X: np.ndarray, k: int, seed: int = SEED) -> np.ndarray:
12
+ """Run one algorithm with k clusters and return the group of each row."""
13
+ if name == "kmeans":
14
+ return KMeans(n_clusters=k, n_init=10, random_state=seed).fit_predict(X)
15
+ if name == "agglomerative":
16
+ return AgglomerativeClustering(n_clusters=k).fit_predict(X)
17
+ if name == "gmm":
18
+ return GaussianMixture(n_components=k, random_state=seed).fit(X).predict(X)
19
+ raise ValueError(f"Unknown algorithm: {name}")
@@ -0,0 +1,70 @@
1
+ """Judge every index against structureless null data."""
2
+ import numpy as np
3
+ import pandas as pd
4
+ from joblib import Parallel, delayed
5
+
6
+ from clustrust.core.algorithms import ALGORITHMS, SEED
7
+ from clustrust.core.runner import sweep
8
+ from clustrust.core.null import NULLS
9
+
10
+ INDEX_COLS = ["silhouette", "calinski_harabasz", "davies_bouldin"]
11
+
12
+
13
+ def _null_scores(X, null_name, child_seed, algorithms, k_range, seed):
14
+ rng = np.random.default_rng(child_seed)
15
+ return sweep(NULLS[null_name](X, rng), algorithms, k_range, seed)
16
+
17
+
18
+ def _z_table(real: pd.DataFrame, nulls: pd.DataFrame) -> pd.DataFrame:
19
+ keys = ["algorithm", "k"]
20
+ mean = nulls.groupby(keys)[INDEX_COLS].mean().add_suffix("_null_mean").reset_index()
21
+ std = nulls.groupby(keys)[INDEX_COLS].std().add_suffix("_null_std").reset_index()
22
+ out = real.merge(mean, on=keys).merge(std, on=keys)
23
+ for c in INDEX_COLS:
24
+ z = (out[c] - out[c + "_null_mean"]) / out[c + "_null_std"].replace(0, np.nan)
25
+ out[c + "_z"] = -z if c == "davies_bouldin" else z # flipped: higher is always better
26
+ return out
27
+
28
+
29
+ def calibrated_sweep(X, algorithms=ALGORITHMS, k_range=range(2, 9), n_null: int = 20,
30
+ seed: int = SEED, null: str = "gaussian", n_jobs: int = 1) -> pd.DataFrame:
31
+ """Real scores plus a z-score for each index against structureless null datasets.
32
+
33
+ null: 'gaussian', 'pca_uniform' or 'both'. With 'both', each z-score is the smaller of the
34
+ two, so a result must beat both nulls. (The *_null_mean and *_null_std columns then
35
+ describe the first null only.) n_jobs > 1 runs the null datasets in parallel.
36
+ """
37
+ names = ["gaussian", "pca_uniform"] if null == "both" else [null]
38
+ for n in names:
39
+ if n not in NULLS:
40
+ raise ValueError(f"Unknown null model: {n}")
41
+ real = sweep(X, algorithms, k_range, seed)
42
+ children = np.random.SeedSequence(seed).spawn(n_null) # same results for any n_jobs
43
+ out = None
44
+ for name in names:
45
+ runs = Parallel(n_jobs=n_jobs)(
46
+ delayed(_null_scores)(X, name, c, algorithms, k_range, seed) for c in children)
47
+ tab = _z_table(real, pd.concat(runs))
48
+ if out is None:
49
+ out = tab
50
+ else:
51
+ for c in INDEX_COLS:
52
+ out[c + "_z"] = np.minimum(out[c + "_z"], tab[c + "_z"])
53
+ return out
54
+
55
+
56
+ def verdict(cal: pd.DataFrame, threshold: float = 2.0) -> tuple[str, str]:
57
+ """Indices-only verdict from the calibrated table (older version, kept for now)."""
58
+ zcols = [c + "_z" for c in INDEX_COLS]
59
+ by_k = cal.groupby("k")[zcols].mean()
60
+ beating = by_k > threshold
61
+ if not beating.to_numpy().any():
62
+ return ("No evidence of clusters",
63
+ f"No index beats the null data (z > {threshold}) at any k.")
64
+ best = {c: int(by_k[c].idxmax()) for c in zcols if beating[c].any()}
65
+ if len(set(best.values())) == 1:
66
+ k = next(iter(best.values()))
67
+ return ("Clear structure", f"All indices that beat the null agree on k = {k}.")
68
+ return ("Weak or ambiguous structure",
69
+ "Indices beat the null but disagree on k: "
70
+ + ", ".join(f"{c[:-2]} -> {k}" for c, k in best.items()))
@@ -0,0 +1,51 @@
1
+ """Consensus clustering: combine many resampled clusterings into one."""
2
+ import numpy as np
3
+ from scipy.cluster.hierarchy import linkage, fcluster
4
+ from scipy.spatial.distance import squareform
5
+
6
+ from clustrust.core.algorithms import get_labels, SEED
7
+ from clustrust.core.defaults import value
8
+
9
+ def consensus(name: str, X: np.ndarray, k: int, n_rounds: int = 50,
10
+ frac: float = value("subsample_fraction"), seed: int = SEED) -> tuple[np.ndarray, np.ndarray]:
11
+ """Return (consensus labels, co-association matrix).
12
+
13
+ The matrix entry (i, j) is the fraction of resamples, among those that
14
+ contained both rows, in which rows i and j were put in the same group.
15
+ """
16
+ rng = np.random.default_rng(seed)
17
+ n = len(X)
18
+ together = np.zeros((n, n))
19
+ sampled = np.zeros((n, n))
20
+ for _ in range(n_rounds):
21
+ idx = rng.choice(n, size=int(frac * n), replace=False)
22
+ labels = get_labels(name, X[idx], k, seed)
23
+ same = (labels[:, None] == labels[None, :]).astype(float)
24
+ together[np.ix_(idx, idx)] += same
25
+ sampled[np.ix_(idx, idx)] += 1
26
+
27
+ C = np.divide(together, sampled, out=np.zeros_like(together), where=sampled > 0)
28
+ np.fill_diagonal(C, 1.0)
29
+
30
+ Z = linkage(squareform(1.0 - C, checks=False), method="average")
31
+ final = fcluster(Z, t=k, criterion="maxclust") - 1
32
+ return final, C
33
+
34
+ def pac(C: np.ndarray, lo: float = 0.1, hi: float = 0.9) -> float:
35
+ """Proportion of ambiguously clustered pairs: pairs whose co-association is
36
+ strictly between lo and hi. Lower means clearer structure."""
37
+ vals = C[np.triu_indices_from(C, k=1)]
38
+ return float(np.mean((vals > lo) & (vals < hi)))
39
+
40
+
41
+ def point_confidence(C: np.ndarray, labels: np.ndarray) -> np.ndarray:
42
+ """For each point, its average co-association with the other members of its own
43
+ consensus cluster (1 = always grouped with them). NaN for one-point clusters."""
44
+ conf = np.full(len(labels), np.nan)
45
+ for c in np.unique(labels):
46
+ members = np.where(labels == c)[0]
47
+ if len(members) < 2:
48
+ continue
49
+ sub = C[np.ix_(members, members)]
50
+ conf[members] = (sub.sum(axis=1) - 1.0) / (len(members) - 1) # drop the diagonal
51
+ return conf
@@ -0,0 +1,66 @@
1
+ """Default values for every adjustable parameter, and where each one comes from.
2
+
3
+ kind: 'literature' = published rule, or the default of a widely used package
4
+ 'convention' = common statistical convention, not specific to clustering
5
+ 'ours' = our own choice, declared as such in the paper
6
+ Every value can be changed by the user. 'note' holds the reasoning behind a choice.
7
+ """
8
+ DEFAULTS = {
9
+ "hopkins_tendency": {"value": 0.75, "kind": "literature",
10
+ "source": "Lawson & Jurs 1990 (H > 0.75: clustering tendency, 90% confidence)",
11
+ "note": "The 0.75 rule assumes a uniform baseline. On Gaussian noise H was 0.78, "
12
+ "so ClusTrust also requires H to beat structureless data with the same "
13
+ "means and correlations."},
14
+ "jaccard_dissolved": {"value": 0.50, "kind": "literature",
15
+ "source": "Hennig 2008; fpc clusterboot default"},
16
+ "jaccard_stable": {"value": 0.75, "kind": "literature",
17
+ "source": "Hennig 2007; fpc documentation"},
18
+ "stability_ari": {"value": 0.80, "kind": "literature",
19
+ "source": "Steinley 2004 'good' band, applied to agreement between resamples by analogy"},
20
+ "agreement_ari": {"value": 0.80, "kind": "literature",
21
+ "source": "Steinley 2004 'good' band, applied to agreement between algorithms by analogy"},
22
+ "pac_low": {"value": 0.10, "kind": "literature", "source": "Senbabaoglu et al. 2014"},
23
+ "pac_high": {"value": 0.90, "kind": "literature", "source": "Senbabaoglu et al. 2014"},
24
+ "pac_rule": {"value": "lowest", "kind": "literature",
25
+ "source": "Senbabaoglu et al. 2014: the k with the lowest PAC is preferred"},
26
+ "min_indices": {"value": 2, "kind": "literature",
27
+ "source": "Majority rule across indices, as in NbClust (Charrad et al. 2014; verify)"},
28
+ "n_rounds": {"value": 100, "kind": "literature",
29
+ "source": "Hennig 2007; fpc clusterboot default B = 100"},
30
+ "n_null": {"value": 100, "kind": "literature",
31
+ "source": "clusGap default B = 100 (Tibshirani, Walther & Hastie 2001)"},
32
+ "null_model": {"value": "both", "kind": "ours",
33
+ "source": "Gaussian null: Senbabaoglu et al. 2014, SigClust (Liu et al. 2008); "
34
+ "uniform-over-principal-components null: Tibshirani et al. 2001",
35
+ "note": "In a pilot the Gaussian null alone flagged uniform noise as structured, so by "
36
+ "default a result must beat both nulls."},
37
+ "z_cutoff": {"value": 2.0, "kind": "convention",
38
+ "source": "Two standard deviations; no clustering-specific value exists"},
39
+ "subsample_fraction": {
40
+ "value": 0.80, "kind": "literature",
41
+ "source": "Ben-Hur, Elisseeff & Guyon 2002 (fraction not much smaller than 1); "
42
+ "Wilkerson & Hayes 2010 (ConsensusClusterPlus default pItem = 0.8)",
43
+ "note": "We use 0.8 rather than the half-of-the-data default of fpc's optional subset scheme "
44
+ "(fpc's default scheme is the bootstrap). A larger fraction keeps more points of small "
45
+ "clusters in every resample, so they are less likely to be lost by chance; the cost is "
46
+ "that resamples overlap more, so stability values are somewhat higher.",
47
+ },"jaccard_unstable": {
48
+ "value": 0.60,
49
+ "kind": "literature",
50
+ "source": "Hennig 2008 / fpc & clustrd documentation: below 0.6 should not be trusted"
51
+ },
52
+ "jaccard_highly_stable": {
53
+ "value": 0.85,
54
+ "kind": "literature",
55
+ "source": "Hennig 2008 / fpc & clustrd documentation: 0.85 or more is highly stable"
56
+ },
57
+ }
58
+
59
+ PRESETS = {
60
+ "quick": {"n_rounds": 20, "n_null": 20, "null_model": "gaussian"},
61
+ "literature": {k: DEFAULTS[k]["value"] for k in ("n_rounds", "n_null", "null_model")},
62
+ }
63
+
64
+
65
+ def value(name: str):
66
+ return DEFAULTS[name]["value"]
@@ -0,0 +1,116 @@
1
+ """Evidence profile: combine calibrated indices, stability, PAC and agreement per k."""
2
+ from collections import Counter
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+ from clustrust.core.algorithms import ALGORITHMS, SEED
8
+ from clustrust.core.calibrate import calibrated_sweep, INDEX_COLS
9
+ from clustrust.core.runner import stability_sweep
10
+ from clustrust.core.consensus import consensus, pac
11
+ from clustrust.core.agreement import agreement
12
+ from clustrust.core.defaults import value
13
+
14
+ DEFAULTS = {"z": value("z_cutoff"), "min_indices": value("min_indices"),
15
+ "stability": value("stability_ari"), "agreement": value("agreement_ari")}
16
+
17
+
18
+ def evidence_profile(X, algorithms=ALGORITHMS, k_range=range(2, 9), n_null=None,
19
+ n_rounds=None, seed: int = SEED, cons_algo: str = "kmeans",
20
+ null=None, n_jobs: int = 1):
21
+ """Return (per-k table, calibrated table). None means: use the literature default."""
22
+ n_null = value("n_null") if n_null is None else n_null
23
+ n_rounds = value("n_rounds") if n_rounds is None else n_rounds
24
+ null = value("null_model") if null is None else null
25
+ cal = calibrated_sweep(X, algorithms, k_range, n_null=n_null, seed=seed,
26
+ null=null, n_jobs=n_jobs)
27
+ stab = stability_sweep(X, algorithms, k_range, n_rounds=n_rounds, seed=seed)
28
+ zcols = [c + "_z" for c in INDEX_COLS]
29
+ prof = cal.groupby("k")[zcols].mean()
30
+ prof["stability"] = stab.groupby("k")["stability_mean"].mean()
31
+ pacs, agrees = [], []
32
+ for k in prof.index:
33
+ _, C = consensus(cons_algo, X, int(k), n_rounds=n_rounds, seed=seed)
34
+ pacs.append(pac(C, value("pac_low"), value("pac_high")))
35
+ if len(algorithms) > 1:
36
+ M = agreement(X, int(k), algorithms, seed).to_numpy()
37
+ agrees.append(M[np.triu_indices_from(M, k=1)].mean())
38
+ else:
39
+ agrees.append(np.nan)
40
+ prof["pac"] = pacs
41
+ prof["agreement"] = agrees
42
+ return prof.reset_index(), cal
43
+
44
+
45
+ def criteria(prof: pd.DataFrame, **overrides) -> pd.DataFrame:
46
+ """For each k: does it pass the index, stability and agreement criteria?"""
47
+ p = {**DEFAULTS, **overrides}
48
+ zcols = [c for c in prof.columns if c.endswith("_z")]
49
+ out = pd.DataFrame({"k": prof["k"].astype(int).to_numpy()})
50
+ out["indices"] = ((prof[zcols] > p["z"]).sum(axis=1) >= p["min_indices"]).to_numpy()
51
+ out["stability"] = (prof["stability"] >= p["stability"]).to_numpy()
52
+ # with one algorithm there is nothing to compare, so agreement is not required
53
+ out["agreement"] = ((prof["agreement"] >= p["agreement"]) | prof["agreement"].isna()).to_numpy()
54
+ out["passes"] = out[["indices", "stability", "agreement"]].all(axis=1).astype(bool)
55
+ return out
56
+
57
+
58
+ def passing_k(prof: pd.DataFrame, **overrides) -> list[int]:
59
+ crit = criteria(prof, **overrides)
60
+ return crit.loc[crit["passes"], "k"].tolist()
61
+
62
+
63
+ def summarize(prof: pd.DataFrame, **overrides) -> dict:
64
+ """Verdict, reason, best-supported k and the other acceptable k.
65
+
66
+ PAC is not a pass/fail criterion (the literature gives no cutoff): among the k that pass,
67
+ the one with the lowest PAC is preferred (Senbabaoglu et al. 2014). The structure is called
68
+ clear only if that k is unique and is also favoured by most indices.
69
+ """
70
+ p = {**DEFAULTS, **overrides}
71
+ zcols = [c for c in prof.columns if c.endswith("_z")]
72
+ if not (prof[zcols] > p["z"]).to_numpy().any():
73
+ return {"verdict": "No evidence of clusters", "best_k": None, "candidates": [],
74
+ "reason": f"No index beats the null data (z > {p['z']}) at any k."}
75
+ crit = criteria(prof, **overrides)
76
+ passing = crit.loc[crit["passes"], "k"].tolist()
77
+ if not passing:
78
+ detail = []
79
+ for _, row in crit.iterrows():
80
+ failed = [n for n in ("indices", "stability", "agreement") if not row[n]]
81
+ if len(failed) <= 1:
82
+ detail.append(f"k={int(row['k'])} fails only {failed[0]}")
83
+ msg = "Indices beat the null but no k passes every criterion."
84
+ if detail:
85
+ msg += " Closest: " + "; ".join(detail) + "."
86
+ return {"verdict": "Weak or ambiguous structure", "reason": msg,
87
+ "best_k": None, "candidates": []}
88
+ sub = prof[prof["k"].isin(passing)].sort_values(["pac", "k"])
89
+ best = int(sub["k"].iloc[0])
90
+ pac_unique = len(sub) == 1 or sub["pac"].iloc[0] < sub["pac"].iloc[1]
91
+ votes = {}
92
+ for c in zcols:
93
+ try:
94
+ votes[c[:-2]] = int(prof.loc[prof[c].idxmax(), "k"])
95
+ except ValueError: # column has no valid values
96
+ pass
97
+ top_k, top_n = Counter(votes.values()).most_common(1)[0] if votes else (None, 0)
98
+ index_k = top_k if top_n >= p["min_indices"] else None
99
+ if len(passing) == 1:
100
+ return {"verdict": "Clear structure", "best_k": best, "candidates": passing,
101
+ "reason": f"k = {best} is the only k that beats the null on at least "
102
+ f"{p['min_indices']} indices and is stable and consistent across algorithms."}
103
+ if pac_unique and index_k == best:
104
+ others = [k for k in passing if k != best]
105
+ return {"verdict": "Clear structure", "best_k": best, "candidates": passing,
106
+ "reason": f"k = {best} has the lowest PAC among the k that pass every criterion "
107
+ f"and is favoured by most indices. Also acceptable: {others}."}
108
+ return {"verdict": "Weak or ambiguous structure", "best_k": best, "candidates": passing,
109
+ "reason": f"Several k pass every criterion: {passing}. Lowest PAC: k = {best}. "
110
+ "Index favourites: " + ", ".join(f"{n} -> {k}" for n, k in votes.items()) + "."}
111
+
112
+
113
+ def decide(prof: pd.DataFrame, **overrides) -> tuple[str, str]:
114
+ """Return (verdict, reason). Thresholds can be overridden."""
115
+ s = summarize(prof, **overrides)
116
+ return s["verdict"], s["reason"]
@@ -0,0 +1,26 @@
1
+ """Validity indices: scores that judge how good a clustering is."""
2
+ import numpy as np
3
+ from sklearn.metrics import (
4
+ silhouette_score,
5
+ calinski_harabasz_score,
6
+ davies_bouldin_score,
7
+ )
8
+
9
+
10
+ def score(X: np.ndarray, labels: np.ndarray) -> dict:
11
+ """Three quality scores for one clustering."""
12
+ return {
13
+ "silhouette": float(silhouette_score(X, labels)), # higher is better
14
+ "calinski_harabasz": float(calinski_harabasz_score(X, labels)), # higher is better
15
+ "davies_bouldin": float(davies_bouldin_score(X, labels)), # lower is better
16
+ }
17
+
18
+ def silhouette_band(s: float) -> str:
19
+ """Kaufman & Rousseeuw 1990 interpretation of an average silhouette."""
20
+ if s >= 0.71:
21
+ return "strong"
22
+ if s >= 0.51:
23
+ return "reasonable"
24
+ if s >= 0.26:
25
+ return "weak"
26
+ return "none"
clustrust/core/null.py ADDED
@@ -0,0 +1,23 @@
1
+ """Null reference data: same mean and correlations as the real data, but no clusters."""
2
+ import numpy as np
3
+
4
+
5
+ def gaussian_null(X: np.ndarray, rng: np.random.Generator) -> np.ndarray:
6
+ """One structureless dataset: a single Gaussian with the data's mean and covariance."""
7
+ mean = X.mean(axis=0)
8
+ cov = np.atleast_2d(np.cov(X, rowvar=False))
9
+ return rng.multivariate_normal(mean, cov, size=len(X))
10
+
11
+
12
+ def uniform_pca_null(X: np.ndarray, rng: np.random.Generator) -> np.ndarray:
13
+ """Uniform data in the box around X after rotating it onto its principal axes
14
+ (the gap statistic's reference data, Tibshirani et al. 2001)."""
15
+ mean = X.mean(axis=0)
16
+ Xc = X - mean
17
+ _, _, Vt = np.linalg.svd(Xc, full_matrices=False)
18
+ R = Xc @ Vt.T
19
+ U = rng.uniform(R.min(axis=0), R.max(axis=0), size=R.shape)
20
+ return U @ Vt + mean
21
+
22
+
23
+ NULLS = {"gaussian": gaussian_null, "pca_uniform": uniform_pca_null}
@@ -0,0 +1,19 @@
1
+ """Describe what each cluster looks like."""
2
+ import numpy as np
3
+ import pandas as pd
4
+
5
+
6
+ def cluster_profiles(df: pd.DataFrame, labels: np.ndarray) -> tuple[pd.DataFrame, pd.Series]:
7
+ """Return (mean of each feature per cluster with sizes, feature separation scores).
8
+
9
+ df must be the numeric table the labels were computed on (use numeric_frame).
10
+ The separation score is eta-squared: the share of a feature's variance explained
11
+ by cluster membership (0 = useless, 1 = perfectly separates the clusters).
12
+ """
13
+ labels = np.asarray(labels)
14
+ means = df.groupby(labels).mean()
15
+ means.insert(0, "size", df.groupby(labels).size())
16
+ overall = df.mean()
17
+ ss_total = ((df - overall) ** 2).sum().replace(0, np.nan)
18
+ ss_between = sum(len(g) * (g.mean() - overall) ** 2 for _, g in df.groupby(labels))
19
+ return means, (ss_between / ss_total).sort_values(ascending=False)
@@ -0,0 +1,28 @@
1
+ """Runs every algorithm for every k and collects the results in one table."""
2
+ import pandas as pd
3
+
4
+ from clustrust.core.algorithms import get_labels, ALGORITHMS, SEED
5
+ from clustrust.core.indices import score
6
+ from clustrust.core.stability import stability
7
+
8
+
9
+ def sweep(X, algorithms=ALGORITHMS, k_range=range(2, 9), seed: int = SEED) -> pd.DataFrame:
10
+ """Try every algorithm for every k and return one results table."""
11
+ rows = []
12
+ for name in algorithms:
13
+ for k in k_range:
14
+ labels = get_labels(name, X, k, seed)
15
+ rows.append({"algorithm": name, "k": k, **score(X, labels)})
16
+ return pd.DataFrame(rows)
17
+
18
+
19
+ def stability_sweep(X, algorithms=ALGORITHMS, k_range=range(2, 9),
20
+ n_rounds: int = 20, seed: int = SEED) -> pd.DataFrame:
21
+ """Stability (mean and std of ARI over resamples) for every algorithm and k."""
22
+ rows = []
23
+ for name in algorithms:
24
+ for k in k_range:
25
+ mean, std = stability(name, X, k, n_rounds=n_rounds, seed=seed)
26
+ rows.append({"algorithm": name, "k": k,
27
+ "stability_mean": mean, "stability_std": std})
28
+ return pd.DataFrame(rows)
@@ -0,0 +1,62 @@
1
+ """Stability: do the groups stay the same when the data changes a little?"""
2
+ import numpy as np
3
+ import pandas as pd
4
+ from sklearn.metrics import adjusted_rand_score
5
+
6
+ from clustrust.core.algorithms import get_labels, SEED
7
+ from clustrust.core.defaults import value
8
+
9
+ def stability(name: str, X: np.ndarray, k: int, n_rounds: int = 20,
10
+ frac: float = value("subsample_fraction"), seed: int = SEED) -> tuple[float, float]:
11
+ """Average agreement (ARI) between the full clustering and subsample clusterings.
12
+
13
+ Returns (mean, standard deviation). Close to 1 means very stable.
14
+ """
15
+ rng = np.random.default_rng(seed)
16
+ reference = get_labels(name, X, k, seed)
17
+ scores = []
18
+ for _ in range(n_rounds):
19
+ idx = rng.choice(len(X), size=int(frac * len(X)), replace=False)
20
+ sub_labels = get_labels(name, X[idx], k, seed)
21
+ scores.append(adjusted_rand_score(reference[idx], sub_labels))
22
+ return float(np.mean(scores)), float(np.std(scores))
23
+
24
+ def cluster_jaccard(name: str, X: np.ndarray, k: int, n_rounds: int = 50,
25
+ frac: float = value("subsample_fraction"), seed: int = SEED,
26
+ threshold: float = 0.5, reference = None) -> pd.DataFrame:
27
+ """Cluster-wise stability. For each cluster of the full-data solution, the best-matching
28
+ Jaccard similarity in each resample, averaged. At or below threshold = 'dissolved'."""
29
+ rng = np.random.default_rng(seed)
30
+ ref = get_labels(name, X, k, seed) if reference is None else np.asarray(reference)
31
+ ids = np.unique(ref)
32
+ totals = np.zeros(len(ids))
33
+ for _ in range(n_rounds):
34
+ idx = rng.choice(len(X), size=int(frac * len(X)), replace=False)
35
+ sub = get_labels(name, X[idx], k, seed)
36
+ ref_sub = ref[idx]
37
+ for a, c in enumerate(ids):
38
+ A = ref_sub == c
39
+ best = 0.0
40
+ for s in np.unique(sub):
41
+ B = sub == s
42
+ union = np.logical_or(A, B).sum()
43
+ if union:
44
+ best = max(best, np.logical_and(A, B).sum() / union)
45
+ totals[a] += best
46
+ mean = totals / n_rounds
47
+ return pd.DataFrame({"cluster": ids,
48
+ "size": [int((ref == c).sum()) for c in ids],
49
+ "mean_jaccard": mean,
50
+ "dissolved": mean <= threshold})
51
+
52
+ def jaccard_band(x: float) -> str:
53
+ """Hennig-style reading of a cluster's mean Jaccard stability."""
54
+ if x <= value("jaccard_dissolved"):
55
+ return "dissolved"
56
+ if x < value("jaccard_unstable"):
57
+ return "unstable"
58
+ if x < value("jaccard_stable"):
59
+ return "pattern only"
60
+ if x < value("jaccard_highly_stable"):
61
+ return "stable"
62
+ return "highly stable"
@@ -0,0 +1,46 @@
1
+ """Does the data have group structure at all, before any clustering?"""
2
+ import numpy as np
3
+ from sklearn.decomposition import PCA
4
+ from sklearn.neighbors import NearestNeighbors
5
+
6
+ from clustrust.core.algorithms import SEED
7
+ from clustrust.core.null import gaussian_null
8
+
9
+
10
+ def hopkins(X: np.ndarray, rng: np.random.Generator, m: int | None = None) -> float:
11
+ """Hopkins statistic: about 0.5 for evenly spread data, towards 1 for clustered data."""
12
+ n, d = X.shape
13
+ m = m or max(10, min(int(0.1 * n), n - 1))
14
+ nn = NearestNeighbors(n_neighbors=2).fit(X)
15
+ U = rng.uniform(X.min(axis=0), X.max(axis=0), size=(m, d))
16
+ u = nn.kneighbors(U, n_neighbors=1)[0].sum()
17
+ idx = rng.choice(n, size=m, replace=False)
18
+ w = nn.kneighbors(X[idx], n_neighbors=2)[0][:, 1].sum() # skip the point itself
19
+ return float(u / (u + w))
20
+
21
+
22
+ def tendency_check(X: np.ndarray, n_null: int = 20, seed: int = SEED) -> dict:
23
+ """Hopkins on the real data versus structureless Gaussian null data, plus the dip test."""
24
+ rng = np.random.default_rng(seed)
25
+ real = hopkins(X, rng)
26
+ nulls = np.array([hopkins(gaussian_null(X, rng), rng) for _ in range(n_null)])
27
+ z = (real - nulls.mean()) / (nulls.std() or np.nan)
28
+ out = {"hopkins": real, "null_mean": float(nulls.mean()),
29
+ "null_std": float(nulls.std()), "hopkins_z": float(z),
30
+ "dip": None, "dip_p": None}
31
+ try:
32
+ from diptest import diptest
33
+ pc1 = PCA(n_components=1).fit_transform(X).ravel()
34
+ out["dip"], out["dip_p"] = (float(v) for v in diptest(pc1))
35
+ except ImportError:
36
+ pass # dip test is optional
37
+ return out
38
+
39
+ '''
40
+ Hopkins on Gaussian data is not exactly 0.5,
41
+ because the statistic assumes uniform data.
42
+ That is why the result is compared with the null
43
+ instead of with 0.5. The dip test is only applied
44
+ to the first principal component, so it can miss
45
+ structure that isn't visible along that direction.
46
+ '''
File without changes