geolatent#

geolatent — Geometry-aware, model-intelligent 3-D ML visualisations.

geolatent is a production-grade Python library that provides semantic 3-D visualisation primitives specifically designed for machine learning workflows. It is not a thin wrapper around Plotly; instead it operates as an abstraction layer that understands model decision geometry, high-dimensional feature spaces, and embedding manifold structure.

Key capabilities#

  • visualize_decision_geometry() — project a classifier’s decision function to 3-D via PCA inverse-transform and render probability isosurfaces, class scatter clouds, and Mahalanobis confidence ellipsoids in a single call.

  • inspect_latent_space() — visualise the geometric structure of arbitrary high-dimensional embeddings (transformer hidden states, VAE latent codes, word vectors, etc.) with configurable projection (PCA / t-SNE / UMAP), confidence ellipsoids, and convex-hull cluster boundaries.

Both functions produce interactive Plotly figures styled with a dark-scientific theme and are ready for inline display in Google Colab and Jupyter notebooks.

Quick start#

from sklearn.svm import SVC
from sklearn.datasets import make_classification
from geolatent import visualize_decision_geometry

X, y = make_classification(n_samples=300, n_features=15, n_classes=3,
                           n_informative=8, random_state=0)
model = SVC(kernel="rbf", probability=True).fit(X, y)

fig = visualize_decision_geometry(model, X, y)
fig.show()

See also

Submodules#

Attributes#

Classes#

ColorPalette

Specification of all colours used within a single visualisation theme.

ProjectionConfig

Configuration for the dimensionality-reduction pipeline.

RenderConfig

Low-level rendering and layout parameters.

VisualizationConfig

Top-level configuration container for geolatent.

GeometryUtils

Collection of geometric analysis and Plotly trace generators.

MeshBuilder

Constructs prediction meshes for 3-D decision-surface rendering.

PredictionMesh

Outputs of a decision-surface prediction sweep over a 3-D grid.

DimensionalityProjector

Unified dimensionality-reduction pipeline.

ProjectionResult

Container returned by DimensionalityProjector.fit_transform().

DataOverlay

Generates data-point and structural overlays for 3-D scenes.

Scene3D

Stateful 3-D Plotly figure builder with dark-scientific theming.

DecisionSurfaceRenderer

Renders decision surfaces from a PredictionMesh.

Functions#

visualize_decision_geometry(→ plotly.graph_objects.Figure)

Render the decision geometry of a scikit-learn-compatible classifier in 3-D.

inspect_latent_space(→ plotly.graph_objects.Figure)

Visualise the geometric structure of high-dimensional embeddings in 3-D.

Package Contents#

geolatent.visualize_decision_geometry(model: object, X: numpy.ndarray, y: numpy.ndarray, *, config: geolatent.config.themes.VisualizationConfig | None = None, projection_method: str = 'pca', predict_fn=None, feature_names: List[str] | None = None, mesh_resolution: int = 30, show_surface: bool = True, show_confidence: bool = True, show_scatter: bool = True, show_centroids: bool = True, show_ellipsoids: bool = False, show_convex_hulls: bool = False, ellipsoid_confidence: float = 0.9, class_names: Dict | None = None, title: str | None = None, batch_size: int | None = None) plotly.graph_objects.Figure[source]#

Render the decision geometry of a scikit-learn-compatible classifier in 3-D.

The input feature matrix X is projected to 3 principal components via PCA (or t-SNE / UMAP for pure scatter visualisation). When PCA is used, the model’s decision function is evaluated on a regular 3-D grid that is inverse-transformed back into the original feature space, producing decision boundary isosurfaces anchored to the actual model geometry — not an approximation in an arbitrary slice.

