Skip to content

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.

Advanced ~14 min7 steps

What runs in CodeSplash

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

Read first

01

When you only have distances

Read

Some 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.

02

Map the cities

In the app
Multidimensional scaling (MDS / PCoA / NMDS)Recorded · Python and R agreeRecorded 2026-11-25 · 12 values compared · largest relative difference 2.5e-15
R

Classical scaling (distance matrix) placed 21 rows in 2 dimensions reproducing 86.8% of the positive variance.

Goodness of fit
86.8%
Stress
—

Plots

Principal coordinatesWhich rows group together, and how well separated are the groups?
View data
cityItemDimension 1Dimension 2
AthensAthens2290.27−1798.80
BarcelonaBarcelona−825.38−546.81
BrusselsBrussels59.183367.08
CalaisCalais−82.846429.91
CherbourgCherbourg−352.50290.91
CologneCologne293.69405.31
CopenhagenCopenhagen681.931108.64
GenevaGeneva−9.423−240.41
GibraltarGibraltar−2048.45−642.46
HamburgHamburg561.11773.37
Hook of HollandHook of Holland164.92549.37
LisbonLisbon−1935.04−49.125
LyonsLyons−226.42−187.09
MadridMadrid−1423.35−305.88
MarseillesMarseilles−299.50−388.81
MilanMilan260.88−416.67
MunichMunich587.68−81.182
ParisParis−156.84211.14
RomeRome709.41−1109.37
StockholmStockholm839.451836.79
ViennaVienna911.23−205.93

Principal coordinates

DimensionEigenvalue
11.954e+7
21.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
))
Python

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

DimensionEigenvalue
11.954e+7
21.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.

03

Keeping neighborhoods: Sammon mapping

Read

Classical 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.

Multidimensional scaling (MDS / PCoA / NMDS)Recorded · Python and R agreeRecorded 2026-11-25 · 12 values compared · largest relative difference 2.5e-15
R

Sammon mapping (distance matrix) placed 21 rows in 2 dimensions with stress 0.0094.

Goodness of fit
86.8%
Stress
0.0094

Plots

Sammon mapWhich rows group together, and how well separated are the groups?
View data
cityItemDimension 1Dimension 2
AthensAthens1921.91−1830.43
BarcelonaBarcelona−759.76−606.09
BrusselsBrussels80.199443.37
CalaisCalais−106.21512.10
CherbourgCherbourg−484.41477.30
CologneCologne295.33445.05
CopenhagenCopenhagen543.941091.59
GenevaGeneva−7.410−269.68
GibraltarGibraltar−1942.80−727.83
HamburgHamburg626.72721.55
Hook of HollandHook of Holland185.86658.29
LisbonLisbon−1916.64−83.584
LyonsLyons−149.49−217.71
MadridMadrid−1372.71−349.73
MarseillesMarseilles−285.26−514.73
MilanMilan273.11−426.50
MunichMunich569.25−106.53
ParisParis−161.49261.15
RomeRome698.67−1023.66
StockholmStockholm951.881716.51
ViennaVienna1039.31−170.44
Shepard diagramHow faithfully does an MDS map keep the original distances?

Sammon stress = 0.0094

View data
DissimilarityMap distanceEqual distances
3,3132947.943,313
2,9632926.102,963
3,1753098.503,175
3,3393334.073,339
2,7622797.072,762
3,2763230.633,276
2,6102481.572,610
4,4854018.924,485
2,9772861.842,977
3,0303034.403,030
4,5324217.344,532
2,7532625.182,753
3,9493612.063,949
2,8652569.572,865
2,2822165.542,282
2,1792191.242,179
3,0002952.173,000
8171465.33817
3,9273677.193,927
1,9911880.041,991
1,3181344.201,318
1,3261295.171,326
1,2941117.841,294
1,4981489.341,498
2,2182140.502,218
803824.13803
1,1721189.291,172
2,0181919.622,018
1,4901578.871,490
1,3051269.401,305
645723.38645
636664.40636
521483.22521
1,0141048.371,014
1,3651419.791,365
1,0331053.581,033
1,4601517.031,460
2,8682885.162,868
1,8021851.061,802
204198.67204
583565.63583
206215.14206
966797.03966
677718.41677
2,2562337.572,256
597613.24597
172239.49172
2,0842065.202,084
690699.84690
1,5581655.271,558
1,0111025.431,011
925891.00925
747735.91747
285302.68285
1,5111592.071,511
1,6161542.951,616
1,1751138.701,175
460379.80460
409407.10409
1,136870.921,136

