Download code/src/lnpbench/global_rep.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 7.52 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/src/lnpbench/global_rep.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench/code/src/lnpbench/global_rep.py
-
curl -L -o global_rep.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/src/lnpbench/global_rep.py
7.52 kB
| """Global (dataset-level) representation learning, label-free. | |
| The rest of the package learns a representation *per molecule*: descriptors of | |
| one lipid, physics of one fragment. A tree or a network trained on such | |
| features can only interpolate between molecules it has seen analogues of. The | |
| modules here add a second, complementary view: a coordinate system fitted on | |
| the whole chemical space of the database, in which any molecule -- including | |
| one from a study that was never labelled -- has a smooth position. | |
| Two constructions are provided. | |
| ``codebook`` | |
| A vector-quantised codebook of chemical archetypes. k-means is fitted on | |
| standardised chemistry features of a large reference set; every molecule is | |
| then described by its *soft* membership over the K archetypes, | |
| ``p_k ~ exp(-d_k^2 / 2 sigma^2)``, plus the entropy and margin of that | |
| distribution. A fingerprint says "this is molecule #7731"; a soft | |
| membership says "this is 60 % a tertiary-amine diester lipid and 30 % a | |
| branched polyunsaturated one". The latter is shared by many molecules and | |
| therefore transfers. | |
| ``spectral`` | |
| Laplacian eigenmaps of the k-nearest-neighbour graph over the same features. | |
| This is the classical manifold-learning view of the same idea and provides a | |
| lower-dimensional, smoother alternative to the codebook. | |
| Both are **unsupervised**: no target value is used anywhere. They may be | |
| fitted on all rows of the database (transductive but label-free) or on the | |
| training rows only (fully inductive); the experiment script reports both. | |
| """ | |
| from __future__ import annotations | |
| from typing import Optional, Tuple | |
| import numpy as np | |
| from scipy import sparse | |
| from scipy.sparse.linalg import eigsh | |
| def _standardise(X: np.ndarray, ref: Optional[np.ndarray] = None) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: | |
| ref = X if ref is None else ref | |
| mu = np.nanmean(ref, axis=0) | |
| sd = np.nanstd(ref, axis=0) | |
| sd = np.where(sd < 1e-8, 1.0, sd) | |
| return (X - mu) / sd, mu, sd | |
| def _pca(Z: np.ndarray, ref: np.ndarray, dim: int) -> Tuple[np.ndarray, np.ndarray]: | |
| """PCA fitted on ``ref`` (already standardised), applied to ``Z``.""" | |
| dim = int(min(dim, ref.shape[1], ref.shape[0] - 1)) | |
| if dim < 1: | |
| return Z, np.eye(Z.shape[1], dtype=np.float32) | |
| mu = ref.mean(0) | |
| U, S, Vt = np.linalg.svd(ref - mu, full_matrices=False) | |
| comps = Vt[:dim].T # (D, dim) | |
| scale = np.sqrt(np.maximum(S[:dim] ** 2 / max(len(ref) - 1, 1), 1e-12)) | |
| return ((Z - mu) @ comps) / scale, comps | |
| def codebook_embed( | |
| X: np.ndarray, | |
| fit_rows: np.ndarray, | |
| k: int = 64, | |
| pca_dim: int = 48, | |
| seed: int = 0, | |
| include_stats: bool = True, | |
| ) -> np.ndarray: | |
| """Soft membership over ``k`` chemical archetypes. | |
| Parameters | |
| ---------- | |
| X : (N, D) chemistry features for **all** rows that will ever be encoded. | |
| fit_rows : rows of ``X`` used to fit the standardiser / PCA / k-means. | |
| Pass ``np.arange(len(X))`` for the label-free transductive variant, or | |
| the training rows only for the fully inductive variant. | |
| """ | |
| from sklearn.cluster import KMeans | |
| Xf = np.nan_to_num(X.astype(np.float64), nan=0.0, posinf=0.0, neginf=0.0) | |
| Xf = np.clip(Xf, -1e6, 1e6) | |
| Zf, mu, sd = _standardise(Xf[fit_rows]) | |
| Zf, _ = _pca(Zf, Zf, pca_dim) | |
| Z, _ = _pca((Xf - mu) / sd, (Xf[fit_rows] - mu) / sd, pca_dim) | |
| km = KMeans(n_clusters=k, n_init=10, random_state=seed, algorithm="lloyd") | |
| km.fit(Zf) | |
| centers = km.cluster_centers_.astype(np.float64) # (k, p) | |
| # squared distances of every row to every archetype (quadratic expansion; | |
| # the naive broadcast would materialise an (N, k, p) array) | |
| zn2 = (Z ** 2).sum(1, keepdims=True) | |
| cn2 = (centers ** 2).sum(1)[None, :] | |
| d2 = np.maximum(zn2 - 2.0 * (Z @ centers.T) + cn2, 0.0) # (N, k) | |
| # temperature: median within-cluster distance on the fit rows | |
| fit_d2 = d2[fit_rows] | |
| nearest = fit_d2.min(1) | |
| sigma2 = max(float(np.median(nearest)), 1e-6) | |
| logits = -(d2 - nearest[:, None]) / (2.0 * sigma2) | |
| logits -= logits.max(1, keepdims=True) | |
| P = np.exp(logits) | |
| P /= P.sum(1, keepdims=True) | |
| if not include_stats: | |
| return P.astype(np.float32) | |
| ent = -(P * np.log(P + 1e-12)).sum(1) / np.log(k) | |
| ds = np.sqrt(np.maximum(d2, 0.0)) | |
| ds.sort(1) | |
| margin = (ds[:, 1] - ds[:, 0]) / (ds[:, 1] + 1e-6) | |
| coords = np.sqrt(np.maximum(d2, 0.0))[:, :8] / (np.sqrt(sigma2) + 1e-6) | |
| stats = np.stack([ent, margin, np.sqrt(nearest) / (np.sqrt(sigma2) + 1e-6)], axis=1) | |
| return np.concatenate([P, stats, coords], axis=1).astype(np.float32) | |
| def knn_graph(Z: np.ndarray, k: int = 15) -> sparse.csr_matrix: | |
| """Symmetric cosine kNN affinity.""" | |
| from sklearn.neighbors import NearestNeighbors | |
| Zn = Z / (np.linalg.norm(Z, axis=1, keepdims=True) + 1e-9) | |
| nn = NearestNeighbors(n_neighbors=min(k + 1, len(Z)), metric="cosine", algorithm="brute") | |
| nn.fit(Zn) | |
| dist, ind = nn.kneighbors(Zn) | |
| dist, ind = dist[:, 1:], ind[:, 1:] | |
| rows = np.repeat(np.arange(len(Z)), ind.shape[1]) | |
| cols = ind.ravel() | |
| vals = np.exp(-(dist.ravel() ** 2) / (2 * np.median(dist) ** 2 + 1e-12)) | |
| W = sparse.coo_matrix((vals, (rows, cols)), shape=(len(Z), len(Z))).tocsr() | |
| W = W.maximum(W.T) | |
| return W | |
| def spectral_embed( | |
| X: np.ndarray, | |
| fit_rows: Optional[np.ndarray] = None, | |
| k: int = 15, | |
| pca_dim: int = 48, | |
| n_components: int = 32, | |
| ) -> np.ndarray: | |
| """Laplacian eigenmaps of the chemistry manifold. | |
| The graph is built on all rows (the geometry of chemical space does not | |
| depend on labels); ``fit_rows`` is only used for the standardiser / PCA. | |
| """ | |
| Xf = np.nan_to_num(X.astype(np.float64), nan=0.0, posinf=0.0, neginf=0.0) | |
| Xf = np.clip(Xf, -1e6, 1e6) | |
| if fit_rows is None: | |
| fit_rows = np.arange(len(Xf)) | |
| Zf, mu, sd = _standardise(Xf[fit_rows]) | |
| _, comps = _pca(Zf, Zf, pca_dim) | |
| Z = ((Xf - mu) / sd) @ comps | |
| W = knn_graph(Z, k=k) | |
| d = np.asarray(W.sum(1)).ravel() | |
| dinv = 1.0 / np.sqrt(np.maximum(d, 1e-9)) | |
| Dinv = sparse.diags(dinv) | |
| M = Dinv @ W @ Dinv # symmetric diffusion operator | |
| # Largest eigenpairs of the normalised affinity. ARPACK is not used here: | |
| # a kNN graph over 19k points is close to disconnected, so the top of the | |
| # spectrum has a large near-degenerate cluster and iterative eigensolvers | |
| # stall. A randomised SVD recovers the same subspace in a few seconds. | |
| from sklearn.utils.extmath import randomized_svd | |
| n_components = int(min(n_components, len(Z) - 2)) | |
| U, S, _ = randomized_svd(M, n_components=n_components + 1, n_iter=7, random_state=0) | |
| lam = np.clip(S, -1.0, 1.0) | |
| # The (1 - lambda) diffusion-map scaling is deliberately *not* applied: on | |
| # this graph the top of the spectrum is degenerate (lambda ~ 0.99 for every | |
| # component), so that scaling would collapse all coordinates to zero. The | |
| # raw eigenvector basis is returned instead and ``spectral_diagnostics`` | |
| # reports the degeneracy so the failure is visible rather than hidden. | |
| vecs = U[:, 1:] | |
| # deterministic sign: make the largest-|value| entry positive | |
| for j in range(vecs.shape[1]): | |
| idx = int(np.argmax(np.abs(vecs[:, j]))) | |
| if vecs[idx, j] < 0: | |
| vecs[:, j] *= -1.0 | |
| spectral_embed.last_spectrum = np.asarray(lam, dtype=np.float64) | |
| return vecs.astype(np.float32) |