Parameters:
  • model (sklearn-compatible estimator) – Must implement predict(X). Also implements predict_proba(X) for richer confidence-surface rendering (recommended).

  • X (array-like of shape (n_samples, n_features)) – Training feature matrix. Will be standardised and projected internally.

  • y (array-like of shape (n_samples,)) – Class label vector. Integer or string labels are both supported.

  • config (VisualizationConfig, optional) – Custom theme and rendering configuration. Defaults to DARK_SCIENTIFIC.

  • projection_method ({"pca", "tsne", "umap", "sensitivity"}) – Dimensionality-reduction algorithm. "pca" and "sensitivity" both support decision-surface rendering. "sensitivity" uses finite-difference Jacobians to find axes the model actually cares about and works with any callable (sklearn, PyTorch, XGBoost, etc.).

  • predict_fn (callable, optional) – Required when projection_method="sensitivity" with a non-sklearn model. For sklearn models it is auto-derived from model.predict_proba or model.predict when not supplied.

  • feature_names (list of str, optional) – Names of the input features. Shown on axes and sensitivity labels.

  • mesh_resolution (int) – Grid resolution per dimension for the prediction mesh. Total inference calls equal mesh_resolution³. Default 30.

  • show_surface (bool) – Whether to render the decision boundary / probability surfaces.

  • show_confidence (bool) – When True and the model exposes predict_proba, render nested confidence isosurfaces in addition to the primary boundary shell.

  • show_scatter (bool) – Whether to render the data-point scatter cloud.

  • show_centroids (bool) – Whether to render class-centroid diamond markers.

  • show_ellipsoids (bool) – Whether to overlay Mahalanobis-distance confidence ellipsoids.

  • show_convex_hulls (bool) – Whether to overlay transparent convex-hull surfaces per class.

  • ellipsoid_confidence (float) – Confidence level for ellipsoid construction (default 0.90 → 90 % region).

  • class_names (dict, optional) – Mapping from class label to human-readable display string.

  • title (str, optional) – Figure title. Overrides config.title when supplied.

  • batch_size (int, optional) – Batch size for model inference on the prediction mesh.

Returns:

fig – Interactive 3-D Plotly figure.

Return type:

plotly.graph_objects.Figure

Raises:
  • TypeError – If model does not expose a predict method.

  • ValueError – If X or y fail validation (shape, NaN, insufficient classes).

Examples

>>> from sklearn.ensemble import GradientBoostingClassifier
>>> from sklearn.datasets import make_classification
>>> from geolatent import visualize_decision_geometry
>>>
>>> X, y = make_classification(n_samples=400, n_features=20, n_classes=3,
...                            n_informative=10, random_state=0)
>>> clf = GradientBoostingClassifier(n_estimators=50, random_state=0).fit(X, y)
>>> fig = visualize_decision_geometry(clf, X, y,
...                                   title="GBM — 3-class Decision Geometry")
>>> fig.show()
geolatent.inspect_latent_space(embeddings: numpy.ndarray, labels: numpy.ndarray, *, config: geolatent.config.themes.VisualizationConfig | None = None, projection_method: str = 'pca', show_scatter: bool = True, show_centroids: bool = True, show_ellipsoids: bool = True, show_convex_hulls: bool = False, ellipsoid_confidence: float = 0.9, class_names: Dict | None = None, title: str | None = None, point_size: int | None = None, scatter_opacity: float | None = None) plotly.graph_objects.Figure[source]#

Visualise the geometric structure of high-dimensional embeddings in 3-D.

Projects embeddings from their native dimensionality to 3-D using the chosen dimensionality-reduction algorithm, then renders an interactive scene with class-coloured scatter clouds, centroid markers, and optional structural overlays (confidence ellipsoids, convex hulls).

Parameters:
  • embeddings (array-like of shape (n_samples, n_dims)) – High-dimensional embedding vectors. Suitable inputs include transformer hidden states, GAN latent codes, learned feature maps, or any continuous representation to be analysed structurally.

  • labels (array-like of shape (n_samples,)) – Integer or string class / group labels for colour coding.

  • config (VisualizationConfig, optional) – Theme and rendering configuration. Defaults to DARK_SCIENTIFIC.

  • projection_method ({"pca", "tsne", "umap"}) – Dimensionality-reduction algorithm. "pca" is fast and preserves global geometry; "tsne" / "umap" are better at revealing local cluster structure at the cost of interpretability.

  • show_scatter (bool) – Whether to render the data-point scatter cloud.

  • show_centroids (bool) – Whether to render class-centroid diamond markers.

  • show_ellipsoids (bool) – Whether to overlay Mahalanobis-distance confidence ellipsoids (default True — these are the primary structural indicator in latent-space analysis).

  • show_convex_hulls (bool) – Whether to overlay transparent convex-hull surfaces per class.

  • ellipsoid_confidence (float) – Confidence level for the Mahalanobis ellipsoid (default 0.90).

  • class_names (dict, optional) – Mapping from label value to display string.

  • title (str, optional) – Figure title.

  • point_size (int, optional) – Override the default scatter marker size.

  • scatter_opacity (float, optional) – Override the default scatter marker opacity.