First 60 of 210 rows.

Principal coordinates

DimensionEigenvalue
11.954e+7
21.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
))
Python

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

DimensionEigenvalue
11.954e+7
21.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.

04

Make a guess

Predict

Predict 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?

About 100%About 50%Far below 0%
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%.

05

Three-way tables

Read

A 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".

Tensor decomposition (CP / PARAFAC and Tucker)Recorded · Python and R agreeRecorded 2026-11-21 · 31 values compared
R

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

store: factor loadingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
FactorValuestoreLoading
Factor 10.57Store 10.5717
Factor 20.75Store 10.7543
Factor 10.32Store 20.3237
Factor 20.31Store 20.3092
Factor 10.22Store 30.2200
Factor 20.24Store 30.2399
Factor 10.21Store 40.2099
Factor 20.49Store 40.4862
Factor 10.25Store 50.2525
Factor 20.19Store 50.1908
Factor 10.39Store 60.3889
Factor 20.00Store 65.183e-5
Factor 10.24Store 70.2355
Factor 20.06Store 70.0591
Factor 10.45Store 80.4533
Factor 20.04Store 80.0396
product: factor loadingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
FactorValueproductLoading
Factor 10.59P10.5911
Factor 20.47P10.4696
Factor 10.37P20.3734
Factor 20.68P20.6792
Factor 10.18P30.1763
Factor 20.07P30.0660
Factor 10.48P40.4781
Factor 20.56P40.5582
Factor 10.40P50.3966
Factor 20.03P50.0331
Factor 10.31P60.3070
Factor 20.03P60.0344
month: factor loadingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
FactorValuemonthLoading
Factor 10.29Jan0.2915
Factor 20.71Jan0.7082
Factor 10.36Feb0.3634
Factor 20.52Feb0.5188
Factor 10.44Mar0.4365
Factor 20.36Mar0.3594
Factor 10.51Apr0.5074
Factor 20.25Apr0.2521
Factor 10.58May0.5788
Factor 20.19May0.1914
Fit by number of componentsHow many components carry most of the variance?
View data
ComponentsFitGain in fit
10.99790.9979
20.99970.0018
30.99984.787e-5
40.99983.727e-5
50.99994.347e-5

Components

ComponentWeight λShare of Σλ²
139.09699.3%
23.2520.7%

Choosing the number of components

ComponentsFitCore consistency (%)
10.9979100
20.999799.958
30.999842.090
40.9998−688.09
50.9999−4751.09

Factors: store

storeFactor 1Factor 2
Store 10.57170.7543
Store 20.32370.3092
Store 30.22000.2399
Store 40.20990.4862
Store 50.25250.1908
Store 60.38895.183e-5
Store 70.23550.0591
Store 80.45330.0396

Factors: product

productFactor 1Factor 2
P10.59110.4696
P20.37340.6792
P30.17630.0660
P40.47810.5582
P50.39660.0331
P60.30700.0344

Factors: month

monthFactor 1Factor 2
Jan0.29150.7082
Feb0.36340.5188
Mar0.43650.3594
Apr0.50740.2521
May0.57880.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
))
Python

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

ComponentWeight λShare of Σλ²
139.09699.3%
23.2520.7%

Choosing the number of components

ComponentsFitCore consistency (%)
10.9979100
20.999799.958
30.999842.090
40.9998−688.09
50.9999−4751.09

Factors: store

storeFactor 1Factor 2
Store 10.57170.7543
Store 20.32370.3092
Store 30.22000.2399
Store 40.20990.4862
Store 50.25250.1908
Store 60.38895.183e-5
Store 70.23550.0591
Store 80.45330.0396

Factors: product

productFactor 1Factor 2
P10.59110.4696
P20.37340.6792
P30.17630.0660
P40.47810.5582
P50.39660.0331
P60.30700.0344

Factors: month

monthFactor 1Factor 2
Jan0.29150.7082
Feb0.36340.5188
Mar0.43650.3594
Apr0.50740.2521
May0.57880.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.

06

Tucker: a factor count per mode

Read

TuckerTucker 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.

