Tables with three or more ways: tensor decompositions
Sales by store, product and month form a cube, not a table. CP writes it as a sum of separable pieces, Tucker as a small core with factors per mode, tensor trains as a chain. Two relatives need data types CodeSplash doesn't load.
What runs in CodeSplash
- REP021CP/PARAFAC tensor decomposition Runs in CodeSplash
- REP022Tucker decomposition Runs in CodeSplash
- REP023Tensor-train decomposition Explained here
- REP024Tensor robust PCA using the t-SVD nuclear norm Needs a data type CodeSplash doesn't load yet
- REP025Collective matrix factorization Needs a data type CodeSplash doesn't load yet
- Tensor decomposition (CP / PARAFAC and Tucker) Verified in Python and R
You will be able to
- Write the CP model, read its components, and use core consistency to judge the rank
- Contrast Tucker's core and per-mode ranks with CP, and say why Tucker factors aren't unique
- Explain what tensor trains, tensor robust PCA and collective matrix factorization add, and why they aren't in the app
Don't flatten the cube
ReadSales recorded by store, product and month form a three-way array . You could flatten it into a stores × (products·months) table and run PCA, but then "product 3 in March" and "product 3 in April" become unrelated columns and the month pattern is lost.
Tensor decompositions keep each way, or mode, separate, so a component has a store profile, a product profile and a month profile.
CP: a sum of separable pieces
ReadCPCP 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). (CANDECOMP/PARAFAC) writes
Each component is one store vector times one product vector times one month vector: "large stores sell lots of product group 1 in winter". Unlike PCA, CP is usually unique up to scale and order once the rank is right, so its components can be read directly.
Tensor rank behaves differently from matrix rank: some fits keep improving while factors grow without bound and cancel each other (degeneracy).
Choosing the CP rank
ReadCP 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,
})
On an 8 × 6 × 5 sales cube, rank 2 fits 99.97% of the sum of squares. Core consistencyCore consistencyHow close CP factors come to a diagonal Tucker core (Bro & Kiers 2003): near 100% supports CP; below 50% hints at too many components. is 100.0 at rank 2, 42.1 at rank 3 and −688 at rank 4. Fit barely improves past rank 2 while consistency collapses: rank 3 and up are fitting noise.
Tucker: a core and per-mode ranks
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 factor matrix and rank, joined by a small core array :
CP is the special case of a diagonal core. Tucker compresses more flexibly (2 store components, 3 product components, 2 month components), but any rotation inside a mode can be absorbed by the core, so individual Tucker factors aren't unique.
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,
})
With ranks (2, 3, 2), it fits 99.97%, and one core cell carries 99.8% of the core's sum of squares.
Many modes: tensor trains
ReadA dense array with modes of size has entries. A tensor trainTensor trainWrites a many-way array as a chain of small three-way cores, so storage grows with the number of modes instead of exponentially. stores it as a chain of small three-way cores,
where each is a small matrix. Storage grows like : linear in the number of modes. In the reference's example, a tensor needs 20 core numbers. The ranks depend on the order of the modes, and small cores are not latent causes.
Two relatives that need other data
Read- Tensor robust PCATensor robust PCARobust PCA for a stack of matrices, such as video frames: a low-rank background plus sparse changes, using the t-SVD nuclear norm. (REP024) splits a stack of frames into a low-rank background and sparse changes using the t-SVD nuclear norm. Its natural data are video frames or image stacks, which CodeSplash doesn't load.
- Collective matrix factorizationCollective matrix factorizationFactors several related tables at once, so an entity that appears in two tables (a user, an item) gets one shared vector. (REP025) factors several linked tables at once, such as user × item ratings and item × tag features, giving each item one shared vector. It needs multi-table relational data, which CodeSplash doesn't analyze as one input. Missing ratings must stay missing, never become zeros.
Readiness
ReadCP (REP021) and Tucker (REP022) run in CodeSplash: Discover → Tensor decomposition, from a long table with one row per cell. Tensor trains (REP023) are explained here. Tensor robust PCA (REP024) and collective matrix factorization (REP025) need a data type CodeSplash doesn't load yet.
Reference · REP023 · Explained hereTensor-train decompositionCompress high-order arrays using a chain of small cores, avoiding the exponential storage of an unrestricted dense tensor. Reference · REP024 · Needs a data type CodeSplash doesn't load yetTensor robust PCA using the t-SVD nuclear normSeparate low-tubal-rank structure from sparse corruption in a three-way array, often illustrated by foreground/background video separation. Reference · REP025 · Needs a data type CodeSplash doesn't load yetCollective matrix factorizationJointly factor several relational matrices that share entity types, such as user–item ratings and item–tag features, using common factors where entities overlap.Check: tensors
CheckpointCheck yourself
What does one CP component of a store × product × month cube contain?
Show the answer
Answer: a
Each component is separable: . That is what makes it readable.
Check yourself
Fit keeps creeping up from rank 2 to rank 4, but core consistency drops from near 100 to strongly negative. Which rank do you report?
Show the answer
Answer: a
Fit always improves with more components. Core consistency tests whether a CP model of that rank is appropriate.
Check yourself
Why are individual Tucker factors harder to interpret than CP components?
Show the answer
Answer: a
Tucker identifies subspaces per mode. CP's diagonal core removes that freedom, which is why CP components are usually unique.
Check yourself
What is CP in terms of Tucker?
Show the answer
Answer: a
A superdiagonal core links component of every mode only to component of the others.
Check yourself
A 10-way array with 4 values per mode has about a million entries. Why can a tensor train store it with far fewer numbers?
Show the answer
Answer: a
entries versus roughly core numbers.
Check yourself
You reorder the modes of a tensor before fitting a tensor train. What can change?
Show the answer
Answer: a
Tensor-train ranks are ranks of particular unfoldings, which depend on which modes sit next to each other.
Check yourself
Which data suit tensor robust PCA best, and why isn't it in CodeSplash?
Show the answer
Answer: a
Low-rank background plus sparse moving pixels is the classic case. Video stays in the Academy only.
Check yourself
When does tensor robust PCA's background/foreground split break down?
Show the answer
Answer: a
The method assumes a low-rank background and sparse changes. Dense motion or a moving camera violates both.
Check yourself
In collective matrix factorization of ratings (users × items) and features (items × tags), what is shared?
Show the answer
Answer: a
Items appear in both relations, so they get one vector that must explain both their ratings and their tags.
Check yourself
Most user–item pairs have no rating. How should collective matrix factorization treat them?
Show the answer
Answer: a
An unrated item isn't a disliked item. Treating gaps as zeros teaches the model that everyone dislikes most things.
Recap
Recap- CP is a sum of separable components, usually unique; choose its rank with core consistency, not fit alone.
- Tucker has per-mode ranks and a core; its factors rotate freely.
- Tensor trains chain small cores; tensor robust PCA and collective factorization need image stacks or linked tables.
Concepts in this lesson