Returns:

fig

Return type:

plotly.graph_objects.Figure

Raises:

ValueError – If embeddings or labels fail shape / finiteness validation.

Examples

>>> from geolatent import inspect_latent_space
>>> import numpy as np
>>>
>>> # Simulate 4 Gaussian clusters in a 128-D embedding space
>>> rng = np.random.default_rng(0)
>>> embeddings = np.vstack([
...     rng.normal(loc=c, scale=1.0, size=(100, 128))
...     for c in [0, 3, 6, 9]
... ])
>>> labels = np.repeat([0, 1, 2, 3], 100)
>>> fig = inspect_latent_space(
...     embeddings, labels,
...     projection_method="pca",
...     title="128-D Gaussian Clusters — PCA Projection",
... )
>>> fig.show()
class geolatent.ColorPalette[source]#

Specification of all colours used within a single visualisation theme.

Parameters:
  • background (str) – Hex colour for the outermost canvas / paper background.

  • grid (str) – Hex colour for axis gridlines and background panes.

  • text (str) – Hex colour for all labels, titles, and annotations.

  • axis_line (str) – Hex colour for zero-axis lines and tick marks.

  • class_colors (list of str) – Ordered list of hex colours assigned to distinct classes. Colours are cycled when the number of classes exceeds the list length.

  • surface_colorscale (str) – Plotly-compatible named colorscale used for probability volumes and scalar-field surfaces.

  • boundary_colorscale (str) – Colorscale used to shade diverging decision-boundary surfaces.

  • marker_line_color (str) – Colour of the thin outline drawn around scatter markers.

  • centroid_color (str) – Colour of the star-shaped class-centroid markers.

  • annotation_color (str) – Colour of variance-explained and other textual annotations.

background: str = '#0d1117'#
grid: str = '#161b22'#
text: str = '#e6edf3'#
axis_line: str = '#30363d'#
class_colors: List[str] = ['#58a6ff', '#3fb950', '#f78166', '#d2a8ff', '#ffa657', '#79c0ff', '#56d364', '#ff7b72']#
surface_colorscale: str = 'Plasma'#
boundary_colorscale: str = 'RdBu'#
marker_line_color: str = '#0d1117'#
centroid_color: str = '#f0f6fc'#
annotation_color: str = '#8b949e'#
geolatent.DARK_SCIENTIFIC: VisualizationConfig#
class geolatent.ProjectionConfig[source]#

Configuration for the dimensionality-reduction pipeline.

Parameters:
  • method ({"pca", "tsne", "umap", "sensitivity"}) – Projection algorithm. "pca" and "sensitivity" both support inverse-transform (required for decision-surface rendering). "sensitivity" finds axes the model actually cares about using finite-difference Jacobians. "tsne" and "umap" are for latent-space visualisation only.

  • n_components (int) – Target dimensionality. Should be 3 for all 3-D visualisations.

  • whiten (bool) – Whether to whiten the PCA output (unit variance per component).

  • tsne_perplexity (float) – Perplexity hyper-parameter for t-SNE. Should be less than n_samples.

  • tsne_learning_rate (float) – Learning rate for t-SNE gradient descent.

  • tsne_n_iter (int) – Maximum number of iterations for t-SNE optimisation.

  • umap_n_neighbors (int) – Number of neighbours used by UMAP to build the local topology.

  • umap_min_dist (float) – Minimum distance between embedded points for UMAP.

  • random_state (int) – Global random seed for reproducibility across all stochastic operations.

  • scale_input (bool) – Whether to standardise features (zero-mean, unit-variance) before applying the chosen projection. Strongly recommended for PCA.

method: str = 'pca'#
n_components: int = 3#
whiten: bool = False#
tsne_perplexity: float = 30.0#
tsne_learning_rate: float = 200.0#
tsne_n_iter: int = 1000#
umap_n_neighbors: int = 15#
umap_min_dist: float = 0.1#
random_state: int = 42#
scale_input: bool = True#
sensitivity_n_subsample: int = 300#
sensitivity_eps: float = 0.01#
class geolatent.RenderConfig[source]#

Low-level rendering and layout parameters.