Tensor decomposition (CP / PARAFAC and Tucker)Recorded · Python and R agreeRecorded 2026-11-21 · 19 values compared
R

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

store: factor loadingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
FactorValuestoreLoading
Factor 10.59Store 10.5888
Factor 20.47Store 10.4707
Factor 10.33Store 20.3269
Factor 20.08Store 20.0845
Factor 10.22Store 30.2238
Factor 20.10Store 30.1033
Factor 10.23Store 40.2277
Factor 20.50Store 40.4996
Factor 10.25Store 50.2522
Factor 2-0.01Store 5−0.0137
Factor 10.37Store 60.3722
Factor 2-0.48Store 6−0.4768
Factor 10.23Store 70.2286
Factor 2-0.20Store 7−0.1976
Factor 10.44Store 80.4360
Factor 2-0.49Store 8−0.4944
product: factor loadingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
FactorValueproductLoading
Factor 10.59P10.5896
Factor 2-0.06P1−0.0586
Factor 3-0.01P1−0.0070
Factor 10.39P20.3923
Factor 20.65P20.6546
Factor 30.22P20.2188
Factor 10.17P30.1721
Factor 2-0.15P3−0.1516
Factor 30.89P30.8949
Factor 10.49P40.4861
Factor 20.28P40.2758
Factor 3-0.35P4−0.3533
Factor 10.38P50.3811
Factor 2-0.55P5−0.5491
Factor 3-0.05P5−0.0470
Factor 10.30P60.2954
Factor 2-0.41P6−0.4093
Factor 3-0.16P6−0.1557
month: factor loadingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
FactorValuemonthLoading
Factor 10.32Jan0.3170
Factor 20.77Jan0.7693
Factor 10.38Feb0.3757
Factor 20.37Feb0.3650
Factor 10.44Mar0.4371
Factor 20.01Mar0.0130
Factor 10.50Apr0.4991
Factor 2-0.26Apr−0.2609
Factor 10.56May0.5641
Factor 2-0.45May−0.4547

Core tensor (largest cells first)

store factorproduct factormonth factorCore valueShare of Σ core²
11140.79899.8%
2121.0440.1%
2210.89960.0%
1220.83550.0%
2220.60780.0%
132−0.08310.0%
2310.05630.0%
2320.03090.0%
121−0.01500.0%
112−0.01280.0%
211−0.01170.0%
131−0.00080.0%

Factors: store

storeFactor 1Factor 2
Store 10.58880.4707
Store 20.32690.0845
Store 30.22380.1033
Store 40.22770.4996
Store 50.2522−0.0137
Store 60.3722−0.4768
Store 70.2286−0.1976
Store 80.4360−0.4944

Factors: product

productFactor 1Factor 2Factor 3
P10.5896−0.0586−0.0070
P20.39230.65460.2188
P30.1721−0.15160.8949
P40.48610.2758−0.3533
P50.3811−0.5491−0.0470
P60.2954−0.4093−0.1557

Factors: month

monthFactor 1Factor 2
Jan0.31700.7693
Feb0.37570.3650
Mar0.43710.0130
Apr0.4991−0.2609
May0.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
))
Python

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 factorproduct factormonth factorCore valueShare of Σ core²
11140.79899.8%
2121.0440.1%
2210.89960.0%
1220.83550.0%
2220.60780.0%
132−0.08310.0%
2310.05630.0%
2320.03090.0%
121−0.01500.0%
112−0.01280.0%
211−0.01170.0%
131−0.00080.0%

Factors: store

storeFactor 1Factor 2
Store 10.58880.4707
Store 20.32690.0845
Store 30.22380.1033
Store 40.22770.4996
Store 50.2522−0.0137
Store 60.3722−0.4768
Store 70.2286−0.1976
Store 80.4360−0.4944

Factors: product

productFactor 1Factor 2Factor 3
P10.5896−0.0586−0.0070
P20.39230.65460.2188
P30.1721−0.15160.8949
P40.48610.2758−0.3533
P50.3811−0.5491−0.0470
P60.2954−0.4093−0.1557

Factors: month

monthFactor 1Factor 2
Jan0.31700.7693
Feb0.37570.3650
Mar0.43710.0130
Apr0.4991−0.2609
May0.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,
})
07

Check your understanding

Checkpoint

Check 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.