CDiscover · discover.tensor
Tensor decomposition (CP / PARAFAC and Tucker)
What few patterns describe a three-way table — stores × products × months, subjects × items × occasions?
Decomposes a three-way array, given as a long table with three mode columns and a value, into a few interpretable parts. CP (CANDECOMP/PARAFAC) writes it as a sum of components, each with one factor per mode, so a component reads as "these stores × these products × these months"; Tucker gives each mode its own number of factors and a small core that links them. It reports the fit, the factors of every mode, CP's core consistency and a scan over the number of components. Missing cells are filled from the model as it fits.
A real result
Example “Sales cp”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
CP decomposition with 2 components of the 8 × 6 × 5 (store × product × month) array of sales: fit 1.000 (relative error 0.017), core consistency 100%.
- Fit
- 0.9997
- Relative error
- 0.0165
- Core consistency (%)
- 99.958
Plots
View data
| Factor | Value | store | Loading |
|---|---|---|---|
| Factor 1 | 0.57 | Store 1 | 0.5717 |
| Factor 2 | 0.75 | Store 1 | 0.7543 |
| Factor 1 | 0.32 | Store 2 | 0.3237 |
| Factor 2 | 0.31 | Store 2 | 0.3092 |
| Factor 1 | 0.22 | Store 3 | 0.2200 |
| Factor 2 | 0.24 | Store 3 | 0.2399 |
| Factor 1 | 0.21 | Store 4 | 0.2099 |
| Factor 2 | 0.49 | Store 4 | 0.4862 |
| Factor 1 | 0.25 | Store 5 | 0.2525 |
| Factor 2 | 0.19 | Store 5 | 0.1908 |
| Factor 1 | 0.39 | Store 6 | 0.3889 |
| Factor 2 | 0.00 | Store 6 | 5.183e-5 |
| Factor 1 | 0.24 | Store 7 | 0.2355 |
| Factor 2 | 0.06 | Store 7 | 0.0591 |
| Factor 1 | 0.45 | Store 8 | 0.4533 |
| Factor 2 | 0.04 | Store 8 | 0.0396 |
View data
| Factor | Value | product | Loading |
|---|---|---|---|
| Factor 1 | 0.59 | P1 | 0.5911 |
| Factor 2 | 0.47 | P1 | 0.4696 |
| Factor 1 | 0.37 | P2 | 0.3734 |
| Factor 2 | 0.68 | P2 | 0.6792 |
| Factor 1 | 0.18 | P3 | 0.1763 |
| Factor 2 | 0.07 | P3 | 0.0660 |
| Factor 1 | 0.48 | P4 | 0.4781 |
| Factor 2 | 0.56 | P4 | 0.5582 |
| Factor 1 | 0.40 | P5 | 0.3966 |
| Factor 2 | 0.03 | P5 | 0.0331 |
| Factor 1 | 0.31 | P6 | 0.3070 |
| Factor 2 | 0.03 | P6 | 0.0344 |
View data
| Factor | Value | month | Loading |
|---|---|---|---|
| Factor 1 | 0.29 | Jan | 0.2915 |
| Factor 2 | 0.71 | Jan | 0.7082 |
| Factor 1 | 0.36 | Feb | 0.3634 |
| Factor 2 | 0.52 | Feb | 0.5188 |
| Factor 1 | 0.44 | Mar | 0.4365 |
| Factor 2 | 0.36 | Mar | 0.3594 |
| Factor 1 | 0.51 | Apr | 0.5074 |
| Factor 2 | 0.25 | Apr | 0.2521 |
| Factor 1 | 0.58 | May | 0.5788 |
| Factor 2 | 0.19 | May | 0.1914 |
View data
| Components | Fit | Gain in fit |
|---|---|---|
| 1 | 0.9979 | 0.9979 |
| 2 | 0.9997 | 0.0018 |
| 3 | 0.9998 | 4.787e-5 |
| 4 | 0.9998 | 3.727e-5 |
| 5 | 0.9999 | 4.347e-5 |
Components
| Component | Weight λ | Share of Σλ² |
|---|---|---|
| 1 | 39.096 | 99.3% |
| 2 | 3.252 | 0.7% |
Choosing the number of components
| Components | Fit | Core consistency (%) |
|---|---|---|
| 1 | 0.9979 | 100 |
| 2 | 0.9997 | 99.958 |
| 3 | 0.9998 | 42.090 |
| 4 | 0.9998 | −688.09 |
| 5 | 0.9999 | −4751.09 |
Factors: store
| store | Factor 1 | Factor 2 |
|---|---|---|
| Store 1 | 0.5717 | 0.7543 |
| Store 2 | 0.3237 | 0.3092 |
| Store 3 | 0.2200 | 0.2399 |
| Store 4 | 0.2099 | 0.4862 |
| Store 5 | 0.2525 | 0.1908 |
| Store 6 | 0.3889 | 5.183e-5 |
| Store 7 | 0.2355 | 0.0591 |
| Store 8 | 0.4533 | 0.0396 |
Factors: product
| product | Factor 1 | Factor 2 |
|---|---|---|
| P1 | 0.5911 | 0.4696 |
| P2 | 0.3734 | 0.6792 |
| P3 | 0.1763 | 0.0660 |
| P4 | 0.4781 | 0.5582 |
| P5 | 0.3966 | 0.0331 |
| P6 | 0.3070 | 0.0344 |
Factors: month
| month | Factor 1 | Factor 2 |
|---|---|---|
| Jan | 0.2915 | 0.7082 |
| Feb | 0.3634 | 0.5188 |
| Mar | 0.4365 | 0.3594 |
| Apr | 0.5074 | 0.2521 |
| May | 0.5788 | 0.1914 |
- Fit = 1 − Σ(x − x̂)² / Σx² over the observed cells (not centered); CP factors have unit length, weights λ carry the scale, components are sorted by λ, and each component's first two factors have their largest entry positive; core consistency (Bro & Kiers 2003) near 100% supports a CP model, below 50% suggests too many components. From the HOSVD start; stops when the fit changes by less than 1e-08 or after 500 sweeps (54 used).
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).
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Sales cprep2_tensor · mode1: store · mode2: product · mode3: month · value: sales
- Sales cp3 no scanrep2_tensor · mode1: store · mode2: product · mode3: month · value: sales
- Sales tuckerrep2_tensor · mode1: store · mode2: product · mode3: month · value: sales
- Sales cp missing cellsrep2_tensor_gaps · mode1: store · mode2: product · mode3: month · value: sales
- Degenerate constantrep2_tensor · mode1: store · mode2: product · mode3: month · value: sales
- Degenerate one storerep2_tensor · mode1: store · mode2: product · mode3: month · value: sales
- Degenerate too many componentsrep2_tensor · mode1: store · mode2: product · mode3: month · value: sales
In the guides
Where it sits in the decision guides
- Multiview and multiway structure (CCA, generalized CCA, tensors) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- First modecategorical · 1 column · 2–500 levels
- The first index of the array, for example the store.
- Second modecategorical · 1 column · 2–500 levels
- The second index, for example the product.
- Third modecategorical · 1 column · 2–500 levels
- The third index, for example the month.
- Valuenumeric · 1 column
- The number in each cell; rows that repeat a cell are averaged.
Choices you make
model
- Decompositiondefault cp
CP finds components shared by all three modes; Tucker lets each mode have its own number of factors.
- CP (PARAFAC)(default) — A sum of rank-one components; unique up to scaling and order, so each component is directly interpretable.
- Tucker — Orthonormal factors per mode and a core tensor linking them; more flexible, factors are a basis rather than unique.
- Componentsdefault 2
CP components; at most the smallest mode's number of levels.
- Factors (first mode)default 2
Tucker factors for the first mode.
- Factors (second mode)default 2
Tucker factors for the second mode.
- Factors (third mode)default 2
Tucker factors for the third mode.
- Scan the number of componentsdefault on
Also fits 1 to 6 components (or the smallest mode's size) and reports each fit and core consistency.
Advanced
- Maximum sweepsdefault 500
Alternating sweeps before stopping; it stops earlier when the fit changes by less than 1e-8.
What it reports
- n_cells
- How many independent units the analysis used; it sets precision and power.
- n_observed
- How many independent units the analysis used; it sets precision and power.
- n_mode1
- How many independent units the analysis used; it sets precision and power.
- n_mode2
- How many independent units the analysis used; it sets precision and power.
- n_mode3
- How many independent units the analysis used; it sets precision and power.
- rank
- CP: the number of components and each one's weight λ. Tucker: the number of factors kept for each mode.
- rank1
- CP: the number of components and each one's weight λ. Tucker: the number of factors kept for each mode.
- rank2
- CP: the number of components and each one's weight λ. Tucker: the number of factors kept for each mode.
- rank3
- CP: the number of components and each one's weight λ. Tucker: the number of factors kept for each mode.
- fit
- 1 − Σ(x − x̂)² / Σx² over the observed cells; the relative error is the square root of what's left. Not centered.
- rel_error
- 1 − Σ(x − x̂)² / Σx² over the observed cells; the relative error is the square root of what's left. Not centered.
- iterations
- Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
- converged
- Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
- corcondia
- How close CP factors come to a diagonal Tucker core (Bro & Kiers 2003): near 100% supports CP; below 50% hints at too many components.
- core_top_share
- Share of the core tensor's sum of squares in its largest cell; near 1 means one combination of factors carries the array.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
Per group, level or term: lambda[<r>], scan_fit[<r>], scan_corcondia[<r>], factor_check[<mode>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy, pandas, codesplash; R uses codesplashr, nanoparquet.
Default traps between the two languages
- Both engines run the codesplash twins: the same HOSVD start, alternating updates and EM fill for missing cells, with every singular vector and factor flipped so its largest entry is positive and CP components sorted by weight, so factors match without matching up permutations or signs. tensorly's parafac and tucker (init = 'svd') reach the same fit on the test arrays (checked in tests/crosscheck/w5_rep2_tensor.py).
The exact script CodeSplash ran for example “Sales cp” · 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,
})
The exact script CodeSplash ran for example “Sales cp” · 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
))
Sources
- Harshman, R. A. (1970). Foundations of the PARAFAC procedure. UCLA Working Papers in Phonetics, 16, 1–84.
- Carroll, J. D., & Chang, J.-J. (1970). Analysis of individual differences in multidimensional scaling via an N-way generalization of Eckart–Young decomposition. Psychometrika, 35, 283–319.
- Tucker, L. R. (1966). Some mathematical notes on three-mode factor analysis. Psychometrika, 31, 279–311.
- De Lathauwer, L., De Moor, B., & Vandewalle, J. (2000). On the best rank-1 and rank-(R1, R2, ..., RN) approximation of higher-order tensors. SIAM J. Matrix Anal. Appl., 21, 1324–1342.
- Bro, R., & Kiers, H. A. L. (2003). A new efficient method for determining the number of components in PARAFAC models. Journal of Chemometrics, 17, 274–286.
- Kolda, T. G., & Bader, B. W. (2009). Tensor decompositions and applications. SIAM Review, 51, 455–500.
From the CodeSplash method registry · discover.tensor v1.0.0.