Parameters:
  • width (int) – Canvas width in pixels.

  • height (int) – Canvas height in pixels.

  • surface_opacity (float) – Alpha value (0–1) for decision boundary / probability isosurfaces.

  • scatter_opacity (float) – Alpha value (0–1) for data-point scatter markers.

  • marker_size (int) – Diameter of scatter markers in pixels.

  • centroid_marker_size (int) – Diameter of class-centroid markers in pixels.

  • ellipsoid_opacity (float) – Alpha value (0–1) for confidence ellipsoid surfaces.

  • show_axes (bool) – Whether to display axis labels, ticks, and gridlines.

  • show_legend (bool) – Whether to show the interactive legend panel.

  • show_colorbar (bool) – Whether to show the colourbar for scalar-field surfaces.

  • camera_eye (dict) – Plotly camera eye dict with keys x, y, z.

  • camera_up (dict) – Plotly camera up vector dict.

  • font_family (str) – Font family string passed to Plotly’s font specification.

  • font_size (int) – Base font size in points.

width: int = 960#
height: int = 720#
surface_opacity: float = 0.28#
scatter_opacity: float = 0.88#
marker_size: int = 5#
centroid_marker_size: int = 14#
ellipsoid_opacity: float = 0.15#
show_axes: bool = True#
show_legend: bool = True#
show_colorbar: bool = False#
camera_eye: Dict[str, float]#
camera_up: Dict[str, float]#
font_family: str = "'JetBrains Mono', 'Fira Code', 'Consolas', 'Courier New', monospace"#
font_size: int = 12#
class geolatent.VisualizationConfig[source]#

Top-level configuration container for geolatent.

Combines colour, rendering, and projection sub-configurations into a single immutable-style object that can be passed to any public API function. All sub-configs carry sensible defaults so that VisualizationConfig() yields a production-ready dark-scientific theme.

Parameters:
  • colors (ColorPalette) – Colour definitions for the entire visualisation.

  • render (RenderConfig) – Rendering and canvas layout parameters.

  • projection (ProjectionConfig) – Dimensionality-reduction settings applied to model inputs and embeddings.

  • title (str, optional) – Plot title string. When set, overrides the auto-generated title.

  • show_variance_annotation (bool) – When True and PCA is used, annotates the figure with the cumulative explained-variance ratio captured by the three principal components.

Examples

>>> from geolatent.config.themes import VisualizationConfig, ProjectionConfig
>>> cfg = VisualizationConfig()
>>> cfg_tsne = cfg.with_method("tsne")
>>> cfg_titled = cfg.with_title("SVM Decision Geometry — RBF Kernel")
colors: ColorPalette#
render: RenderConfig#
projection: ProjectionConfig#
title: str | None = None#
show_variance_annotation: bool = True#
copy() VisualizationConfig[source]#

Return an independent deep copy of this configuration object.

with_method(method: str) VisualizationConfig[source]#

Return a copy with the projection method overridden.

Parameters:

method ({"pca", "tsne", "umap", "sensitivity"}) – New projection algorithm.

Return type:

VisualizationConfig

with_title(title: str) VisualizationConfig[source]#

Return a copy with the plot title overridden.

Parameters:

title (str)

Return type:

VisualizationConfig

with_resolution(width: int, height: int) VisualizationConfig[source]#

Return a copy with canvas dimensions overridden.

Parameters:
Return type:

VisualizationConfig

with_opacity(surface: float | None = None, scatter: float | None = None, ellipsoid: float | None = None) VisualizationConfig[source]#

Return a copy with opacity values selectively overridden.

Parameters:
  • surface (float, optional)

  • scatter (float, optional)

  • ellipsoid (float, optional)

Return type:

VisualizationConfig

class geolatent.GeometryUtils(config: geolatent.config.themes.VisualizationConfig)[source]#

Collection of geometric analysis and Plotly trace generators.

All methods accept the 3-D projected coordinate array X_proj and the label vector y, and return lists of fully configured Plotly traces that can be added directly to a Scene3D.

Parameters:

config (VisualizationConfig) – Master configuration; colour palette and render settings are read here.

config#
compute_class_ellipsoids(X_proj: numpy.ndarray, y: numpy.ndarray, *, confidence: float = 0.9, n_grid: int = 40, class_names: Dict | None = None) List[plotly.graph_objects.Surface][source]#

Generate parametric ellipsoid traces for each class.

The ellipsoid is derived from the empirical covariance matrix of the class subset and scaled so that it encloses confidence percent of samples under a multivariate-Gaussian assumption.

