Maps from distances, and patterns in three-way tables
Make a map when all you have are distances, keep local neighborhoods with Sammon mapping, and find the few patterns behind a stores × products × months table with CP and Tucker decompositions.
What runs in CodeSplash
- Multidimensional scaling (MDS / PCoA / NMDS) Verified in Python and R
- Tensor decomposition (CP / PARAFAC and Tucker) Verified in Python and R
You will be able to
- Build an MDS map from a distance matrix or a list of pairs
- Explain what Sammon mapping keeps that classical scaling doesn't
- Read a CP component across all three modes at once
- Use the fit and core consistency to choose the number of components
When you only have distances
ReadSome data never come as variables: road distances between cities, how often two products are bought together, a dissimilarity a panel rated. MDSPrincipal coordinates analysisA map whose distances reproduce a chosen dissimilarity as closely as possible, solved exactly by eigen decomposition. needs only the distances, so the Discover map can start from them.
Choose Distances from → Distance matrix when each row is one object and the chosen columns are its distances to every object, in the same order as the rows. Choose Pair list when each row is one pair: from, to and the distance.
Map the cities
In the appClassical scaling (distance matrix) placed 21 rows in 2 dimensions reproducing 86.8% of the positive variance.
- Goodness of fit
- 86.8%
- Stress
- —
Plots
View data
| city | Item | Dimension 1 | Dimension 2 |
|---|---|---|---|
| Athens | Athens | 2290.27 | −1798.80 |
| Barcelona | Barcelona | −825.38 | −546.81 |
| Brussels | Brussels | 59.183 | 367.08 |
| Calais | Calais | −82.846 | 429.91 |
| Cherbourg | Cherbourg | −352.50 | 290.91 |
| Cologne | Cologne | 293.69 | 405.31 |
| Copenhagen | Copenhagen | 681.93 | 1108.64 |
| Geneva | Geneva | −9.423 | −240.41 |
| Gibraltar | Gibraltar | −2048.45 | −642.46 |
| Hamburg | Hamburg | 561.11 | 773.37 |
| Hook of Holland | Hook of Holland | 164.92 | 549.37 |
| Lisbon | Lisbon | −1935.04 | −49.125 |
| Lyons | Lyons | −226.42 | −187.09 |
| Madrid | Madrid | −1423.35 | −305.88 |
| Marseilles | Marseilles | −299.50 | −388.81 |
| Milan | Milan | 260.88 | −416.67 |
| Munich | Munich | 587.68 | −81.182 |
| Paris | Paris | −156.84 | 211.14 |
| Rome | Rome | 709.41 | −1109.37 |
| Stockholm | Stockholm | 839.45 | 1836.79 |
| Vienna | Vienna | 911.23 | −205.93 |
Principal coordinates
| Dimension | Eigenvalue |
|---|---|
| 1 | 1.954e+7 |
| 2 | 1.186e+7 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Multidimensional scaling (MDS / PCoA / NMDS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mds 1.1.0 · spec a455379895bba44c
# Dataset: rep2_eurodist (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("Athens", "Barcelona", "Brussels", "Calais", "Cherbourg", "Cologne", "Copenhagen", "Geneva", "Gibraltar", "Hamburg", "Hook of Holland", "Lisbon", "Lyons", "Madrid", "Marseilles", "Milan", "Munich", "Paris", "Rome", "Stockholm", "Vienna")
LABEL <- "city"
DISTANCE <- "euclidean"
METHOD <- "classical"
# A square dissimilarity matrix: the chosen variables are its columns, one dataset row per object.
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep2_eurodist.parquet", col_select = unique(c(FEATURES, LABEL))), check.names = FALSE)
n_input <- nrow(df)
warnings <- list()
n_missing <- sum(is.na(df[FEATURES]))
if (n_missing > 0) cs_error("CS_E_INVALID_VALUES", column = "The distance matrix", requirement = "complete (no missing distances)", count = n_missing)
mx <- cs_ml_mds_matrix(df[FEATURES], FEATURES)
D <- mx$D
warnings <- c(warnings, as.list(mx$notes))
rows <- seq_len(nrow(df)) - 1L
point_labels <- if (is.null(LABEL)) NULL else { g <- as.character(df[[LABEL]]); g[is.na(g)] <- "(missing)"; g }
if (length(rows) < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "MDS", min = 3, n = length(rows))
# %% Scaling
K <- min(2, length(rows) - 1L)
classical <- cs_ml_pcoa(D, K)
coords <- classical$coords
K <- ncol(coords)
values <- list(n = length(rows), n_variables = length(FEATURES), n_components = K,
gof_abs = classical$gof_abs, gof_pos = classical$gof_pos, n_negative = classical$n_negative,
stress = NaN, iterations = 0L)
for (j in seq_len(K)) values[[sprintf("eigen[%d]", j)]] <- classical$eigen[j]
charts <- list()
if (METHOD == "nmds") {
fit <- cs_ml_nmds(D, coords, max_iter = 200)
coords <- fit$coords
values$stress <- fit$stress
values$iterations <- fit$iterations
show <- cs_ml_even_sample(length(fit$delta), 2000) + 1L
note <- sprintf("Kruskal stress-1 = %.3f", fit$stress)
if (length(show) < length(fit$delta)) note <- paste0(note, sprintf("; %s of %s pairs shown", format(length(show), big.mark = ","), format(length(fit$delta), big.mark = ",")))
charts[[1]] <- cs_chart("shepard", "shepard-diagram", "Shepard diagram", list(
dissimilarity = cs_col("Dissimilarity", fit$delta[show], "numeric"),
distance = cs_col("Map distance", fit$distance[show], "numeric"),
fitted = cs_col("Monotone fit", fit$disparity[show], "numeric")
), note = note)
if (fit$stress > 0.2) warnings <- c(warnings, sprintf("Stress %.2f is high (above 0.2): the map distorts many distances — try more dimensions.", fit$stress))
}
for (j in seq_len(K)) values[[sprintf("coord_check[%d]", j)]] <- cs_ml_checksum(coords[, j], rows)
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.mds/eurodist_matrix_classical/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(K)) emb[[paste0("dim_", j)]] <- coords[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
ARTIFACTS <- list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
# %% Result
MAP_TITLE <- switch(METHOD, nmds = "NMDS map", sammon = "Sammon map", "Principal coordinates")
if (K >= 2) {
groups <- if (is.null(point_labels) || length(unique(point_labels)) > 30) rep("All items", length(rows)) else point_labels
data <- list(
x = cs_col("Dimension 1", coords[, 1], "numeric"),
y = cs_col("Dimension 2", coords[, 2], "numeric"),
cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
)
if (!is.null(point_labels)) data$label <- cs_col("Item", point_labels, "categorical")
charts <- c(list(cs_chart("map", "cluster-scatter", MAP_TITLE, data)), charts)
}
SOURCE <- switch("matrix", features = gsub("_", "–", DISTANCE), matrix = "distance matrix", pairs = "pair list")
WHAT <- if ("matrix" == "pairs") "items" else "rows"
summary <- if (METHOD == "nmds") {
sprintf("Non-metric MDS (%s) placed %d %s in %d dimensions with stress %.3f.", SOURCE, length(rows), WHAT, K, values$stress)
} else if (METHOD == "sammon") {
sprintf("Sammon mapping (%s) placed %d %s in %d dimensions with stress %.4f.", SOURCE, length(rows), WHAT, K, values$stress)
} else {
sprintf("Classical scaling (%s) placed %d %s in %d dimensions reproducing %.1f%% of the positive variance.", SOURCE, length(rows), WHAT, K, 100 * classical$gof_pos)
}
cs_publish(list(
title = "Multidimensional scaling (MDS / PCoA / NMDS)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = list(list(key = "gof_pos", label = "Goodness of fit", value = classical$gof_pos, format = "percent"),
list(key = "stress", label = "Stress", value = values$stress)),
tables = list(list(key = "eigen", title = "Principal coordinates",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"),
list(key = "eigen", label = "Eigenvalue", type = "number")),
rows = lapply(seq_len(K), function(j) list(dimension = j, eigen = classical$eigen[j])))),
charts = charts,
values = values,
warnings = warnings,
artifacts = ARTIFACTS
))
Classical scaling (distance matrix) placed 21 rows in 2 dimensions reproducing 86.8% of the positive variance.
- Goodness of fit
- 86.8%
- Stress
- —
To keep this page light, the plots are shown once, under the R tab.
Principal coordinates
| Dimension | Eigenvalue |
|---|---|
| 1 | 1.954e+7 |
| 2 | 1.186e+7 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multidimensional scaling (MDS / PCoA / NMDS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mds 1.1.0 · spec a455379895bba44c
# Dataset: rep2_eurodist (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.ml import discover_ext as dx
from codesplash.ml import embed as csembed
from codesplash.ml import mds_ext as mdsx
# %% Data
FEATURES = ["Athens", "Barcelona", "Brussels", "Calais", "Cherbourg", "Cologne", "Copenhagen", "Geneva", "Gibraltar", "Hamburg", "Hook of Holland", "Lisbon", "Lyons", "Madrid", "Marseilles", "Milan", "Munich", "Paris", "Rome", "Stockholm", "Vienna"]
LABEL = "city"
DISTANCE = "euclidean"
METHOD = "classical"
# A square dissimilarity matrix: the chosen variables are its columns, one dataset row per object.
df = pd.read_parquet("tests/parity/fixtures/rep2_eurodist.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
n_missing = int(df[FEATURES].isna().to_numpy().sum())
if n_missing:
cs.cs_error("CS_E_INVALID_VALUES", column="The distance matrix", requirement="complete (no missing distances)", count=n_missing)
D, notes = mdsx.matrix_input(df[FEATURES].to_numpy(dtype=float), FEATURES)
warnings += notes
rows = np.arange(len(df))
point_labels = None if LABEL is None else [("(missing)" if pd.isna(v) else str(v)) for v in df[LABEL]]
if len(rows) < 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="MDS", min=3, n=len(rows))
# %% Scaling
K = min(2, len(rows) - 1)
classical = dx.pcoa(D, K)
coords = classical["coords"]
K = coords.shape[1]
values = {
"n": len(rows), "n_variables": len(FEATURES), "n_components": K,
"gof_abs": classical["gof_abs"], "gof_pos": classical["gof_pos"], "n_negative": classical["n_negative"],
"stress": float("nan"), "iterations": 0,
}
for j in range(K):
values[f"eigen[{j + 1}]"] = float(classical["eigen"][j])
charts = []
if METHOD == "nmds":
fit = dx.nmds(D, coords, max_iter=200)
coords = fit["coords"]
values["stress"] = fit["stress"]
values["iterations"] = fit["iterations"]
show = csc.even_sample(len(fit["delta"]), 2000)
charts.append(cs.chart("shepard", "shepard-diagram", "Shepard diagram", {
"dissimilarity": cs.col("Dissimilarity", fit["delta"][show], "numeric"),
"distance": cs.col("Map distance", fit["distance"][show], "numeric"),
"fitted": cs.col("Monotone fit", fit["disparity"][show], "numeric"),
}, note=f"Kruskal stress-1 = {fit['stress']:.3f}" + ("" if len(show) == len(fit["delta"]) else f"; {len(show):,} of {len(fit['delta']):,} pairs shown")))
if fit["stress"] > 0.2:
warnings.append(f"Stress {fit['stress']:.2f} is high (above 0.2): the map distorts many distances — try more dimensions.")
for j in range(K):
values[f"coord_check[{j + 1}]"] = csembed.checksum(coords[:, j], rows)
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.mds/eurodist_matrix_classical/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(K):
emb[f"dim_{j + 1}"] = coords[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
ARTIFACTS = [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}]
# %% Result
MAP_TITLE = {"nmds": "NMDS map", "sammon": "Sammon map"}.get(METHOD, "Principal coordinates")
if K >= 2:
groups = ["All items"] * len(rows) if point_labels is None or len(set(point_labels)) > 30 else point_labels
data = {
"x": cs.col("Dimension 1", coords[:, 0], "numeric"),
"y": cs.col("Dimension 2", coords[:, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", groups, "categorical"),
}
if point_labels is not None:
data["label"] = cs.col("Item", point_labels, "categorical")
charts.insert(0, cs.chart("map", "cluster-scatter", MAP_TITLE, data))
SOURCE = {"features": DISTANCE.replace("_", "–"), "matrix": "distance matrix", "pairs": "pair list"}["matrix"]
WHAT = "items" if "matrix" == "pairs" else "rows"
if METHOD == "nmds":
summary = f"Non-metric MDS ({SOURCE}) placed {len(rows)} {WHAT} in {K} dimensions with stress {values['stress']:.3f}."
elif METHOD == "sammon":
summary = f"Sammon mapping ({SOURCE}) placed {len(rows)} {WHAT} in {K} dimensions with stress {values['stress']:.4f}."
else:
summary = f"Classical scaling ({SOURCE}) placed {len(rows)} {WHAT} in {K} dimensions reproducing {classical['gof_pos']:.1%} of the positive variance."
cs.publish({
"title": "Multidimensional scaling (MDS / PCoA / NMDS)",
"engine": cs.engine_info("numpy", "scikit-learn", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "gof_pos", "label": "Goodness of fit", "value": classical["gof_pos"], "format": "percent"},
{"key": "stress", "label": "Stress", "value": values["stress"]},
],
"tables": [{
"key": "eigen",
"title": "Principal coordinates",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "eigen", "label": "Eigenvalue", "type": "number"}],
"rows": [{"dimension": j + 1, "eigen": float(classical["eigen"][j])} for j in range(K)],
}],
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": ARTIFACTS,
})
Road distances between 21 European cities, as a square matrix. Classical scaling places them in two dimensions that reproduce 86.8% of the positive variance. 9 negative eigenvalues say road distances aren't quite Euclidean: roads wind around mountains and seas.
The same distances entered as pairs give the same map. Non-metric MDS keeps only their order and reaches a stress of 0.0588.
Keeping neighborhoods: Sammon mapping
ReadClassical scaling cares most about the big distances, so nearby cities can be squashed together. Sammon mappingSammon mappingMDS that weights each pair by one over its distance, so small distances — local neighborhoods — are kept best. divides each pair's error by its distance, so small distances count more.
Sammon mapping (distance matrix) placed 21 rows in 2 dimensions with stress 0.0094.
- Goodness of fit
- 86.8%
- Stress
- 0.0094
Plots
View data
| city | Item | Dimension 1 | Dimension 2 |
|---|---|---|---|
| Athens | Athens | 1921.91 | −1830.43 |
| Barcelona | Barcelona | −759.76 | −606.09 |
| Brussels | Brussels | 80.199 | 443.37 |
| Calais | Calais | −106.21 | 512.10 |
| Cherbourg | Cherbourg | −484.41 | 477.30 |
| Cologne | Cologne | 295.33 | 445.05 |
| Copenhagen | Copenhagen | 543.94 | 1091.59 |
| Geneva | Geneva | −7.410 | −269.68 |
| Gibraltar | Gibraltar | −1942.80 | −727.83 |
| Hamburg | Hamburg | 626.72 | 721.55 |
| Hook of Holland | Hook of Holland | 185.86 | 658.29 |
| Lisbon | Lisbon | −1916.64 | −83.584 |
| Lyons | Lyons | −149.49 | −217.71 |
| Madrid | Madrid | −1372.71 | −349.73 |
| Marseilles | Marseilles | −285.26 | −514.73 |
| Milan | Milan | 273.11 | −426.50 |
| Munich | Munich | 569.25 | −106.53 |
| Paris | Paris | −161.49 | 261.15 |
| Rome | Rome | 698.67 | −1023.66 |
| Stockholm | Stockholm | 951.88 | 1716.51 |
| Vienna | Vienna | 1039.31 | −170.44 |
Sammon stress = 0.0094
View data
| Dissimilarity | Map distance | Equal distances |
|---|---|---|
| 3,313 | 2947.94 | 3,313 |
| 2,963 | 2926.10 | 2,963 |
| 3,175 | 3098.50 | 3,175 |
| 3,339 | 3334.07 | 3,339 |
| 2,762 | 2797.07 | 2,762 |
| 3,276 | 3230.63 | 3,276 |
| 2,610 | 2481.57 | 2,610 |
| 4,485 | 4018.92 | 4,485 |
| 2,977 | 2861.84 | 2,977 |
| 3,030 | 3034.40 | 3,030 |
| 4,532 | 4217.34 | 4,532 |
| 2,753 | 2625.18 | 2,753 |
| 3,949 | 3612.06 | 3,949 |
| 2,865 | 2569.57 | 2,865 |
| 2,282 | 2165.54 | 2,282 |
| 2,179 | 2191.24 | 2,179 |
| 3,000 | 2952.17 | 3,000 |
| 817 | 1465.33 | 817 |
| 3,927 | 3677.19 | 3,927 |
| 1,991 | 1880.04 | 1,991 |
| 1,318 | 1344.20 | 1,318 |
| 1,326 | 1295.17 | 1,326 |
| 1,294 | 1117.84 | 1,294 |
| 1,498 | 1489.34 | 1,498 |
| 2,218 | 2140.50 | 2,218 |
| 803 | 824.13 | 803 |
| 1,172 | 1189.29 | 1,172 |
| 2,018 | 1919.62 | 2,018 |
| 1,490 | 1578.87 | 1,490 |
| 1,305 | 1269.40 | 1,305 |
| 645 | 723.38 | 645 |
| 636 | 664.40 | 636 |
| 521 | 483.22 | 521 |
| 1,014 | 1048.37 | 1,014 |
| 1,365 | 1419.79 | 1,365 |
| 1,033 | 1053.58 | 1,033 |
| 1,460 | 1517.03 | 1,460 |
| 2,868 | 2885.16 | 2,868 |
| 1,802 | 1851.06 | 1,802 |
| 204 | 198.67 | 204 |
| 583 | 565.63 | 583 |
| 206 | 215.14 | 206 |
| 966 | 797.03 | 966 |
| 677 | 718.41 | 677 |
| 2,256 | 2337.57 | 2,256 |
| 597 | 613.24 | 597 |
| 172 | 239.49 | 172 |
| 2,084 | 2065.20 | 2,084 |
| 690 | 699.84 | 690 |
| 1,558 | 1655.27 | 1,558 |
| 1,011 | 1025.43 | 1,011 |
| 925 | 891.00 | 925 |
| 747 | 735.91 | 747 |
| 285 | 302.68 | 285 |
| 1,511 | 1592.07 | 1,511 |
| 1,616 | 1542.95 | 1,616 |
| 1,175 | 1138.70 | 1,175 |
| 460 | 379.80 | 460 |
| 409 | 407.10 | 409 |
| 1,136 | 870.92 | 1,136 |
First 60 of 210 rows.
Principal coordinates
| Dimension | Eigenvalue |
|---|---|
| 1 | 1.954e+7 |
| 2 | 1.186e+7 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Multidimensional scaling (MDS / PCoA / NMDS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mds 1.1.0 · spec d17e575e11d18159
# Dataset: rep2_eurodist (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("Athens", "Barcelona", "Brussels", "Calais", "Cherbourg", "Cologne", "Copenhagen", "Geneva", "Gibraltar", "Hamburg", "Hook of Holland", "Lisbon", "Lyons", "Madrid", "Marseilles", "Milan", "Munich", "Paris", "Rome", "Stockholm", "Vienna")
LABEL <- "city"
DISTANCE <- "euclidean"
METHOD <- "sammon"
# A square dissimilarity matrix: the chosen variables are its columns, one dataset row per object.
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep2_eurodist.parquet", col_select = unique(c(FEATURES, LABEL))), check.names = FALSE)
n_input <- nrow(df)
warnings <- list()
n_missing <- sum(is.na(df[FEATURES]))
if (n_missing > 0) cs_error("CS_E_INVALID_VALUES", column = "The distance matrix", requirement = "complete (no missing distances)", count = n_missing)
mx <- cs_ml_mds_matrix(df[FEATURES], FEATURES)
D <- mx$D
warnings <- c(warnings, as.list(mx$notes))
rows <- seq_len(nrow(df)) - 1L
point_labels <- if (is.null(LABEL)) NULL else { g <- as.character(df[[LABEL]]); g[is.na(g)] <- "(missing)"; g }
if (length(rows) < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "MDS", min = 3, n = length(rows))
# %% Scaling
K <- min(2, length(rows) - 1L)
classical <- cs_ml_pcoa(D, K)
coords <- classical$coords
K <- ncol(coords)
values <- list(n = length(rows), n_variables = length(FEATURES), n_components = K,
gof_abs = classical$gof_abs, gof_pos = classical$gof_pos, n_negative = classical$n_negative,
stress = NaN, iterations = 0L)
for (j in seq_len(K)) values[[sprintf("eigen[%d]", j)]] <- classical$eigen[j]
charts <- list()
if (METHOD == "nmds") {
fit <- cs_ml_nmds(D, coords, max_iter = 200)
coords <- fit$coords
values$stress <- fit$stress
values$iterations <- fit$iterations
show <- cs_ml_even_sample(length(fit$delta), 2000) + 1L
note <- sprintf("Kruskal stress-1 = %.3f", fit$stress)
if (length(show) < length(fit$delta)) note <- paste0(note, sprintf("; %s of %s pairs shown", format(length(show), big.mark = ","), format(length(fit$delta), big.mark = ",")))
charts[[1]] <- cs_chart("shepard", "shepard-diagram", "Shepard diagram", list(
dissimilarity = cs_col("Dissimilarity", fit$delta[show], "numeric"),
distance = cs_col("Map distance", fit$distance[show], "numeric"),
fitted = cs_col("Monotone fit", fit$disparity[show], "numeric")
), note = note)
if (fit$stress > 0.2) warnings <- c(warnings, sprintf("Stress %.2f is high (above 0.2): the map distorts many distances — try more dimensions.", fit$stress))
}
if (METHOD == "sammon") {
# Sammon mapping from the classical start with MASS::sammon (the Python engine ports its algorithm).
fit <- cs_ml_sammon(D, coords, niter = 200)
coords <- fit$points
values$stress <- fit$stress
values$iterations <- NaN
up <- which(upper.tri(D), arr.ind = TRUE)
up <- up[order(up[, 1], up[, 2]), , drop = FALSE]
delta <- D[up]
mapd <- sqrt(rowSums((coords[up[, 1], , drop = FALSE] - coords[up[, 2], , drop = FALSE])^2))
show <- cs_ml_even_sample(length(delta), 2000) + 1L
note <- sprintf("Sammon stress = %.4f", fit$stress)
if (length(show) < length(delta)) note <- paste0(note, sprintf("; %s of %s pairs shown", format(length(show), big.mark = ","), format(length(delta), big.mark = ",")))
charts[[length(charts) + 1]] <- cs_chart("shepard", "shepard-diagram", "Shepard diagram", list(
dissimilarity = cs_col("Dissimilarity", delta[show], "numeric"),
distance = cs_col("Map distance", mapd[show], "numeric"),
fitted = cs_col("Equal distances", delta[show], "numeric")
), note = note)
}
for (j in seq_len(K)) values[[sprintf("coord_check[%d]", j)]] <- cs_ml_checksum(coords[, j], rows)
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.mds/eurodist_matrix_sammon/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(K)) emb[[paste0("dim_", j)]] <- coords[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
ARTIFACTS <- list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
# %% Result
MAP_TITLE <- switch(METHOD, nmds = "NMDS map", sammon = "Sammon map", "Principal coordinates")
if (K >= 2) {
groups <- if (is.null(point_labels) || length(unique(point_labels)) > 30) rep("All items", length(rows)) else point_labels
data <- list(
x = cs_col("Dimension 1", coords[, 1], "numeric"),
y = cs_col("Dimension 2", coords[, 2], "numeric"),
cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
)
if (!is.null(point_labels)) data$label <- cs_col("Item", point_labels, "categorical")
charts <- c(list(cs_chart("map", "cluster-scatter", MAP_TITLE, data)), charts)
}
SOURCE <- switch("matrix", features = gsub("_", "–", DISTANCE), matrix = "distance matrix", pairs = "pair list")
WHAT <- if ("matrix" == "pairs") "items" else "rows"
summary <- if (METHOD == "nmds") {
sprintf("Non-metric MDS (%s) placed %d %s in %d dimensions with stress %.3f.", SOURCE, length(rows), WHAT, K, values$stress)
} else if (METHOD == "sammon") {
sprintf("Sammon mapping (%s) placed %d %s in %d dimensions with stress %.4f.", SOURCE, length(rows), WHAT, K, values$stress)
} else {
sprintf("Classical scaling (%s) placed %d %s in %d dimensions reproducing %.1f%% of the positive variance.", SOURCE, length(rows), WHAT, K, 100 * classical$gof_pos)
}
cs_publish(list(
title = "Multidimensional scaling (MDS / PCoA / NMDS)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = list(list(key = "gof_pos", label = "Goodness of fit", value = classical$gof_pos, format = "percent"),
list(key = "stress", label = "Stress", value = values$stress)),
tables = list(list(key = "eigen", title = "Principal coordinates",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"),
list(key = "eigen", label = "Eigenvalue", type = "number")),
rows = lapply(seq_len(K), function(j) list(dimension = j, eigen = classical$eigen[j])))),
charts = charts,
values = values,
warnings = warnings,
artifacts = ARTIFACTS
))
Sammon mapping (distance matrix) placed 21 rows in 2 dimensions with stress 0.0094.
- Goodness of fit
- 86.8%
- Stress
- 0.0094
To keep this page light, the plots are shown once, under the R tab.
Principal coordinates
| Dimension | Eigenvalue |
|---|---|
| 1 | 1.954e+7 |
| 2 | 1.186e+7 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multidimensional scaling (MDS / PCoA / NMDS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mds 1.1.0 · spec d17e575e11d18159
# Dataset: rep2_eurodist (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.ml import discover_ext as dx
from codesplash.ml import embed as csembed
from codesplash.ml import mds_ext as mdsx
# %% Data
FEATURES = ["Athens", "Barcelona", "Brussels", "Calais", "Cherbourg", "Cologne", "Copenhagen", "Geneva", "Gibraltar", "Hamburg", "Hook of Holland", "Lisbon", "Lyons", "Madrid", "Marseilles", "Milan", "Munich", "Paris", "Rome", "Stockholm", "Vienna"]
LABEL = "city"
DISTANCE = "euclidean"
METHOD = "sammon"
# A square dissimilarity matrix: the chosen variables are its columns, one dataset row per object.
df = pd.read_parquet("tests/parity/fixtures/rep2_eurodist.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
n_missing = int(df[FEATURES].isna().to_numpy().sum())
if n_missing:
cs.cs_error("CS_E_INVALID_VALUES", column="The distance matrix", requirement="complete (no missing distances)", count=n_missing)
D, notes = mdsx.matrix_input(df[FEATURES].to_numpy(dtype=float), FEATURES)
warnings += notes
rows = np.arange(len(df))
point_labels = None if LABEL is None else [("(missing)" if pd.isna(v) else str(v)) for v in df[LABEL]]
if len(rows) < 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="MDS", min=3, n=len(rows))
# %% Scaling
K = min(2, len(rows) - 1)
classical = dx.pcoa(D, K)
coords = classical["coords"]
K = coords.shape[1]
values = {
"n": len(rows), "n_variables": len(FEATURES), "n_components": K,
"gof_abs": classical["gof_abs"], "gof_pos": classical["gof_pos"], "n_negative": classical["n_negative"],
"stress": float("nan"), "iterations": 0,
}
for j in range(K):
values[f"eigen[{j + 1}]"] = float(classical["eigen"][j])
charts = []
if METHOD == "nmds":
fit = dx.nmds(D, coords, max_iter=200)
coords = fit["coords"]
values["stress"] = fit["stress"]
values["iterations"] = fit["iterations"]
show = csc.even_sample(len(fit["delta"]), 2000)
charts.append(cs.chart("shepard", "shepard-diagram", "Shepard diagram", {
"dissimilarity": cs.col("Dissimilarity", fit["delta"][show], "numeric"),
"distance": cs.col("Map distance", fit["distance"][show], "numeric"),
"fitted": cs.col("Monotone fit", fit["disparity"][show], "numeric"),
}, note=f"Kruskal stress-1 = {fit['stress']:.3f}" + ("" if len(show) == len(fit["delta"]) else f"; {len(show):,} of {len(fit['delta']):,} pairs shown")))
if fit["stress"] > 0.2:
warnings.append(f"Stress {fit['stress']:.2f} is high (above 0.2): the map distorts many distances — try more dimensions.")
if METHOD == "sammon":
# Sammon mapping from the classical start: MASS's algorithm (the R engine calls MASS::sammon).
fit = mdsx.sammon(D, coords, niter=200)
coords = fit["points"]
values["stress"] = fit["stress"]
values["iterations"] = float("nan")
iu = np.triu_indices(len(rows), 1)
delta = D[iu]
mapd = np.sqrt(np.sum((coords[iu[0]] - coords[iu[1]]) ** 2, axis=1))
show = csc.even_sample(len(delta), 2000)
charts.append(cs.chart("shepard", "shepard-diagram", "Shepard diagram", {
"dissimilarity": cs.col("Dissimilarity", delta[show], "numeric"),
"distance": cs.col("Map distance", mapd[show], "numeric"),
"fitted": cs.col("Equal distances", delta[show], "numeric"),
}, note=f"Sammon stress = {fit['stress']:.4f}" + ("" if len(show) == len(delta) else f"; {len(show):,} of {len(delta):,} pairs shown")))
for j in range(K):
values[f"coord_check[{j + 1}]"] = csembed.checksum(coords[:, j], rows)
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.mds/eurodist_matrix_sammon/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(K):
emb[f"dim_{j + 1}"] = coords[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
ARTIFACTS = [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}]
# %% Result
MAP_TITLE = {"nmds": "NMDS map", "sammon": "Sammon map"}.get(METHOD, "Principal coordinates")
if K >= 2:
groups = ["All items"] * len(rows) if point_labels is None or len(set(point_labels)) > 30 else point_labels
data = {
"x": cs.col("Dimension 1", coords[:, 0], "numeric"),
"y": cs.col("Dimension 2", coords[:, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", groups, "categorical"),
}
if point_labels is not None:
data["label"] = cs.col("Item", point_labels, "categorical")
charts.insert(0, cs.chart("map", "cluster-scatter", MAP_TITLE, data))
SOURCE = {"features": DISTANCE.replace("_", "–"), "matrix": "distance matrix", "pairs": "pair list"}["matrix"]
WHAT = "items" if "matrix" == "pairs" else "rows"
if METHOD == "nmds":
summary = f"Non-metric MDS ({SOURCE}) placed {len(rows)} {WHAT} in {K} dimensions with stress {values['stress']:.3f}."
elif METHOD == "sammon":
summary = f"Sammon mapping ({SOURCE}) placed {len(rows)} {WHAT} in {K} dimensions with stress {values['stress']:.4f}."
else:
summary = f"Classical scaling ({SOURCE}) placed {len(rows)} {WHAT} in {K} dimensions reproducing {classical['gof_pos']:.1%} of the positive variance."
cs.publish({
"title": "Multidimensional scaling (MDS / PCoA / NMDS)",
"engine": cs.engine_info("numpy", "scikit-learn", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "gof_pos", "label": "Goodness of fit", "value": classical["gof_pos"], "format": "percent"},
{"key": "stress", "label": "Stress", "value": values["stress"]},
],
"tables": [{
"key": "eigen",
"title": "Principal coordinates",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "eigen", "label": "Eigenvalue", "type": "number"}],
"rows": [{"dimension": j + 1, "eigen": float(classical["eigen"][j])} for j in range(K)],
}],
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": ARTIFACTS,
})
Its stress, 0.00941, is on Sammon's own scale; compare it only with other Sammon maps. The Shepard diagram plots each pair's map distance against its real distance, so you can see which pairs the map stretches.
Make a guess
PredictPredict first
A sales table of 8 stores × 6 products × 5 months was built from two patterns plus a little noise. You fit CP with two components. What core consistency do you expect?
Reveal
About 100%. Two components match how the table was made, so the CP model fits its own assumptions: core consistency is 100%. With more components than the data support, it drops far below 50%.
Three-way tables
ReadA table of stores × products × months is an array with three modes. Flattening it to two (store-months by products) hides patterns that need all three at once.
CPCP decompositionWrites a three-way table as a sum of r rank-one parts; each part has one factor per mode (e.g. store, product, month). writes the array as a sum of a few components. Each component has a factor for every mode, so one reads as "these stores sell these products, more in these months".
CP decomposition with 2 components of the 8 × 6 × 5 (store × product × month) array of sales: fit 1.000 (relative error 0.017), core consistency 100%.
- Fit
- 0.9997
- Relative error
- 0.0165
- Core consistency (%)
- 99.958
Plots
View data
| Factor | Value | store | Loading |
|---|---|---|---|
| Factor 1 | 0.57 | Store 1 | 0.5717 |
| Factor 2 | 0.75 | Store 1 | 0.7543 |
| Factor 1 | 0.32 | Store 2 | 0.3237 |
| Factor 2 | 0.31 | Store 2 | 0.3092 |
| Factor 1 | 0.22 | Store 3 | 0.2200 |
| Factor 2 | 0.24 | Store 3 | 0.2399 |
| Factor 1 | 0.21 | Store 4 | 0.2099 |
| Factor 2 | 0.49 | Store 4 | 0.4862 |
| Factor 1 | 0.25 | Store 5 | 0.2525 |
| Factor 2 | 0.19 | Store 5 | 0.1908 |
| Factor 1 | 0.39 | Store 6 | 0.3889 |
| Factor 2 | 0.00 | Store 6 | 5.183e-5 |
| Factor 1 | 0.24 | Store 7 | 0.2355 |
| Factor 2 | 0.06 | Store 7 | 0.0591 |
| Factor 1 | 0.45 | Store 8 | 0.4533 |
| Factor 2 | 0.04 | Store 8 | 0.0396 |
View data
| Factor | Value | product | Loading |
|---|---|---|---|
| Factor 1 | 0.59 | P1 | 0.5911 |
| Factor 2 | 0.47 | P1 | 0.4696 |
| Factor 1 | 0.37 | P2 | 0.3734 |
| Factor 2 | 0.68 | P2 | 0.6792 |
| Factor 1 | 0.18 | P3 | 0.1763 |
| Factor 2 | 0.07 | P3 | 0.0660 |
| Factor 1 | 0.48 | P4 | 0.4781 |
| Factor 2 | 0.56 | P4 | 0.5582 |
| Factor 1 | 0.40 | P5 | 0.3966 |
| Factor 2 | 0.03 | P5 | 0.0331 |
| Factor 1 | 0.31 | P6 | 0.3070 |
| Factor 2 | 0.03 | P6 | 0.0344 |
View data
| Factor | Value | month | Loading |
|---|---|---|---|
| Factor 1 | 0.29 | Jan | 0.2915 |
| Factor 2 | 0.71 | Jan | 0.7082 |
| Factor 1 | 0.36 | Feb | 0.3634 |
| Factor 2 | 0.52 | Feb | 0.5188 |
| Factor 1 | 0.44 | Mar | 0.4365 |
| Factor 2 | 0.36 | Mar | 0.3594 |
| Factor 1 | 0.51 | Apr | 0.5074 |
| Factor 2 | 0.25 | Apr | 0.2521 |
| Factor 1 | 0.58 | May | 0.5788 |
| Factor 2 | 0.19 | May | 0.1914 |
View data
| Components | Fit | Gain in fit |
|---|---|---|
| 1 | 0.9979 | 0.9979 |
| 2 | 0.9997 | 0.0018 |
| 3 | 0.9998 | 4.787e-5 |
| 4 | 0.9998 | 3.727e-5 |
| 5 | 0.9999 | 4.347e-5 |
Components
| Component | Weight λ | Share of Σλ² |
|---|---|---|
| 1 | 39.096 | 99.3% |
| 2 | 3.252 | 0.7% |
Choosing the number of components
| Components | Fit | Core consistency (%) |
|---|---|---|
| 1 | 0.9979 | 100 |
| 2 | 0.9997 | 99.958 |
| 3 | 0.9998 | 42.090 |
| 4 | 0.9998 | −688.09 |
| 5 | 0.9999 | −4751.09 |
Factors: store
| store | Factor 1 | Factor 2 |
|---|---|---|
| Store 1 | 0.5717 | 0.7543 |
| Store 2 | 0.3237 | 0.3092 |
| Store 3 | 0.2200 | 0.2399 |
| Store 4 | 0.2099 | 0.4862 |
| Store 5 | 0.2525 | 0.1908 |
| Store 6 | 0.3889 | 5.183e-5 |
| Store 7 | 0.2355 | 0.0591 |
| Store 8 | 0.4533 | 0.0396 |
Factors: product
| product | Factor 1 | Factor 2 |
|---|---|---|
| P1 | 0.5911 | 0.4696 |
| P2 | 0.3734 | 0.6792 |
| P3 | 0.1763 | 0.0660 |
| P4 | 0.4781 | 0.5582 |
| P5 | 0.3966 | 0.0331 |
| P6 | 0.3070 | 0.0344 |
Factors: month
| month | Factor 1 | Factor 2 |
|---|---|---|
| Jan | 0.2915 | 0.7082 |
| Feb | 0.3634 | 0.5188 |
| Mar | 0.4365 | 0.3594 |
| Apr | 0.5074 | 0.2521 |
| May | 0.5788 | 0.1914 |
- Fit = 1 − Σ(x − x̂)² / Σx² over the observed cells (not centered); CP factors have unit length, weights λ carry the scale, components are sorted by λ, and each component's first two factors have their largest entry positive; core consistency (Bro & Kiers 2003) near 100% supports a CP model, below 50% suggests too many components. From the HOSVD start; stops when the fit changes by less than 1e-08 or after 500 sweeps (54 used).
The exact R script · R R version 4.5.1 (2025-06-13)
# Tensor decomposition (CP / PARAFAC and Tucker)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.tensor 1.0.0 · spec 3145cb4a1b15023a
# Dataset: rep2_tensor (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep2_tensor.parquet", col_select = c("store", "product", "month", "sales")))
n_input <- nrow(df)
df[["store"]] <- factor(df[["store"]], levels = c("Store 1", "Store 2", "Store 3", "Store 4", "Store 5", "Store 6", "Store 7", "Store 8")) # stored level order
df[["product"]] <- factor(df[["product"]], levels = c("P1", "P2", "P3", "P4", "P5", "P6")) # stored level order
df[["month"]] <- factor(df[["month"]], levels = c("Jan", "Feb", "Mar", "Apr", "May")) # stored level order
df <- df[stats::complete.cases(df[c("store", "product", "month", "sales")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("store", "product", "month", "sales")) # infinite values stop the run (registry/errors.yaml)
# %% Tensor
# A three-way table in long form (one row per cell: three mode columns and a value) decomposed by CP
# (CANDECOMP/PARAFAC, Harshman 1970; Carroll & Chang 1970) or Tucker (Tucker 1966; HOOI, De Lathauwer et al.
# 2000). Missing cells are filled with the current reconstruction each sweep (EM-ALS).
MODES <- c("store", "product", "month")
VALUE <- "sales"
METHOD <- "cp" # cp | tucker
RANK <- as.integer(2)
RANKS <- as.integer(c(2, 2, 2))
SCAN <- TRUE
MAX_ITER <- as.integer(500)
TOL <- 1e-8
if (length(unique(MODES)) < 3) cs_error("CS_E_INVALID_OPTION", option = "The three modes", allowed = "three different columns", value = paste(MODES, collapse = ", "))
levs <- lapply(MODES, function(m) levels(df[[m]]))
dims <- lengths(levs)
for (t in 1:3) cs_check_groups(levs[[t]], MODES[t], minimum = 2)
if (prod(dims) > 200000) cs_error("CS_E_UNDEFINED", what = "Tensor decomposition", reason = sprintf("the dense array would have %s cells (at most 200,000)", format(prod(dims), big.mark = ",")))
cs_check_not_constant(df[[VALUE]], VALUE)
pv <- cs_tn_pivot(as.integer(df[[MODES[1]]]), as.integer(df[[MODES[2]]]), as.integer(df[[MODES[3]]]), as.double(df[[VALUE]]), dims)
X <- pv$X
mask <- pv$mask
n_cells <- as.integer(prod(dims))
n_obs <- sum(mask)
if (pv$dup > 0) warnings <- c(warnings, sprintf("%d cell(s) had more than one row; each uses the mean of its values.", pv$dup))
if (n_obs < 0.5 * n_cells) cs_error("CS_E_UNDEFINED", what = "Tensor decomposition", reason = sprintf("only %d of %d cells have a value (at least half are needed)", n_obs, n_cells))
if (n_obs < n_cells) warnings <- c(warnings, sprintf("%d of %d cells have no value; they are filled with the model's reconstruction at each sweep.", n_cells - n_obs, n_cells))
cap <- min(dims)
if (METHOD == "cp" && RANK > cap) cs_error("CS_E_INVALID_OPTION", option = "Components", allowed = sprintf("at most %d (the smallest mode's number of levels)", cap), value = as.character(RANK))
if (METHOD == "tucker") {
for (t in 1:3) if (RANKS[t] > dims[t]) cs_error("CS_E_INVALID_OPTION", option = sprintf("Factors for %s", MODES[t]), allowed = sprintf("at most %d", dims[t]), value = as.character(RANKS[t]))
}
# %% Decompose
values <- list(n_cells = n_cells, n_observed = n_obs, n_mode1 = dims[1], n_mode2 = dims[2], n_mode3 = dims[3],
rank = NaN, rank1 = NaN, rank2 = NaN, rank3 = NaN, corcondia = NaN, core_top_share = NaN)
tables <- list()
charts <- list()
scan_rows <- list()
if (METHOD == "cp") {
fit <- cs_tn_cp_als(X, mask, RANK, MAX_ITER, TOL)
factors <- list(fit$A, fit$B, fit$C)
cc <- if (RANK >= 2) cs_tn_corcondia(fit$filled, fit$A, fit$B, fit$C, fit$lam) else 100
values <- utils::modifyList(values, list(rank = RANK, fit = fit$fit, rel_error = fit$rel_error, iterations = fit$iterations, converged = fit$converged, corcondia = cc))
for (r in seq_len(RANK)) values[[sprintf("lambda[%d]", r)]] <- fit$lam[r]
tables[[length(tables) + 1]] <- list(key = "components", title = "Components",
columns = list(list(key = "component", label = "Component", type = "integer"), list(key = "lambda", label = "Weight λ", type = "number"),
list(key = "share", label = "Share of Σλ²", type = "percent")),
rows = lapply(seq_len(RANK), function(r) list(component = r, lambda = fit$lam[r], share = fit$lam[r]^2 / sum(fit$lam^2))))
if (SCAN) {
for (r_ in seq_len(if (cap <= 6) cap else 6)) {
f_ <- if (r_ == RANK) fit else cs_tn_cp_als(X, mask, r_, MAX_ITER, TOL)
cc_ <- if (r_ >= 2) (if (r_ == RANK) cc else cs_tn_corcondia(f_$filled, f_$A, f_$B, f_$C, f_$lam)) else 100
scan_rows[[length(scan_rows) + 1]] <- list(rank = r_, fit = f_$fit, corcondia = cc_)
}
tables[[length(tables) + 1]] <- list(key = "scan", title = "Choosing the number of components",
columns = list(list(key = "rank", label = "Components", type = "integer"), list(key = "fit", label = "Fit", type = "number"),
list(key = "corcondia", label = "Core consistency (%)", type = "number")),
rows = scan_rows)
for (row in scan_rows) {
values[[sprintf("scan_fit[%d]", row$rank)]] <- row$fit
values[[sprintf("scan_corcondia[%d]", row$rank)]] <- row$corcondia
}
}
if (RANK >= 2 && cc < 50) warnings <- c(warnings, sprintf("Core consistency is %.0f%% (below 50%%): %d components may be too many for a CP model — compare fewer.", cc, RANK))
} else {
fit <- cs_tn_tucker_hooi(X, mask, RANKS, MAX_ITER, TOL)
factors <- fit$U
G <- fit$G
values <- utils::modifyList(values, list(rank1 = RANKS[1], rank2 = RANKS[2], rank3 = RANKS[3], fit = fit$fit, rel_error = fit$rel_error,
iterations = fit$iterations, converged = fit$converged))
total_g <- sum(G^2)
core_rows <- list()
for (a in seq_len(RANKS[1])) for (b in seq_len(RANKS[2])) for (c in seq_len(RANKS[3])) {
core_rows[[length(core_rows) + 1]] <- list(a = a, b = b, c = c, value = G[a, b, c], share = if (total_g > 0) G[a, b, c]^2 / total_g else NaN)
}
core_rows <- core_rows[order(-vapply(core_rows, function(row) row$share, 0), method = "radix")]
values$core_top_share <- core_rows[[1]]$share
tables[[length(tables) + 1]] <- list(key = "core", title = "Core tensor (largest cells first)",
columns = list(list(key = "a", label = sprintf("%s factor", MODES[1]), type = "integer"), list(key = "b", label = sprintf("%s factor", MODES[2]), type = "integer"),
list(key = "c", label = sprintf("%s factor", MODES[3]), type = "integer"), list(key = "value", label = "Core value", type = "number"),
list(key = "share", label = "Share of Σ core²", type = "percent")),
rows = core_rows)
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-29333/discover.tensor/sales-cp/out-r")
artifacts <- list()
for (t in 1:3) {
m <- MODES[t]; lv <- levs[[t]]; F <- factors[[t]]
fdf <- data.frame(level = lv)
for (r in seq_len(ncol(F))) fdf[[sprintf("factor_%d", r)]] <- F[, r]
path <- file.path(out, sprintf("factors_%s.parquet", m))
nanoparquet::write_parquet(fdf, path)
artifacts[[t]] <- list(key = sprintf("factors_%s", m), path = path, format = "parquet")
rows_ <- rep(lv, each = ncol(F))
cols_ <- rep(sprintf("Factor %d", seq_len(ncol(F))), times = length(lv))
vals_ <- as.vector(t(F))
charts[[length(charts) + 1]] <- cs_chart(sprintf("factors_%s", m), "matrix-heatmap", sprintf("%s: factor loadings", m), list(
row = cs_col(m, rows_, "categorical"), col = cs_col("Factor", cols_, "categorical"),
value = cs_col("Loading", vals_), label = cs_col("Value", sprintf("%.2f", vals_), "categorical")))
tables[[length(tables) + 1]] <- list(key = sprintf("factors_%s", m), title = sprintf("Factors: %s", m),
columns = c(list(list(key = "level", label = m, type = "string")), lapply(seq_len(ncol(F)), function(r) list(key = sprintf("f%d", r), label = sprintf("Factor %d", r), type = "number"))),
rows = lapply(seq_along(lv), function(i) { row <- list(level = lv[i]); for (r in seq_len(ncol(F))) row[[sprintf("f%d", r)]] <- F[i, r]; row }))
}
if (length(scan_rows)) {
fits <- vapply(scan_rows, function(row) row$fit, 0)
charts[[length(charts) + 1]] <- cs_chart("scan", "scree-plot", "Fit by number of components", list(
component = cs_col("Components", as.double(vapply(scan_rows, function(row) row$rank, 0))),
variance = cs_col("Gain in fit", diff(c(0, fits))),
cumulative = cs_col("Fit", fits)))
}
for (t in 1:3) values[[sprintf("factor_check[%s]", MODES[t])]] <- sum(seq_len(nrow(factors[[t]])) * factors[[t]])
# %% Result
shape <- sprintf("%d × %d × %d (%s)", dims[1], dims[2], dims[3], paste(MODES, collapse = " × "))
summary <- if (METHOD == "cp") {
paste0(sprintf("CP decomposition with %d component%s of the %s array of %s: fit %.3f (relative error %.3f)", RANK, if (RANK != 1) "s" else "", shape, VALUE, fit$fit, fit$rel_error),
if (RANK >= 2) sprintf(", core consistency %.0f%%", cc) else "", ".")
} else {
sprintf("Tucker decomposition with %d × %d × %d factors of the %s array of %s: fit %.3f (relative error %.3f).", RANKS[1], RANKS[2], RANKS[3], shape, VALUE, fit$fit, fit$rel_error)
}
if (!fit$converged) warnings <- c(warnings, cs_warning("CS_W_NO_CONVERGENCE", what = sprintf("The %s decomposition", if (METHOD == "cp") "CP" else "Tucker")))
cs_publish(list(
title = "Tensor decomposition (CP / PARAFAC and Tucker)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n_obs,
summary = summary,
statistics = c(list(list(key = "fit", label = "Fit", value = fit$fit), list(key = "rel_error", label = "Relative error", value = fit$rel_error)),
if (METHOD == "cp") list(list(key = "corcondia", label = "Core consistency (%)", value = values$corcondia)) else list()),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
notes = list(paste0("Fit = 1 − Σ(x − x̂)² / Σx² over the observed cells (not centered); ",
if (METHOD == "cp") "CP factors have unit length, weights λ carry the scale, components are sorted by λ, and each component's first two factors have their largest entry positive; core consistency (Bro & Kiers 2003) near 100% supports a CP model, below 50% suggests too many components. "
else "Tucker factors are orthonormal (each column's largest entry positive) and the core tensor carries the scale. ",
sprintf("From the HOSVD start; stops when the fit changes by less than %s or after %d sweeps (%d used).", format(TOL), MAX_ITER, as.integer(fit$iterations)))),
artifacts = artifacts
))
CP decomposition with 2 components of the 8 × 6 × 5 (store × product × month) array of sales: fit 1.000 (relative error 0.017), core consistency 100%.
- Fit
- 0.9997
- Relative error
- 0.0165
- Core consistency (%)
- 99.958
To keep this page light, the plots are shown once, under the R tab.
Components
| Component | Weight λ | Share of Σλ² |
|---|---|---|
| 1 | 39.096 | 99.3% |
| 2 | 3.252 | 0.7% |
Choosing the number of components
| Components | Fit | Core consistency (%) |
|---|---|---|
| 1 | 0.9979 | 100 |
| 2 | 0.9997 | 99.958 |
| 3 | 0.9998 | 42.090 |
| 4 | 0.9998 | −688.09 |
| 5 | 0.9999 | −4751.09 |
Factors: store
| store | Factor 1 | Factor 2 |
|---|---|---|
| Store 1 | 0.5717 | 0.7543 |
| Store 2 | 0.3237 | 0.3092 |
| Store 3 | 0.2200 | 0.2399 |
| Store 4 | 0.2099 | 0.4862 |
| Store 5 | 0.2525 | 0.1908 |
| Store 6 | 0.3889 | 5.183e-5 |
| Store 7 | 0.2355 | 0.0591 |
| Store 8 | 0.4533 | 0.0396 |
Factors: product
| product | Factor 1 | Factor 2 |
|---|---|---|
| P1 | 0.5911 | 0.4696 |
| P2 | 0.3734 | 0.6792 |
| P3 | 0.1763 | 0.0660 |
| P4 | 0.4781 | 0.5582 |
| P5 | 0.3966 | 0.0331 |
| P6 | 0.3070 | 0.0344 |
Factors: month
| month | Factor 1 | Factor 2 |
|---|---|---|
| Jan | 0.2915 | 0.7082 |
| Feb | 0.3634 | 0.5188 |
| Mar | 0.4365 | 0.3594 |
| Apr | 0.5074 | 0.2521 |
| May | 0.5788 | 0.1914 |
- Fit = 1 − Σ(x − x̂)² / Σx² over the observed cells (not centered); CP factors have unit length, weights λ carry the scale, components are sorted by λ, and each component's first two factors have their largest entry positive; core consistency (Bro & Kiers 2003) near 100% supports a CP model, below 50% suggests too many components. From the HOSVD start; stops when the fit changes by less than 1e-08 or after 500 sweeps (54 used).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Tensor decomposition (CP / PARAFAC and Tucker)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.tensor 1.0.0 · spec 3145cb4a1b15023a
# Dataset: rep2_tensor (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash import ml as csml
from codesplash.ml import tensor as tn
# %% Data
df = pd.read_parquet("tests/parity/fixtures/rep2_tensor.parquet", columns=["store", "product", "month", "sales"])
n_input = len(df)
df["store"] = pd.Categorical(df["store"], categories=["Store 1", "Store 2", "Store 3", "Store 4", "Store 5", "Store 6", "Store 7", "Store 8"]) # stored level order
df["product"] = pd.Categorical(df["product"], categories=["P1", "P2", "P3", "P4", "P5", "P6"]) # stored level order
df["month"] = pd.Categorical(df["month"], categories=["Jan", "Feb", "Mar", "Apr", "May"]) # stored level order
df = df.dropna(subset=["store", "product", "month", "sales"]) # listwise deletion over the analysis columns
df["store"] = df["store"].cat.remove_unused_categories()
df["product"] = df["product"].cat.remove_unused_categories()
df["month"] = df["month"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["store", "product", "month", "sales"]) # infinite values stop the run (registry/errors.yaml)
# %% Tensor
# A three-way table in long form (one row per cell: three mode columns and a value) decomposed by CP
# (CANDECOMP/PARAFAC, Harshman 1970; Carroll & Chang 1970) or Tucker (Tucker 1966; HOOI, De Lathauwer et al.
# 2000). Missing cells are filled with the current reconstruction each sweep (EM-ALS).
MODES = ["store", "product", "month"]
VALUE = "sales"
METHOD = "cp" # cp | tucker
RANK = int(2)
RANKS = [int(2), int(2), int(2)]
SCAN = True
MAX_ITER = int(500)
TOL = 1e-8
if len(set(MODES)) < 3:
cs.cs_error("CS_E_INVALID_OPTION", option="The three modes", allowed="three different columns", value=", ".join(MODES))
levels = [[str(x) for x in df[m].cat.categories] for m in MODES]
dims = [len(lv) for lv in levels]
for m, lv in zip(MODES, levels):
check_groups(lv, m, minimum=2)
if np.prod(dims) > 200000:
cs.cs_error("CS_E_UNDEFINED", what="Tensor decomposition", reason=f"the dense array would have {int(np.prod(dims)):,} cells (at most 200,000)")
check_not_constant(df[VALUE], VALUE)
X, mask, n_dup = tn.pivot(*(df[m].cat.codes.to_numpy() for m in MODES), df[VALUE].to_numpy(dtype=float), dims)
n_cells = int(np.prod(dims))
n_obs = int(mask.sum())
if n_dup:
warnings.append(f"{n_dup} cell(s) had more than one row; each uses the mean of its values.")
if n_obs < 0.5 * n_cells:
cs.cs_error("CS_E_UNDEFINED", what="Tensor decomposition", reason=f"only {n_obs} of {n_cells} cells have a value (at least half are needed)")
if n_obs < n_cells:
warnings.append(f"{n_cells - n_obs} of {n_cells} cells have no value; they are filled with the model's reconstruction at each sweep.")
cap = min(dims)
if METHOD == "cp" and RANK > cap:
cs.cs_error("CS_E_INVALID_OPTION", option="Components", allowed=f"at most {cap} (the smallest mode's number of levels)", value=str(RANK))
if METHOD == "tucker":
for m, r_, d_ in zip(MODES, RANKS, dims):
if r_ > d_:
cs.cs_error("CS_E_INVALID_OPTION", option=f"Factors for {m}", allowed=f"at most {d_}", value=str(r_))
# %% Decompose
values = {"n_cells": n_cells, "n_observed": n_obs, "n_mode1": dims[0], "n_mode2": dims[1], "n_mode3": dims[2],
"rank": float("nan"), "rank1": float("nan"), "rank2": float("nan"), "rank3": float("nan"), "corcondia": float("nan"), "core_top_share": float("nan")}
tables = []
charts = []
scan_rows = []
if METHOD == "cp":
fit = tn.cp_als(X, mask, RANK, MAX_ITER, TOL)
factors = [fit["A"], fit["B"], fit["C"]]
cc = tn.corcondia(fit["filled"], fit["A"], fit["B"], fit["C"], fit["lam"]) if RANK >= 2 else 100.0
values.update({"rank": RANK, "fit": fit["fit"], "rel_error": fit["rel_error"], "iterations": fit["iterations"],
"converged": fit["converged"], "corcondia": cc})
for r in range(RANK):
values[f"lambda[{r + 1}]"] = float(fit["lam"][r])
tables.append({"key": "components", "title": "Components",
"columns": [{"key": "component", "label": "Component", "type": "integer"},
{"key": "lambda", "label": "Weight λ", "type": "number"},
{"key": "share", "label": "Share of Σλ²", "type": "percent"}],
"rows": [{"component": r + 1, "lambda": float(fit["lam"][r]), "share": float(fit["lam"][r] ** 2 / np.sum(fit["lam"] ** 2))} for r in range(RANK)]})
if SCAN:
for r_ in range(1, cap + 1 if cap <= 6 else 7):
f_ = fit if r_ == RANK else tn.cp_als(X, mask, r_, MAX_ITER, TOL)
cc_ = (cc if r_ == RANK else tn.corcondia(f_["filled"], f_["A"], f_["B"], f_["C"], f_["lam"])) if r_ >= 2 else 100.0
scan_rows.append({"rank": r_, "fit": f_["fit"], "corcondia": cc_})
tables.append({"key": "scan", "title": "Choosing the number of components",
"columns": [{"key": "rank", "label": "Components", "type": "integer"}, {"key": "fit", "label": "Fit", "type": "number"},
{"key": "corcondia", "label": "Core consistency (%)", "type": "number"}],
"rows": scan_rows})
for row in scan_rows:
values[f"scan_fit[{row['rank']}]"] = row["fit"]
values[f"scan_corcondia[{row['rank']}]"] = row["corcondia"]
if RANK >= 2 and cc < 50:
warnings.append(f"Core consistency is {cc:.0f}% (below 50%): {RANK} components may be too many for a CP model — compare fewer.")
else:
fit = tn.tucker_hooi(X, mask, RANKS, MAX_ITER, TOL)
factors = fit["U"]
G = fit["G"]
values.update({"rank1": RANKS[0], "rank2": RANKS[1], "rank3": RANKS[2], "fit": fit["fit"], "rel_error": fit["rel_error"],
"iterations": fit["iterations"], "converged": fit["converged"]})
core_rows = []
total_g = float(np.sum(G ** 2))
for a in range(RANKS[0]):
for b in range(RANKS[1]):
for c in range(RANKS[2]):
core_rows.append({"cell": f"{a + 1}·{b + 1}·{c + 1}", "a": a + 1, "b": b + 1, "c": c + 1, "value": float(G[a, b, c]),
"share": float(G[a, b, c] ** 2 / total_g) if total_g > 0 else float("nan")})
core_rows.sort(key=lambda row: -row["share"])
values["core_top_share"] = core_rows[0]["share"]
tables.append({"key": "core", "title": "Core tensor (largest cells first)",
"columns": [{"key": "a", "label": f"{MODES[0]} factor", "type": "integer"}, {"key": "b", "label": f"{MODES[1]} factor", "type": "integer"},
{"key": "c", "label": f"{MODES[2]} factor", "type": "integer"}, {"key": "value", "label": "Core value", "type": "number"},
{"key": "share", "label": "Share of Σ core²", "type": "percent"}],
"rows": [{k_: row[k_] for k_ in ("a", "b", "c", "value", "share")} for row in core_rows]})
values["missing_share"] = n_dropped / n_input if n_input else 0.0
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-29333/discover.tensor/sales-cp/out-python")
artifacts = []
for m, lv, F in zip(MODES, levels, factors):
fdf = pd.DataFrame({"level": lv})
for r in range(F.shape[1]):
fdf[f"factor_{r + 1}"] = F[:, r]
path = os.path.join(out, f"factors_{m}.parquet")
fdf.to_parquet(path, index=False)
artifacts.append({"key": f"factors_{m}", "path": path, "format": "parquet"})
rows_, cols_, vals_ = [], [], []
for i, name in enumerate(lv):
for r in range(F.shape[1]):
rows_.append(name); cols_.append(f"Factor {r + 1}"); vals_.append(float(F[i, r]))
charts.append(cs.chart(f"factors_{m}", "matrix-heatmap", f"{m}: factor loadings", {
"row": cs.col(m, rows_, "categorical"), "col": cs.col("Factor", cols_, "categorical"),
"value": cs.col("Loading", np.array(vals_)), "label": cs.col("Value", [f"{v:.2f}" for v in vals_], "categorical")}))
tables.append({"key": f"factors_{m}", "title": f"Factors: {m}",
"columns": [{"key": "level", "label": m, "type": "string"}] + [{"key": f"f{r + 1}", "label": f"Factor {r + 1}", "type": "number"} for r in range(F.shape[1])],
"rows": [{"level": name, **{f"f{r + 1}": float(F[i, r]) for r in range(F.shape[1])}} for i, name in enumerate(lv)]})
if scan_rows:
fits = np.array([row["fit"] for row in scan_rows])
charts.append(cs.chart("scan", "scree-plot", "Fit by number of components", {
"component": cs.col("Components", np.array([row["rank"] for row in scan_rows], dtype=float)),
"variance": cs.col("Gain in fit", np.diff(np.concatenate([[0.0], fits]))),
"cumulative": cs.col("Fit", fits)}))
for m, F in zip(MODES, factors):
values[f"factor_check[{m}]"] = float(np.sum(np.arange(1, F.shape[0] + 1)[:, None] * F))
# %% Result
shape = f"{dims[0]} × {dims[1]} × {dims[2]} ({' × '.join(MODES)})"
if METHOD == "cp":
summary = (f"CP decomposition with {RANK} component{'s' if RANK != 1 else ''} of the {shape} array of {VALUE}: fit {fit['fit']:.3f} "
f"(relative error {fit['rel_error']:.3f})" + (f", core consistency {cc:.0f}%" if RANK >= 2 else "") + ".")
else:
summary = (f"Tucker decomposition with {RANKS[0]} × {RANKS[1]} × {RANKS[2]} factors of the {shape} array of {VALUE}: fit {fit['fit']:.3f} "
f"(relative error {fit['rel_error']:.3f}).")
if not fit["converged"]:
warnings.append(cs.cs_warning("CS_W_NO_CONVERGENCE", what=f"The {'CP' if METHOD == 'cp' else 'Tucker'} decomposition"))
cs.publish({
"title": "Tensor decomposition (CP / PARAFAC and Tucker)",
"engine": cs.engine_info("numpy", "pandas"),
"n": n_obs,
"summary": summary,
"statistics": [{"key": "fit", "label": "Fit", "value": fit["fit"]}, {"key": "rel_error", "label": "Relative error", "value": fit["rel_error"]}]
+ ([{"key": "corcondia", "label": "Core consistency (%)", "value": values["corcondia"]}] if METHOD == "cp" else []),
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"notes": ["Fit = 1 − Σ(x − x̂)² / Σx² over the observed cells (not centered); "
+ ("CP factors have unit length, weights λ carry the scale, components are sorted by λ, and each component's first two factors have their largest entry positive; "
"core consistency (Bro & Kiers 2003) near 100% supports a CP model, below 50% suggests too many components. "
if METHOD == "cp" else "Tucker factors are orthonormal (each column's largest entry positive) and the core tensor carries the scale. ")
+ f"From the HOSVD start; stops when the fit changes by less than {TOL:g} or after {MAX_ITER} sweeps ({fit['iterations']} used)."],
"artifacts": artifacts,
})
Two components reach a fit of 1.00. The scan table fits up to five components, so you see where the fit stops improving and core consistency collapses. Save factor tables stores each mode's factors as a dataset.
Tucker: a factor count per mode
ReadTuckerTucker decompositionWrites a three-way table as a small core tensor times one factor matrix per mode; each mode can keep its own number of factors. gives each mode its own number of factors and a small core that links them. It's more flexible, but its factors are a basis rather than unique patterns, so read the core's largest cells.
Tucker decomposition with 2 × 3 × 2 factors of the 8 × 6 × 5 (store × product × month) array of sales: fit 1.000 (relative error 0.016).
- Fit
- 0.9997
- Relative error
- 0.0163
Plots
View data
| Factor | Value | store | Loading |
|---|---|---|---|
| Factor 1 | 0.59 | Store 1 | 0.5888 |
| Factor 2 | 0.47 | Store 1 | 0.4707 |
| Factor 1 | 0.33 | Store 2 | 0.3269 |
| Factor 2 | 0.08 | Store 2 | 0.0845 |
| Factor 1 | 0.22 | Store 3 | 0.2238 |
| Factor 2 | 0.10 | Store 3 | 0.1033 |
| Factor 1 | 0.23 | Store 4 | 0.2277 |
| Factor 2 | 0.50 | Store 4 | 0.4996 |
| Factor 1 | 0.25 | Store 5 | 0.2522 |
| Factor 2 | -0.01 | Store 5 | −0.0137 |
| Factor 1 | 0.37 | Store 6 | 0.3722 |
| Factor 2 | -0.48 | Store 6 | −0.4768 |
| Factor 1 | 0.23 | Store 7 | 0.2286 |
| Factor 2 | -0.20 | Store 7 | −0.1976 |
| Factor 1 | 0.44 | Store 8 | 0.4360 |
| Factor 2 | -0.49 | Store 8 | −0.4944 |
View data
| Factor | Value | product | Loading |
|---|---|---|---|
| Factor 1 | 0.59 | P1 | 0.5896 |
| Factor 2 | -0.06 | P1 | −0.0586 |
| Factor 3 | -0.01 | P1 | −0.0070 |
| Factor 1 | 0.39 | P2 | 0.3923 |
| Factor 2 | 0.65 | P2 | 0.6546 |
| Factor 3 | 0.22 | P2 | 0.2188 |
| Factor 1 | 0.17 | P3 | 0.1721 |
| Factor 2 | -0.15 | P3 | −0.1516 |
| Factor 3 | 0.89 | P3 | 0.8949 |
| Factor 1 | 0.49 | P4 | 0.4861 |
| Factor 2 | 0.28 | P4 | 0.2758 |
| Factor 3 | -0.35 | P4 | −0.3533 |
| Factor 1 | 0.38 | P5 | 0.3811 |
| Factor 2 | -0.55 | P5 | −0.5491 |
| Factor 3 | -0.05 | P5 | −0.0470 |
| Factor 1 | 0.30 | P6 | 0.2954 |
| Factor 2 | -0.41 | P6 | −0.4093 |
| Factor 3 | -0.16 | P6 | −0.1557 |
View data
| Factor | Value | month | Loading |
|---|---|---|---|
| Factor 1 | 0.32 | Jan | 0.3170 |
| Factor 2 | 0.77 | Jan | 0.7693 |
| Factor 1 | 0.38 | Feb | 0.3757 |
| Factor 2 | 0.37 | Feb | 0.3650 |
| Factor 1 | 0.44 | Mar | 0.4371 |
| Factor 2 | 0.01 | Mar | 0.0130 |
| Factor 1 | 0.50 | Apr | 0.4991 |
| Factor 2 | -0.26 | Apr | −0.2609 |
| Factor 1 | 0.56 | May | 0.5641 |
| Factor 2 | -0.45 | May | −0.4547 |
Core tensor (largest cells first)
| store factor | product factor | month factor | Core value | Share of Σ core² |
|---|---|---|---|---|
| 1 | 1 | 1 | 40.798 | 99.8% |
| 2 | 1 | 2 | 1.044 | 0.1% |
| 2 | 2 | 1 | 0.8996 | 0.0% |
| 1 | 2 | 2 | 0.8355 | 0.0% |
| 2 | 2 | 2 | 0.6078 | 0.0% |
| 1 | 3 | 2 | −0.0831 | 0.0% |
| 2 | 3 | 1 | 0.0563 | 0.0% |
| 2 | 3 | 2 | 0.0309 | 0.0% |
| 1 | 2 | 1 | −0.0150 | 0.0% |
| 1 | 1 | 2 | −0.0128 | 0.0% |
| 2 | 1 | 1 | −0.0117 | 0.0% |
| 1 | 3 | 1 | −0.0008 | 0.0% |
Factors: store
| store | Factor 1 | Factor 2 |
|---|---|---|
| Store 1 | 0.5888 | 0.4707 |
| Store 2 | 0.3269 | 0.0845 |
| Store 3 | 0.2238 | 0.1033 |
| Store 4 | 0.2277 | 0.4996 |
| Store 5 | 0.2522 | −0.0137 |
| Store 6 | 0.3722 | −0.4768 |
| Store 7 | 0.2286 | −0.1976 |
| Store 8 | 0.4360 | −0.4944 |
Factors: product
| product | Factor 1 | Factor 2 | Factor 3 |
|---|---|---|---|
| P1 | 0.5896 | −0.0586 | −0.0070 |
| P2 | 0.3923 | 0.6546 | 0.2188 |
| P3 | 0.1721 | −0.1516 | 0.8949 |
| P4 | 0.4861 | 0.2758 | −0.3533 |
| P5 | 0.3811 | −0.5491 | −0.0470 |
| P6 | 0.2954 | −0.4093 | −0.1557 |
Factors: month
| month | Factor 1 | Factor 2 |
|---|---|---|
| Jan | 0.3170 | 0.7693 |
| Feb | 0.3757 | 0.3650 |
| Mar | 0.4371 | 0.0130 |
| Apr | 0.4991 | −0.2609 |
| May | 0.5641 | −0.4547 |
- Fit = 1 − Σ(x − x̂)² / Σx² over the observed cells (not centered); Tucker factors are orthonormal (each column's largest entry positive) and the core tensor carries the scale. From the HOSVD start; stops when the fit changes by less than 1e-08 or after 500 sweeps (2 used).
The exact R script · R R version 4.5.1 (2025-06-13)
# Tensor decomposition (CP / PARAFAC and Tucker)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.tensor 1.0.0 · spec b93656926f36566c
# Dataset: rep2_tensor (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep2_tensor.parquet", col_select = c("store", "product", "month", "sales")))
n_input <- nrow(df)
df[["store"]] <- factor(df[["store"]], levels = c("Store 1", "Store 2", "Store 3", "Store 4", "Store 5", "Store 6", "Store 7", "Store 8")) # stored level order
df[["product"]] <- factor(df[["product"]], levels = c("P1", "P2", "P3", "P4", "P5", "P6")) # stored level order
df[["month"]] <- factor(df[["month"]], levels = c("Jan", "Feb", "Mar", "Apr", "May")) # stored level order
df <- df[stats::complete.cases(df[c("store", "product", "month", "sales")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("store", "product", "month", "sales")) # infinite values stop the run (registry/errors.yaml)
# %% Tensor
# A three-way table in long form (one row per cell: three mode columns and a value) decomposed by CP
# (CANDECOMP/PARAFAC, Harshman 1970; Carroll & Chang 1970) or Tucker (Tucker 1966; HOOI, De Lathauwer et al.
# 2000). Missing cells are filled with the current reconstruction each sweep (EM-ALS).
MODES <- c("store", "product", "month")
VALUE <- "sales"
METHOD <- "tucker" # cp | tucker
RANK <- as.integer(2)
RANKS <- as.integer(c(2, 3, 2))
SCAN <- TRUE
MAX_ITER <- as.integer(500)
TOL <- 1e-8
if (length(unique(MODES)) < 3) cs_error("CS_E_INVALID_OPTION", option = "The three modes", allowed = "three different columns", value = paste(MODES, collapse = ", "))
levs <- lapply(MODES, function(m) levels(df[[m]]))
dims <- lengths(levs)
for (t in 1:3) cs_check_groups(levs[[t]], MODES[t], minimum = 2)
if (prod(dims) > 200000) cs_error("CS_E_UNDEFINED", what = "Tensor decomposition", reason = sprintf("the dense array would have %s cells (at most 200,000)", format(prod(dims), big.mark = ",")))
cs_check_not_constant(df[[VALUE]], VALUE)
pv <- cs_tn_pivot(as.integer(df[[MODES[1]]]), as.integer(df[[MODES[2]]]), as.integer(df[[MODES[3]]]), as.double(df[[VALUE]]), dims)
X <- pv$X
mask <- pv$mask
n_cells <- as.integer(prod(dims))
n_obs <- sum(mask)
if (pv$dup > 0) warnings <- c(warnings, sprintf("%d cell(s) had more than one row; each uses the mean of its values.", pv$dup))
if (n_obs < 0.5 * n_cells) cs_error("CS_E_UNDEFINED", what = "Tensor decomposition", reason = sprintf("only %d of %d cells have a value (at least half are needed)", n_obs, n_cells))
if (n_obs < n_cells) warnings <- c(warnings, sprintf("%d of %d cells have no value; they are filled with the model's reconstruction at each sweep.", n_cells - n_obs, n_cells))
cap <- min(dims)
if (METHOD == "cp" && RANK > cap) cs_error("CS_E_INVALID_OPTION", option = "Components", allowed = sprintf("at most %d (the smallest mode's number of levels)", cap), value = as.character(RANK))
if (METHOD == "tucker") {
for (t in 1:3) if (RANKS[t] > dims[t]) cs_error("CS_E_INVALID_OPTION", option = sprintf("Factors for %s", MODES[t]), allowed = sprintf("at most %d", dims[t]), value = as.character(RANKS[t]))
}
# %% Decompose
values <- list(n_cells = n_cells, n_observed = n_obs, n_mode1 = dims[1], n_mode2 = dims[2], n_mode3 = dims[3],
rank = NaN, rank1 = NaN, rank2 = NaN, rank3 = NaN, corcondia = NaN, core_top_share = NaN)
tables <- list()
charts <- list()
scan_rows <- list()
if (METHOD == "cp") {
fit <- cs_tn_cp_als(X, mask, RANK, MAX_ITER, TOL)
factors <- list(fit$A, fit$B, fit$C)
cc <- if (RANK >= 2) cs_tn_corcondia(fit$filled, fit$A, fit$B, fit$C, fit$lam) else 100
values <- utils::modifyList(values, list(rank = RANK, fit = fit$fit, rel_error = fit$rel_error, iterations = fit$iterations, converged = fit$converged, corcondia = cc))
for (r in seq_len(RANK)) values[[sprintf("lambda[%d]", r)]] <- fit$lam[r]
tables[[length(tables) + 1]] <- list(key = "components", title = "Components",
columns = list(list(key = "component", label = "Component", type = "integer"), list(key = "lambda", label = "Weight λ", type = "number"),
list(key = "share", label = "Share of Σλ²", type = "percent")),
rows = lapply(seq_len(RANK), function(r) list(component = r, lambda = fit$lam[r], share = fit$lam[r]^2 / sum(fit$lam^2))))
if (SCAN) {
for (r_ in seq_len(if (cap <= 6) cap else 6)) {
f_ <- if (r_ == RANK) fit else cs_tn_cp_als(X, mask, r_, MAX_ITER, TOL)
cc_ <- if (r_ >= 2) (if (r_ == RANK) cc else cs_tn_corcondia(f_$filled, f_$A, f_$B, f_$C, f_$lam)) else 100
scan_rows[[length(scan_rows) + 1]] <- list(rank = r_, fit = f_$fit, corcondia = cc_)
}
tables[[length(tables) + 1]] <- list(key = "scan", title = "Choosing the number of components",
columns = list(list(key = "rank", label = "Components", type = "integer"), list(key = "fit", label = "Fit", type = "number"),
list(key = "corcondia", label = "Core consistency (%)", type = "number")),
rows = scan_rows)
for (row in scan_rows) {
values[[sprintf("scan_fit[%d]", row$rank)]] <- row$fit
values[[sprintf("scan_corcondia[%d]", row$rank)]] <- row$corcondia
}
}
if (RANK >= 2 && cc < 50) warnings <- c(warnings, sprintf("Core consistency is %.0f%% (below 50%%): %d components may be too many for a CP model — compare fewer.", cc, RANK))
} else {
fit <- cs_tn_tucker_hooi(X, mask, RANKS, MAX_ITER, TOL)
factors <- fit$U
G <- fit$G
values <- utils::modifyList(values, list(rank1 = RANKS[1], rank2 = RANKS[2], rank3 = RANKS[3], fit = fit$fit, rel_error = fit$rel_error,
iterations = fit$iterations, converged = fit$converged))
total_g <- sum(G^2)
core_rows <- list()
for (a in seq_len(RANKS[1])) for (b in seq_len(RANKS[2])) for (c in seq_len(RANKS[3])) {
core_rows[[length(core_rows) + 1]] <- list(a = a, b = b, c = c, value = G[a, b, c], share = if (total_g > 0) G[a, b, c]^2 / total_g else NaN)
}
core_rows <- core_rows[order(-vapply(core_rows, function(row) row$share, 0), method = "radix")]
values$core_top_share <- core_rows[[1]]$share
tables[[length(tables) + 1]] <- list(key = "core", title = "Core tensor (largest cells first)",
columns = list(list(key = "a", label = sprintf("%s factor", MODES[1]), type = "integer"), list(key = "b", label = sprintf("%s factor", MODES[2]), type = "integer"),
list(key = "c", label = sprintf("%s factor", MODES[3]), type = "integer"), list(key = "value", label = "Core value", type = "number"),
list(key = "share", label = "Share of Σ core²", type = "percent")),
rows = core_rows)
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-29333/discover.tensor/sales-tucker/out-r")
artifacts <- list()
for (t in 1:3) {
m <- MODES[t]; lv <- levs[[t]]; F <- factors[[t]]
fdf <- data.frame(level = lv)
for (r in seq_len(ncol(F))) fdf[[sprintf("factor_%d", r)]] <- F[, r]
path <- file.path(out, sprintf("factors_%s.parquet", m))
nanoparquet::write_parquet(fdf, path)
artifacts[[t]] <- list(key = sprintf("factors_%s", m), path = path, format = "parquet")
rows_ <- rep(lv, each = ncol(F))
cols_ <- rep(sprintf("Factor %d", seq_len(ncol(F))), times = length(lv))
vals_ <- as.vector(t(F))
charts[[length(charts) + 1]] <- cs_chart(sprintf("factors_%s", m), "matrix-heatmap", sprintf("%s: factor loadings", m), list(
row = cs_col(m, rows_, "categorical"), col = cs_col("Factor", cols_, "categorical"),
value = cs_col("Loading", vals_), label = cs_col("Value", sprintf("%.2f", vals_), "categorical")))
tables[[length(tables) + 1]] <- list(key = sprintf("factors_%s", m), title = sprintf("Factors: %s", m),
columns = c(list(list(key = "level", label = m, type = "string")), lapply(seq_len(ncol(F)), function(r) list(key = sprintf("f%d", r), label = sprintf("Factor %d", r), type = "number"))),
rows = lapply(seq_along(lv), function(i) { row <- list(level = lv[i]); for (r in seq_len(ncol(F))) row[[sprintf("f%d", r)]] <- F[i, r]; row }))
}
if (length(scan_rows)) {
fits <- vapply(scan_rows, function(row) row$fit, 0)
charts[[length(charts) + 1]] <- cs_chart("scan", "scree-plot", "Fit by number of components", list(
component = cs_col("Components", as.double(vapply(scan_rows, function(row) row$rank, 0))),
variance = cs_col("Gain in fit", diff(c(0, fits))),
cumulative = cs_col("Fit", fits)))
}
for (t in 1:3) values[[sprintf("factor_check[%s]", MODES[t])]] <- sum(seq_len(nrow(factors[[t]])) * factors[[t]])
# %% Result
shape <- sprintf("%d × %d × %d (%s)", dims[1], dims[2], dims[3], paste(MODES, collapse = " × "))
summary <- if (METHOD == "cp") {
paste0(sprintf("CP decomposition with %d component%s of the %s array of %s: fit %.3f (relative error %.3f)", RANK, if (RANK != 1) "s" else "", shape, VALUE, fit$fit, fit$rel_error),
if (RANK >= 2) sprintf(", core consistency %.0f%%", cc) else "", ".")
} else {
sprintf("Tucker decomposition with %d × %d × %d factors of the %s array of %s: fit %.3f (relative error %.3f).", RANKS[1], RANKS[2], RANKS[3], shape, VALUE, fit$fit, fit$rel_error)
}
if (!fit$converged) warnings <- c(warnings, cs_warning("CS_W_NO_CONVERGENCE", what = sprintf("The %s decomposition", if (METHOD == "cp") "CP" else "Tucker")))
cs_publish(list(
title = "Tensor decomposition (CP / PARAFAC and Tucker)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n_obs,
summary = summary,
statistics = c(list(list(key = "fit", label = "Fit", value = fit$fit), list(key = "rel_error", label = "Relative error", value = fit$rel_error)),
if (METHOD == "cp") list(list(key = "corcondia", label = "Core consistency (%)", value = values$corcondia)) else list()),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
notes = list(paste0("Fit = 1 − Σ(x − x̂)² / Σx² over the observed cells (not centered); ",
if (METHOD == "cp") "CP factors have unit length, weights λ carry the scale, components are sorted by λ, and each component's first two factors have their largest entry positive; core consistency (Bro & Kiers 2003) near 100% supports a CP model, below 50% suggests too many components. "
else "Tucker factors are orthonormal (each column's largest entry positive) and the core tensor carries the scale. ",
sprintf("From the HOSVD start; stops when the fit changes by less than %s or after %d sweeps (%d used).", format(TOL), MAX_ITER, as.integer(fit$iterations)))),
artifacts = artifacts
))
Tucker decomposition with 2 × 3 × 2 factors of the 8 × 6 × 5 (store × product × month) array of sales: fit 1.000 (relative error 0.016).
- Fit
- 0.9997
- Relative error
- 0.0163
To keep this page light, the plots are shown once, under the R tab.
Core tensor (largest cells first)
| store factor | product factor | month factor | Core value | Share of Σ core² |
|---|---|---|---|---|
| 1 | 1 | 1 | 40.798 | 99.8% |
| 2 | 1 | 2 | 1.044 | 0.1% |
| 2 | 2 | 1 | 0.8996 | 0.0% |
| 1 | 2 | 2 | 0.8355 | 0.0% |
| 2 | 2 | 2 | 0.6078 | 0.0% |
| 1 | 3 | 2 | −0.0831 | 0.0% |
| 2 | 3 | 1 | 0.0563 | 0.0% |
| 2 | 3 | 2 | 0.0309 | 0.0% |
| 1 | 2 | 1 | −0.0150 | 0.0% |
| 1 | 1 | 2 | −0.0128 | 0.0% |
| 2 | 1 | 1 | −0.0117 | 0.0% |
| 1 | 3 | 1 | −0.0008 | 0.0% |
Factors: store
| store | Factor 1 | Factor 2 |
|---|---|---|
| Store 1 | 0.5888 | 0.4707 |
| Store 2 | 0.3269 | 0.0845 |
| Store 3 | 0.2238 | 0.1033 |
| Store 4 | 0.2277 | 0.4996 |
| Store 5 | 0.2522 | −0.0137 |
| Store 6 | 0.3722 | −0.4768 |
| Store 7 | 0.2286 | −0.1976 |
| Store 8 | 0.4360 | −0.4944 |
Factors: product
| product | Factor 1 | Factor 2 | Factor 3 |
|---|---|---|---|
| P1 | 0.5896 | −0.0586 | −0.0070 |
| P2 | 0.3923 | 0.6546 | 0.2188 |
| P3 | 0.1721 | −0.1516 | 0.8949 |
| P4 | 0.4861 | 0.2758 | −0.3533 |
| P5 | 0.3811 | −0.5491 | −0.0470 |
| P6 | 0.2954 | −0.4093 | −0.1557 |
Factors: month
| month | Factor 1 | Factor 2 |
|---|---|---|
| Jan | 0.3170 | 0.7693 |
| Feb | 0.3757 | 0.3650 |
| Mar | 0.4371 | 0.0130 |
| Apr | 0.4991 | −0.2609 |
| May | 0.5641 | −0.4547 |
- Fit = 1 − Σ(x − x̂)² / Σx² over the observed cells (not centered); Tucker factors are orthonormal (each column's largest entry positive) and the core tensor carries the scale. From the HOSVD start; stops when the fit changes by less than 1e-08 or after 500 sweeps (2 used).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Tensor decomposition (CP / PARAFAC and Tucker)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.tensor 1.0.0 · spec b93656926f36566c
# Dataset: rep2_tensor (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash import ml as csml
from codesplash.ml import tensor as tn
# %% Data
df = pd.read_parquet("tests/parity/fixtures/rep2_tensor.parquet", columns=["store", "product", "month", "sales"])
n_input = len(df)
df["store"] = pd.Categorical(df["store"], categories=["Store 1", "Store 2", "Store 3", "Store 4", "Store 5", "Store 6", "Store 7", "Store 8"]) # stored level order
df["product"] = pd.Categorical(df["product"], categories=["P1", "P2", "P3", "P4", "P5", "P6"]) # stored level order
df["month"] = pd.Categorical(df["month"], categories=["Jan", "Feb", "Mar", "Apr", "May"]) # stored level order
df = df.dropna(subset=["store", "product", "month", "sales"]) # listwise deletion over the analysis columns
df["store"] = df["store"].cat.remove_unused_categories()
df["product"] = df["product"].cat.remove_unused_categories()
df["month"] = df["month"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["store", "product", "month", "sales"]) # infinite values stop the run (registry/errors.yaml)
# %% Tensor
# A three-way table in long form (one row per cell: three mode columns and a value) decomposed by CP
# (CANDECOMP/PARAFAC, Harshman 1970; Carroll & Chang 1970) or Tucker (Tucker 1966; HOOI, De Lathauwer et al.
# 2000). Missing cells are filled with the current reconstruction each sweep (EM-ALS).
MODES = ["store", "product", "month"]
VALUE = "sales"
METHOD = "tucker" # cp | tucker
RANK = int(2)
RANKS = [int(2), int(3), int(2)]
SCAN = True
MAX_ITER = int(500)
TOL = 1e-8
if len(set(MODES)) < 3:
cs.cs_error("CS_E_INVALID_OPTION", option="The three modes", allowed="three different columns", value=", ".join(MODES))
levels = [[str(x) for x in df[m].cat.categories] for m in MODES]
dims = [len(lv) for lv in levels]
for m, lv in zip(MODES, levels):
check_groups(lv, m, minimum=2)
if np.prod(dims) > 200000:
cs.cs_error("CS_E_UNDEFINED", what="Tensor decomposition", reason=f"the dense array would have {int(np.prod(dims)):,} cells (at most 200,000)")
check_not_constant(df[VALUE], VALUE)
X, mask, n_dup = tn.pivot(*(df[m].cat.codes.to_numpy() for m in MODES), df[VALUE].to_numpy(dtype=float), dims)
n_cells = int(np.prod(dims))
n_obs = int(mask.sum())
if n_dup:
warnings.append(f"{n_dup} cell(s) had more than one row; each uses the mean of its values.")
if n_obs < 0.5 * n_cells:
cs.cs_error("CS_E_UNDEFINED", what="Tensor decomposition", reason=f"only {n_obs} of {n_cells} cells have a value (at least half are needed)")
if n_obs < n_cells:
warnings.append(f"{n_cells - n_obs} of {n_cells} cells have no value; they are filled with the model's reconstruction at each sweep.")
cap = min(dims)
if METHOD == "cp" and RANK > cap:
cs.cs_error("CS_E_INVALID_OPTION", option="Components", allowed=f"at most {cap} (the smallest mode's number of levels)", value=str(RANK))
if METHOD == "tucker":
for m, r_, d_ in zip(MODES, RANKS, dims):
if r_ > d_:
cs.cs_error("CS_E_INVALID_OPTION", option=f"Factors for {m}", allowed=f"at most {d_}", value=str(r_))
# %% Decompose
values = {"n_cells": n_cells, "n_observed": n_obs, "n_mode1": dims[0], "n_mode2": dims[1], "n_mode3": dims[2],
"rank": float("nan"), "rank1": float("nan"), "rank2": float("nan"), "rank3": float("nan"), "corcondia": float("nan"), "core_top_share": float("nan")}
tables = []
charts = []
scan_rows = []
if METHOD == "cp":
fit = tn.cp_als(X, mask, RANK, MAX_ITER, TOL)
factors = [fit["A"], fit["B"], fit["C"]]
cc = tn.corcondia(fit["filled"], fit["A"], fit["B"], fit["C"], fit["lam"]) if RANK >= 2 else 100.0
values.update({"rank": RANK, "fit": fit["fit"], "rel_error": fit["rel_error"], "iterations": fit["iterations"],
"converged": fit["converged"], "corcondia": cc})
for r in range(RANK):
values[f"lambda[{r + 1}]"] = float(fit["lam"][r])
tables.append({"key": "components", "title": "Components",
"columns": [{"key": "component", "label": "Component", "type": "integer"},
{"key": "lambda", "label": "Weight λ", "type": "number"},
{"key": "share", "label": "Share of Σλ²", "type": "percent"}],
"rows": [{"component": r + 1, "lambda": float(fit["lam"][r]), "share": float(fit["lam"][r] ** 2 / np.sum(fit["lam"] ** 2))} for r in range(RANK)]})
if SCAN:
for r_ in range(1, cap + 1 if cap <= 6 else 7):
f_ = fit if r_ == RANK else tn.cp_als(X, mask, r_, MAX_ITER, TOL)
cc_ = (cc if r_ == RANK else tn.corcondia(f_["filled"], f_["A"], f_["B"], f_["C"], f_["lam"])) if r_ >= 2 else 100.0
scan_rows.append({"rank": r_, "fit": f_["fit"], "corcondia": cc_})
tables.append({"key": "scan", "title": "Choosing the number of components",
"columns": [{"key": "rank", "label": "Components", "type": "integer"}, {"key": "fit", "label": "Fit", "type": "number"},
{"key": "corcondia", "label": "Core consistency (%)", "type": "number"}],
"rows": scan_rows})
for row in scan_rows:
values[f"scan_fit[{row['rank']}]"] = row["fit"]
values[f"scan_corcondia[{row['rank']}]"] = row["corcondia"]
if RANK >= 2 and cc < 50:
warnings.append(f"Core consistency is {cc:.0f}% (below 50%): {RANK} components may be too many for a CP model — compare fewer.")
else:
fit = tn.tucker_hooi(X, mask, RANKS, MAX_ITER, TOL)
factors = fit["U"]
G = fit["G"]
values.update({"rank1": RANKS[0], "rank2": RANKS[1], "rank3": RANKS[2], "fit": fit["fit"], "rel_error": fit["rel_error"],
"iterations": fit["iterations"], "converged": fit["converged"]})
core_rows = []
total_g = float(np.sum(G ** 2))
for a in range(RANKS[0]):
for b in range(RANKS[1]):
for c in range(RANKS[2]):
core_rows.append({"cell": f"{a + 1}·{b + 1}·{c + 1}", "a": a + 1, "b": b + 1, "c": c + 1, "value": float(G[a, b, c]),
"share": float(G[a, b, c] ** 2 / total_g) if total_g > 0 else float("nan")})
core_rows.sort(key=lambda row: -row["share"])
values["core_top_share"] = core_rows[0]["share"]
tables.append({"key": "core", "title": "Core tensor (largest cells first)",
"columns": [{"key": "a", "label": f"{MODES[0]} factor", "type": "integer"}, {"key": "b", "label": f"{MODES[1]} factor", "type": "integer"},
{"key": "c", "label": f"{MODES[2]} factor", "type": "integer"}, {"key": "value", "label": "Core value", "type": "number"},
{"key": "share", "label": "Share of Σ core²", "type": "percent"}],
"rows": [{k_: row[k_] for k_ in ("a", "b", "c", "value", "share")} for row in core_rows]})
values["missing_share"] = n_dropped / n_input if n_input else 0.0
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-29333/discover.tensor/sales-tucker/out-python")
artifacts = []
for m, lv, F in zip(MODES, levels, factors):
fdf = pd.DataFrame({"level": lv})
for r in range(F.shape[1]):
fdf[f"factor_{r + 1}"] = F[:, r]
path = os.path.join(out, f"factors_{m}.parquet")
fdf.to_parquet(path, index=False)
artifacts.append({"key": f"factors_{m}", "path": path, "format": "parquet"})
rows_, cols_, vals_ = [], [], []
for i, name in enumerate(lv):
for r in range(F.shape[1]):
rows_.append(name); cols_.append(f"Factor {r + 1}"); vals_.append(float(F[i, r]))
charts.append(cs.chart(f"factors_{m}", "matrix-heatmap", f"{m}: factor loadings", {
"row": cs.col(m, rows_, "categorical"), "col": cs.col("Factor", cols_, "categorical"),
"value": cs.col("Loading", np.array(vals_)), "label": cs.col("Value", [f"{v:.2f}" for v in vals_], "categorical")}))
tables.append({"key": f"factors_{m}", "title": f"Factors: {m}",
"columns": [{"key": "level", "label": m, "type": "string"}] + [{"key": f"f{r + 1}", "label": f"Factor {r + 1}", "type": "number"} for r in range(F.shape[1])],
"rows": [{"level": name, **{f"f{r + 1}": float(F[i, r]) for r in range(F.shape[1])}} for i, name in enumerate(lv)]})
if scan_rows:
fits = np.array([row["fit"] for row in scan_rows])
charts.append(cs.chart("scan", "scree-plot", "Fit by number of components", {
"component": cs.col("Components", np.array([row["rank"] for row in scan_rows], dtype=float)),
"variance": cs.col("Gain in fit", np.diff(np.concatenate([[0.0], fits]))),
"cumulative": cs.col("Fit", fits)}))
for m, F in zip(MODES, factors):
values[f"factor_check[{m}]"] = float(np.sum(np.arange(1, F.shape[0] + 1)[:, None] * F))
# %% Result
shape = f"{dims[0]} × {dims[1]} × {dims[2]} ({' × '.join(MODES)})"
if METHOD == "cp":
summary = (f"CP decomposition with {RANK} component{'s' if RANK != 1 else ''} of the {shape} array of {VALUE}: fit {fit['fit']:.3f} "
f"(relative error {fit['rel_error']:.3f})" + (f", core consistency {cc:.0f}%" if RANK >= 2 else "") + ".")
else:
summary = (f"Tucker decomposition with {RANKS[0]} × {RANKS[1]} × {RANKS[2]} factors of the {shape} array of {VALUE}: fit {fit['fit']:.3f} "
f"(relative error {fit['rel_error']:.3f}).")
if not fit["converged"]:
warnings.append(cs.cs_warning("CS_W_NO_CONVERGENCE", what=f"The {'CP' if METHOD == 'cp' else 'Tucker'} decomposition"))
cs.publish({
"title": "Tensor decomposition (CP / PARAFAC and Tucker)",
"engine": cs.engine_info("numpy", "pandas"),
"n": n_obs,
"summary": summary,
"statistics": [{"key": "fit", "label": "Fit", "value": fit["fit"]}, {"key": "rel_error", "label": "Relative error", "value": fit["rel_error"]}]
+ ([{"key": "corcondia", "label": "Core consistency (%)", "value": values["corcondia"]}] if METHOD == "cp" else []),
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"notes": ["Fit = 1 − Σ(x − x̂)² / Σx² over the observed cells (not centered); "
+ ("CP factors have unit length, weights λ carry the scale, components are sorted by λ, and each component's first two factors have their largest entry positive; "
"core consistency (Bro & Kiers 2003) near 100% supports a CP model, below 50% suggests too many components. "
if METHOD == "cp" else "Tucker factors are orthonormal (each column's largest entry positive) and the core tensor carries the scale. ")
+ f"From the HOSVD start; stops when the fit changes by less than {TOL:g} or after {MAX_ITER} sweeps ({fit['iterations']} used)."],
"artifacts": artifacts,
})
Check your understanding
CheckpointCheck yourself
You have a spreadsheet of travel times: each row is a pair of towns with the minutes between them. Which input do you choose?
Show the answer
Answer: c
Each row is one pair, so it is a pair list. Every pair must appear once (or more: repeats are averaged).
Check yourself
Why might you prefer Sammon mapping to classical scaling?
Show the answer
Answer: b
Sammon's stress weights each pair by one over its distance, so errors on short distances cost more. It fails on zero distances.
Check yourself
A CP component has high factors for stores 2 and 5, product P3 and the winter months. What does it describe?
Show the answer
Answer: a
A CP component is a product of its three factors, so it describes the cells where all three are high at once.
Check yourself
Going from 2 to 3 CP components raises the fit from 0.9997 to 0.9998, and core consistency falls from 100% to 42%. What do you keep?
Show the answer
Answer: a
The extra component adds almost no fit and breaks the CP structure, which is a sign it models noise.