Parameters:
  • X_proj (np.ndarray of shape (n_samples, 3)) – Projected data coordinates.

  • y (np.ndarray of shape (n_samples,)) – Class label vector.

  • confidence (float) – Fraction of the distribution to enclose (e.g., 0.90 → 90 % region).

  • n_grid (int) – Resolution of the parametric ellipsoid surface mesh.

  • class_names (dict, optional) – Mapping from class label to display string.

Returns:

traces

Return type:

list of go.Surface

compute_class_centroids(X_proj: numpy.ndarray, y: numpy.ndarray, *, class_names: Dict | None = None) plotly.graph_objects.Scatter3d[source]#

Build a single Scatter3d trace for all class centroids.

Parameters:
  • X_proj (np.ndarray of shape (n_samples, 3))

  • y (np.ndarray of shape (n_samples,))

  • class_names (dict, optional)

Returns:

trace – Star-shaped markers at the class-mean coordinates.

Return type:

go.Scatter3d

compute_convex_hull_traces(X_proj: numpy.ndarray, y: numpy.ndarray, *, class_names: Dict | None = None) List[plotly.graph_objects.Mesh3d][source]#

Generate convex-hull surface traces for each class cluster.

Parameters:
  • X_proj (np.ndarray of shape (n_samples, 3))

  • y (np.ndarray of shape (n_samples,))

  • class_names (dict, optional)

Returns:

traces – One mesh per class, rendered at very low opacity.

Return type:

list of go.Mesh3d

class geolatent.MeshBuilder(resolution: int = 30, padding_fraction: float = 0.12, batch_size: int | None = None)[source]#

Constructs prediction meshes for 3-D decision-surface rendering.

Parameters:
  • resolution (int) – Number of grid points per spatial dimension. Total vertex count equals resolution³. Default 30 provides smooth surfaces for most models with sub-second inference time.

  • padding_fraction (float) – Fractional extension applied beyond the data bounding box on each axis. A value of 0.12 extends the grid by 12 % of the data range on every side, preventing clipping at the edges of the scatter cloud.

  • batch_size (int or None) – Maximum number of points passed to the model in a single predict call. None infers all points at once. Set to e.g. 4096 for memory-constrained models.

Examples

>>> from geolatent.core.mesh_builder import MeshBuilder
>>> builder = MeshBuilder(resolution=25)
>>> mesh = builder.build_prediction_mesh(clf, projector, X_3d)
>>> mesh.probabilities.shape
(15625, 2)
resolution = 30#
padding_fraction = 0.12#
batch_size = None#
build_prediction_mesh(model: object, projector: geolatent.core.projector.DimensionalityProjector, X_proj: numpy.ndarray) PredictionMesh[source]#

Build a prediction mesh for model over the region spanned by X_proj.

Parameters:
  • model (sklearn-compatible estimator) – Must implement at least predict(X).

  • projector (DimensionalityProjector) – Fitted projector that supports inverse_transform (i.e., PCA).

  • X_proj (np.ndarray of shape (n_samples, 3)) – Training data in projected 3-D space, used to define the bounding box.

Returns:

mesh

Return type:

PredictionMesh

Raises:

ValueError – If projector does not support inverse_transform.

class geolatent.PredictionMesh[source]#

Outputs of a decision-surface prediction sweep over a 3-D grid.

x#

Flattened x-coordinates of the grid vertices in projected space.

Type:

np.ndarray of shape (resolution**3,)

y#

Flattened y-coordinates.

Type:

np.ndarray of shape (resolution**3,)

z#

Flattened z-coordinates.

Type:

np.ndarray of shape (resolution**3,)

predictions#

Predicted class index (integer) or regression target at each vertex.

Type:

np.ndarray of shape (resolution**3,)

probabilities#

Per-class probability at each vertex; None when the model does not expose predict_proba.

Type:

np.ndarray of shape (resolution**3, n_classes) or None

grid_shape#

Logical shape (resolution, resolution, resolution) of the 3-D grid.

Type:

tuple of 3 ints

n_classes#

Number of unique predicted class labels (meaningful only for classifiers).

Type:

int

unique_classes#

Sorted array of unique class labels found in predictions.

Type:

np.ndarray

bounds#

Per-axis bounding box: [[xmin, xmax], [ymin, ymax], [zmin, zmax]].

Type:

np.ndarray of shape (3, 2)

is_regression#

True when the model output is treated as a continuous regression value.

Type:

bool

x: numpy.ndarray#
y: numpy.ndarray#
z: numpy.ndarray#
predictions: numpy.ndarray#
probabilities: numpy.ndarray | None#
grid_shape: Tuple[int, int, int]#
n_classes: int#
unique_classes: numpy.ndarray#
bounds: numpy.ndarray#
is_regression: bool = False#
class geolatent.DimensionalityProjector(config: geolatent.config.themes.ProjectionConfig)[source]#

Unified dimensionality-reduction pipeline.

Supports PCA (with invertible transform), t-SNE, and UMAP. The projector follows the fit/transform convention so it can be reused across multiple datasets sharing the same embedding geometry — e.g., projecting a test set using the PCA basis fitted on training data.

Parameters:

config (ProjectionConfig) – Projection hyper-parameters and algorithm selection.

supports_inverse_transform#

True when the underlying algorithm provides a meaningful inverse mapping from the low-dimensional space back to the original feature space. Currently True only for PCA and the identity projection (when the input is already ≤ 3-dimensional).

Type:

bool

is_fitted#

True after fit() or fit_transform() has been called.

Type:

bool

Examples

>>> from geolatent.config.themes import ProjectionConfig
>>> from geolatent.core.projector import DimensionalityProjector
>>> import numpy as np
>>> cfg = ProjectionConfig(method="pca", scale_input=True)
>>> proj = DimensionalityProjector(cfg)
>>> X = np.random.randn(300, 50)
>>> result = proj.fit_transform(X)
>>> result.coordinates.shape
(300, 3)
>>> result.cumulative_variance
0.312...
config#
supports_inverse_transform: bool = False#
is_fitted: bool = False#
fit(X: numpy.ndarray) DimensionalityProjector[source]#

Fit the projection on training data.

Parameters:

X (np.ndarray of shape (n_samples, n_features)) – Input feature matrix. Will be standardised internally if config.scale_input is True.

Returns:

self – The fitted projector instance, supporting method chaining.

Return type:

DimensionalityProjector

transform(X: numpy.ndarray) numpy.ndarray[source]#

Project X using the already-fitted transform.

Parameters:

X (np.ndarray of shape (n_samples, n_features)) – Input feature matrix; must have the same number of features as the data used for fitting.

Returns:

X_proj – 3-D projected coordinates.

Return type:

np.ndarray of shape (n_samples, 3)

fit_transform(X: numpy.ndarray, predict_fn=None, feature_names: List[str] | None = None) ProjectionResult[source]#

Fit the projection and immediately transform the input data.

Parameters:
  • X (np.ndarray of shape (n_samples, n_features)) – Input feature matrix.

  • predict_fn (callable, optional) – Required when config.method == "sensitivity". Any callable that accepts an (n, n_features) array and returns predictions of shape (n,) or (n, n_classes). Works with sklearn, PyTorch, XGBoost, or any custom function.

  • feature_names (list of str, optional) – Names of the input features, used for axis labels.

Returns:

result – Projected coordinates with associated diagnostic metadata.

Return type:

ProjectionResult

inverse_transform(X_proj: numpy.ndarray) numpy.ndarray[source]#

Map projected coordinates back to the original feature space.

This method is only meaningful for PCA and the identity projection. For t-SNE / UMAP, it raises NotImplementedError.

Parameters:

X_proj (np.ndarray of shape (n_points, 3)) – Points in the 3-D projected space.

Returns:

X_original – Best-rank-3 approximation of the corresponding feature vectors in the original (possibly high-dimensional) feature space.

Return type:

np.ndarray of shape (n_points, n_features)

Raises:
class geolatent.ProjectionResult[source]#

Container returned by DimensionalityProjector.fit_transform().

coordinates#

3-D projected coordinates for each input sample.

Type:

np.ndarray of shape (n_samples, 3)

explained_variance_ratio#

Fraction of total variance captured by each principal component. None when a non-PCA method is used.

Type:

np.ndarray of shape (3,) or None

cumulative_variance#

Sum of explained_variance_ratio; convenience scalar indicating how much information is preserved in the projection.

Type:

float or None

method#

Name of the projection algorithm that produced these coordinates.

Type:

str

original_dim#

Number of features in the original (un-projected) space.

Type:

int

axis_labels#

Suggested axis labels for the three projected dimensions.

Type:

list of str

coordinates: numpy.ndarray#
explained_variance_ratio: numpy.ndarray | None#
cumulative_variance: float | None#
method: str#
original_dim: int#
axis_labels: List[str] = ['PC 1', 'PC 2', 'PC 3']#
class geolatent.DataOverlay(config: geolatent.config.themes.VisualizationConfig)[source]#

Generates data-point and structural overlays for 3-D scenes.

Parameters:

config (VisualizationConfig) – Master configuration; colour palette, marker sizes, and opacity values are all sourced from here.

Examples

>>> overlay = DataOverlay(DARK_SCIENTIFIC)
>>> traces = overlay.render_scatter(X_3d, y)
>>> centroid = overlay.render_centroids(X_3d, y)
config#
render_scatter(X_proj: numpy.ndarray, y: numpy.ndarray, *, class_names: Dict | None = None, point_size_override: int | None = None, opacity_override: float | None = None) List[plotly.graph_objects.Scatter3d][source]#

Render a per-class scatter trace for every unique class label.

One go.Scatter3d trace is produced per class, allowing Plotly’s interactive legend to toggle individual classes on and off.

Parameters:
  • X_proj (np.ndarray of shape (n_samples, 3)) – 3-D projected coordinates.

  • y (np.ndarray of shape (n_samples,)) – Class label vector.

  • class_names (dict, optional) – Mapping {label: display_string}.

  • point_size_override (int, optional) – Override config.render.marker_size.

  • opacity_override (float, optional) – Override config.render.scatter_opacity.

Returns:

traces – One trace per unique class, in sorted label order.

Return type:

list of go.Scatter3d

render_centroids(X_proj: numpy.ndarray, y: numpy.ndarray, *, class_names: Dict | None = None) plotly.graph_objects.Scatter3d[source]#

Render diamond-shaped class-centroid markers.

Delegates to compute_class_centroids().

Parameters:
  • X_proj (np.ndarray of shape (n_samples, 3))

  • y (np.ndarray of shape (n_samples,))

  • class_names (dict, optional)

Returns:

trace

Return type:

go.Scatter3d

render_ellipsoids(X_proj: numpy.ndarray, y: numpy.ndarray, *, confidence: float = 0.9, class_names: Dict | None = None) List[plotly.graph_objects.Surface][source]#

Render parametric confidence-ellipsoid surfaces for each class.

Delegates to compute_class_ellipsoids().

Parameters:
  • X_proj (np.ndarray of shape (n_samples, 3))

  • y (np.ndarray of shape (n_samples,))

  • confidence (float) – Confidence level for the Mahalanobis-distance ellipsoid (default 0.90).

  • class_names (dict, optional)

Returns:

traces

Return type:

list of go.Surface

render_convex_hulls(X_proj: numpy.ndarray, y: numpy.ndarray, *, class_names: Dict | None = None) List[plotly.graph_objects.Mesh3d][source]#

Render transparent convex-hull surfaces around each class cluster.

Delegates to compute_convex_hull_traces().

Parameters:
  • X_proj (np.ndarray of shape (n_samples, 3))

  • y (np.ndarray of shape (n_samples,))

  • class_names (dict, optional)

Returns:

traces

Return type:

list of go.Mesh3d

render_trajectory(waypoints: numpy.ndarray, *, name: str = 'Trajectory', color: str | None = None, line_width: int = 4, show_waypoints: bool = True) List[plotly.graph_objects.BaseTraceType][source]#

Render an ordered sequence of waypoints as a 3-D polyline.

Useful for visualising gradient-descent trajectories, attention paths, or other sequential processes in the projected embedding space.

Parameters:
  • waypoints (np.ndarray of shape (n_steps, 3)) – Ordered sequence of 3-D positions.

  • name (str) – Legend label for the trajectory.

  • color (str, optional) – Line colour (hex). Defaults to the first class colour.

  • line_width (int) – Width of the line in pixels.

  • show_waypoints (bool) – Whether to overlay individual step markers.

Returns:

traces

Return type:

list of Plotly traces

class geolatent.Scene3D(config: geolatent.config.themes.VisualizationConfig)[source]#

Stateful 3-D Plotly figure builder with dark-scientific theming.

Parameters:

config (VisualizationConfig) – Master configuration; theme colours, render sizes, and camera settings are all read from here.

Examples

>>> scene = Scene3D(DARK_SCIENTIFIC)
>>> scene.add_trace(some_trace).add_trace(another_trace)
>>> fig = scene.render()
>>> fig.show()
config#
add_trace(trace: plotly.graph_objects.BaseTraceType) Scene3D[source]#

Add a single Plotly trace.

Parameters:

trace (go.BaseTraceType)

Return type:

self

add_traces(traces: Sequence[plotly.graph_objects.BaseTraceType]) Scene3D[source]#

Add multiple Plotly traces at once.

Parameters:

traces (sequence of go.BaseTraceType)

Return type:

self

set_title(title: str) Scene3D[source]#

Set the figure title.

Parameters:

title (str)

Return type:

self

set_axis_labels(labels: List[str]) Scene3D[source]#

Override the three axis labels.

Parameters:

labels (list of 3 str)

Return type:

self

add_variance_annotation(explained_variance_ratio: object) Scene3D[source]#

Append a cumulative explained-variance annotation.

Parameters:

explained_variance_ratio (array-like of shape (3,)) – Per-component explained-variance ratios from PCA.

Return type:

self

add_text_annotation(text: str, *, x: float = 0.99, y: float = 0.99) Scene3D[source]#

Add a free-form text annotation in paper coordinates.

Parameters:
  • text (str) – HTML-formatted annotation text.

  • x (float) – Paper-coordinate position (0–1).

  • y (float) – Paper-coordinate position (0–1).

Return type:

self

render() plotly.graph_objects.Figure[source]#

Apply the dark-scientific layout and return the completed figure.

Returns:

fig – A fully configured Plotly figure ready for fig.show() or fig.write_html().

Return type:

go.Figure

class geolatent.DecisionSurfaceRenderer(config: geolatent.config.themes.VisualizationConfig)[source]#

Renders decision surfaces from a PredictionMesh.

Parameters:

config (VisualizationConfig) – Master configuration; colour palette and surface opacity are read here.

Examples

>>> renderer = DecisionSurfaceRenderer(DARK_SCIENTIFIC)
>>> traces = renderer.render(mesh)
>>> for t in traces:
...     scene.add_trace(t)
config#
render(mesh: geolatent.core.mesh_builder.PredictionMesh, *, class_names: Dict | None = None, show_confidence: bool = True) List[plotly.graph_objects.BaseTraceType][source]#

Auto-select and execute the most appropriate rendering strategy.

Parameters:
  • mesh (PredictionMesh) – Pre-computed prediction mesh from MeshBuilder.

  • class_names (dict, optional) – Mapping from class label to display string.

  • show_confidence (bool) – When True and mesh.probabilities is available, render nested confidence isosurfaces in addition to the boundary shell.

Returns:

traces

Return type:

list of Plotly traces

render_probability_isosurfaces(mesh: geolatent.core.mesh_builder.PredictionMesh, *, class_names: Dict | None = None, show_confidence: bool = True, boundary_threshold: float = 0.5, confidence_thresholds: List[float] | None = None) List[plotly.graph_objects.Isosurface][source]#

Render probability isosurfaces for each class.

For each class c, the decision boundary surface (P(class=c) = 0.5) is rendered as a translucent shell. When show_confidence is True, additional shells at higher probability thresholds convey confidence depth.

Parameters:
  • mesh (PredictionMesh) – Must have probabilities populated.

  • class_names (dict, optional)

  • show_confidence (bool)

  • boundary_threshold (float) – Primary isosurface probability value (default 0.50).

  • confidence_thresholds (list of float, optional) – Additional isosurface levels drawn inside the boundary shell. Defaults to [0.70, 0.85] when show_confidence is True.

Returns:

traces

Return type:

list of go.Isosurface

render_class_volumes(mesh: geolatent.core.mesh_builder.PredictionMesh, *, class_names: Dict | None = None) List[plotly.graph_objects.BaseTraceType][source]#

Render a per-class volume for models without predict_proba.

Maps predicted class indices onto a discrete colour scale and renders the full volumetric class partition as a transparent go.Volume. To give class boundaries a clear visual edge, one go.Isosurface per class boundary is additionally rendered.

Parameters:
Returns:

traces

Return type:

list of Plotly traces

render_regression_field(mesh: geolatent.core.mesh_builder.PredictionMesh) List[plotly.graph_objects.Volume][source]#

Render a continuous regression prediction field as a volumetric trace.

Parameters:

mesh (PredictionMesh) – A mesh whose is_regression flag is True.

Returns:

traces

Return type:

list of go.Volume