Two views of the same rows: CCA, kernel CCA and GCCA
When the same rows are measured twice, canonical correlation finds the directions in each table that move together. See why it overfits so easily, what kernels and ridge add, and how GCCA joins three or more tables.
What runs in CodeSplash
- REP009Canonical correlation analysis (CCA) Runs in CodeSplash
- REP010Kernel canonical correlation analysis Runs in CodeSplash
- REP011Generalized CCA (GCCA) Runs in CodeSplash
- Canonical correlation analysis (CCA, ridge and kernel CCA) Verified in Python and R
- Generalized canonical correlation analysis (GCCA, MAXVAR) Verified in Python and R
You will be able to
- State CCA's objective and read canonical correlations, held-out correlation and a permutation p-value
- Explain why CCA reaches perfect in-sample correlation when columns approach rows, and how ridge and held-out checks help
- Describe kernel CCA and generalized CCA and the extra pitfalls each brings
Directions that move together
ReadTwo tables, ( columns) and ( columns), describe the same rows. Canonical correlation analysisCanonical correlation analysisFinds a weighted sum of each of two sets of variables so the two sums correlate as much as possible, then further uncorrelated pairs. finds weights and that make the two weighted sums as correlated as possible:
Then the next pair, uncorrelated with the first, and so on. The answers come from the SVD of ; its singular values are the canonical correlations. Neither table is the target: the roles are symmetric.
Savings and demographics
ReadCanonical correlation analysis, first canonical r = 0.82, permutation p = .005
- First canonical r
- 0.8248
- Permutation p
- .005
- Held-out r
- 0.8131
Effect size
- First canonical correlation 0.8248
Plots
View data
| Canonical variate 1 of pop15, pop75 | Canonical variate 1 of sr, dpi, ddpi |
|---|---|
| −0.5625 | −1.198 |
| −1.472 | −0.5145 |
| −1.448 | −1.126 |
| 0.6459 | 1.176 |
| 0.9510 | 0.1325 |
| −0.4046 | −1.626 |
| 0.6211 | 0.9759 |
| 1.169 | 0.5354 |
| 1.157 | 1.058 |
| 1.193 | 0.5438 |
| −1.238 | −1.704 |
| 1.091 | 1.156 |
| −0.4886 | −0.6352 |
| −1.459 | −1.211 |
| −1.111 | −1.397 |
| −0.8787 | 0.0830 |
| 1.184 | 1.209 |
| 1.363 | 0.9336 |
| −0.3356 | −0.1509 |
| 0.8506 | 1.036 |
| −0.8966 | −0.1069 |
| −1.078 | −0.5262 |
| −0.3849 | −0.9454 |
| 0.8951 | 1.100 |
| −1.337 | −1.205 |
| −0.2229 | −0.0090 |
| −1.052 | −1.059 |
| −0.9879 | −0.9893 |
| −0.4568 | −0.3494 |
| 1.003 | 0.8928 |
| 0.9124 | 0.8070 |
| 0.8117 | 1.344 |
| 0.9253 | 0.5573 |
| 1.112 | 0.7407 |
| −0.5806 | 0.2067 |
| −0.1964 | 0.3757 |
| 0.0611 | 0.6193 |
| −0.6652 | 0.1675 |
| −1.636 | −1.818 |
| −1.229 | −1.628 |
| 0.9443 | 0.9488 |
| 1.072 | 1.268 |
| −1.492 | −0.4858 |
| −0.7239 | −2.486 |
| 1.196 | 0.3895 |
| 1.238 | 0.3188 |
| 0.5763 | 0.5914 |
| −0.5893 | 0.3917 |
| 0.6244 | 0.5680 |
| 1.328 | 1.046 |
View data
| Dimension | Value | Variable | Correlation with its canonical variate |
|---|---|---|---|
| Dimension 1 | 0.98 | pop15 (first set) | 0.9830 |
| Dimension 2 | 0.18 | pop15 (first set) | 0.1837 |
| Dimension 1 | -0.97 | pop75 (first set) | −0.9698 |
| Dimension 2 | 0.24 | pop75 (first set) | 0.2439 |
| Dimension 1 | -0.49 | sr (second set) | −0.4910 |
| Dimension 2 | -0.86 | sr (second set) | −0.8558 |
| Dimension 1 | -0.95 | dpi (second set) | −0.9545 |
| Dimension 2 | 0.26 | dpi (second set) | 0.2637 |
| Dimension 1 | -0.05 | ddpi (second set) | −0.0473 |
| Dimension 2 | -0.14 | ddpi (second set) | −0.1408 |
Assumptions
- Linear relations — Each canonical variate is a weighted sum of its set's variables; curved relations are missed (kernel CCA catches them).
- Multivariate normality (for Bartlett's test) — Bartlett's chi-square tests assume multivariate normal sets; the permutation p does not.
- Rows per variable — 50 rows for 5 variables (10.0 per variable). Enough for stable weights.
Canonical correlations
| Dimension | Canonical r | r² | Wilks Λ | χ² | df | p (dimensions i…k) |
|---|---|---|---|---|---|---|
| 1 | 0.8248 | 0.6803 | 0.2771 | 59.043 | 6 | < .001 |
| 2 | 0.3653 | 0.1334 | 0.8666 | 6.588 | 2 | .037 |
Structure correlations: first set with its canonical variates
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| pop15 | 0.9830 | 0.1837 |
| pop75 | −0.9698 | 0.2439 |
Structure correlations: second set with its canonical variates
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| sr | −0.4910 | −0.8558 |
| dpi | −0.9545 | 0.2637 |
| ddpi | −0.0473 | −0.1408 |
Standardized canonical weights: first set
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| pop15 | 0.5837 | 2.320 |
| pop75 | −0.4395 | 2.352 |
Standardized canonical weights: second set
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| sr | −0.2657 | −1.047 |
| dpi | −0.9068 | 0.5263 |
| ddpi | −0.0838 | 0.2465 |
Variance extracted and redundancy
| Dimension | First set: own variate | First set: by the other variate | Second set: own variate | Second set: by the other variate |
|---|---|---|---|---|
| 1 | 95.3% | 64.9% | 38.5% | 26.2% |
| 2 | 4.7% | 0.6% | 27.4% | 3.7% |
Held-out correlation of the first pair (5-fold)
| Fold | Held-out r |
|---|---|
| 1 | 0.7283 |
| 2 | 0.8361 |
| 3 | 0.9057 |
| 4 | 0.9140 |
| 5 | 0.6811 |
- Variables standardized; signs make each dimension's largest first-set structure correlation positive; permutation p for the first correlation from 199 row permutations of the second set (seed 42); held-out r = mean over 5 folds of the first pair's correlation on rows the fit did not see.
The exact R script · R R version 4.5.1 (2025-06-13)
# Canonical correlation analysis (CCA, ridge and kernel CCA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.cca 1.0.0 · spec 08dfc48621ffa8b6
# Dataset: rep2_lifecycle (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_lifecycle.parquet", col_select = c("pop15", "pop75", "sr", "dpi", "ddpi")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("pop15", "pop75", "sr", "dpi", "ddpi")]), , 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("pop15", "pop75", "sr", "dpi", "ddpi")) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Canonical correlation analysis (Hotelling 1936): pairs of weighted sums, one per set, that correlate as
# much as possible. Linear CCA (optional ridge, Vinod 1976) or regularized kernel CCA (Hardoon et al. 2004).
x_vars <- c("pop15", "pop75")
y_vars <- c("sr", "dpi", "ddpi")
method <- "linear" # linear | kernel
ridge <- as.numeric(0)
kernel_type <- "rbf" # rbf | linear
bandwidth <- as.numeric(0)
reg <- as.numeric(0.1)
n_comp <- as.integer(2)
n_perm <- if (method == "linear") as.integer(199) else as.integer(199)
cv_folds <- as.integer(5)
alpha <- 0.05
seed <- 42
both <- x_vars[x_vars %in% y_vars]
if (length(both)) cs_error("CS_E_INVALID_OPTION", option = "The two sets", allowed = "separate variables (none in both sets)", value = both[1])
n <- nrow(df)
p <- length(x_vars)
q <- length(y_vars)
cs_check_rows(n, if (method == "linear" && ridge == 0) p + q + 2 else 5, "Canonical correlation analysis")
for (v in c(x_vars, y_vars)) cs_check_not_constant(df[[v]], v)
if (method == "kernel" && n > 2000) {
cs_error("CS_E_UNDEFINED", what = "Kernel CCA", reason = sprintf("it uses n × n kernel matrices; %d rows is too many (at most 2,000)", n))
}
X <- as.matrix(df[x_vars])
Y <- as.matrix(df[y_vars])
storage.mode(X) <- "double"
storage.mode(Y) <- "double"
if (method == "linear") {
fit <- cs_mview_cca(X, Y, ridge)
k <- fit$k
r <- fit$r
rho <- fit$rho
u <- fit$u[, 1]
v <- fit$v[, 1]
struct_x <- fit$struct_x
struct_y <- fit$struct_y
bart <- if (ridge == 0) cs_mview_bartlett(r, n, p, q) else NULL
} else {
fit <- cs_mview_kcca(X, Y, kernel_type, reg, n_comp, bandwidth)
k <- length(fit$rho)
r <- fit$r_train
rho <- fit$rho
u <- fit$F[, 1]
v <- fit$G[, 1]
u <- (u - mean(u)) / stats::sd(u)
v <- (v - mean(v)) / stats::sd(v)
struct_x <- fit$struct_x
struct_y <- fit$struct_y
bart <- NULL
}
perm <- NULL
if (n_perm > 0) {
perm <- if (method == "linear") cs_mview_cca_permutation(X, Y, ridge, n_perm, seed)
else cs_mview_kcca_permutation(X, Y, kernel_type, reg, bandwidth, n_perm, seed)
}
cv <- NULL
if (cv_folds >= 2) {
cv <- if (method == "linear") cs_mview_cca_cv(X, Y, ridge, cv_folds, seed)
else cs_mview_kcca_cv(X, Y, kernel_type, reg, bandwidth, cv_folds, seed)
}
# %% Assumptions
ratio <- n / (p + q)
assumptions <- list(
list(key = "linear", label = if (method == "linear") "Linear relations" else "Smooth relations (kernel)", status = "info",
detail = if (method == "linear") "Each canonical variate is a weighted sum of its set's variables; curved relations are missed (kernel CCA catches them)."
else "The RBF kernel lets each variate be a smooth nonlinear function; the regularization keeps it from fitting noise, so judge it by the held-out correlation."),
list(key = "normality", label = "Multivariate normality (for Bartlett's test)", status = "info",
detail = if (!is.null(bart)) "Bartlett's chi-square tests assume multivariate normal sets; the permutation p does not."
else "No normal-theory test is reported here; the permutation p only assumes exchangeable rows."),
list(key = "rows_per_variable", label = "Rows per variable", status = if (ratio >= 10) "ok" else "warn",
detail = paste0(sprintf("%d rows for %d variables (%.1f per variable). ", n, p + q, ratio),
if (ratio >= 10) "Enough for stable weights."
else "Canonical weights and correlations are unstable below about 10 rows per variable; trust the held-out correlation and structure correlations more than the weights."))
)
# %% Result
nan_or <- function(cond, x) if (cond) x else NaN
values <- list(n = n, p = p, q = q, k = k, r1 = r[1], rho1 = rho[1],
ridge = nan_or(method == "linear", ridge), reg = nan_or(method == "kernel", reg),
p_perm = if (!is.null(perm)) perm$p else NaN, n_perm = if (!is.null(perm)) n_perm else 0L,
cv_r = if (!is.null(cv)) cv$mean else NaN, cv_folds = if (!is.null(cv)) cv_folds else 0L,
wilks = if (!is.null(bart)) bart[[1]]$wilks else NaN, chisq = if (!is.null(bart)) bart[[1]]$chisq else NaN,
df = if (!is.null(bart)) bart[[1]]$df else NaN, p_bartlett = if (!is.null(bart)) bart[[1]]$p else NaN,
redundancy_y = nan_or(method == "linear", sum(fit$redundancy_y)),
redundancy_x = nan_or(method == "linear", sum(fit$redundancy_x)),
sigma_x = nan_or(method == "kernel" && kernel_type == "rbf", fit$sigma_x),
sigma_y = nan_or(method == "kernel" && kernel_type == "rbf", fit$sigma_y))
for (j in seq_len(k)) {
values[[sprintf("r[%d]", j)]] <- r[j]
values[[sprintf("rho[%d]", j)]] <- rho[j]
if (!is.null(bart)) values[[sprintf("p_dim[%d]", j)]] <- bart[[j]]$p
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
cols <- list(list(key = "dimension", label = "Dimension", type = "integer"), list(key = "r", label = "Canonical r", type = "number"),
list(key = "r2", label = "r²", type = "number"))
if (method == "kernel" || ridge > 0) cols <- c(cols, list(list(key = "rho", label = "Regularized ρ", type = "number")))
if (!is.null(bart)) {
cols <- c(cols, list(list(key = "wilks", label = "Wilks Λ", type = "number"), list(key = "chisq", label = "χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p (dimensions i…k)", type = "pvalue")))
}
rows <- lapply(seq_len(k), function(j) {
row <- list(dimension = j, r = r[j], r2 = r[j]^2, rho = rho[j])
if (!is.null(bart)) row <- c(row, list(wilks = bart[[j]]$wilks, chisq = bart[[j]]$chisq, df = bart[[j]]$df, p = bart[[j]]$p))
row
})
tables <- list(list(key = "canonical", title = "Canonical correlations", columns = cols, rows = rows))
struct_table <- function(key, title, names, M) {
list(key = key, title = title,
columns = c(list(list(key = "variable", label = "Variable", type = "string")),
lapply(seq_len(k), function(j) list(key = sprintf("d%d", j), label = sprintf("Dimension %d", j), type = "number"))),
rows = lapply(seq_along(names), function(i) {
row <- list(variable = names[i])
for (j in seq_len(k)) row[[sprintf("d%d", j)]] <- M[i, j]
row
}))
}
tables[[length(tables) + 1]] <- struct_table("structure_x", "Structure correlations: first set with its canonical variates", x_vars, struct_x)
tables[[length(tables) + 1]] <- struct_table("structure_y", "Structure correlations: second set with its canonical variates", y_vars, struct_y)
if (method == "linear") {
tables[[length(tables) + 1]] <- struct_table("coef_x", "Standardized canonical weights: first set", x_vars, fit$coef_x)
tables[[length(tables) + 1]] <- struct_table("coef_y", "Standardized canonical weights: second set", y_vars, fit$coef_y)
tables[[length(tables) + 1]] <- list(key = "redundancy", title = "Variance extracted and redundancy",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"),
list(key = "extracted_x", label = "First set: own variate", type = "percent"),
list(key = "redundancy_x", label = "First set: by the other variate", type = "percent"),
list(key = "extracted_y", label = "Second set: own variate", type = "percent"),
list(key = "redundancy_y", label = "Second set: by the other variate", type = "percent")),
rows = lapply(seq_len(k), function(j) list(dimension = j, extracted_x = fit$extracted_x[j], redundancy_x = fit$redundancy_x[j],
extracted_y = fit$extracted_y[j], redundancy_y = fit$redundancy_y[j])))
}
if (!is.null(cv)) {
tables[[length(tables) + 1]] <- list(key = "cv", title = sprintf("Held-out correlation of the first pair (%d-fold)", cv_folds),
columns = list(list(key = "fold", label = "Fold", type = "integer"), list(key = "r", label = "Held-out r", type = "number")),
rows = lapply(seq_along(cv$folds), function(i) list(fold = i, r = cv$folds[i])))
}
xs <- paste(x_vars, collapse = ", ")
ys <- paste(y_vars, collapse = ", ")
charts <- list(cs_chart("pair", "scatter", "First canonical pair", list(
x = cs_col(sprintf("Canonical variate 1 of %s", xs), u),
y = cs_col(sprintf("Canonical variate 1 of %s", ys), v))))
heat_rows <- character(0); heat_cols <- character(0); heat_vals <- numeric(0)
for (side in list(list(x_vars, struct_x, "first"), list(y_vars, struct_y, "second"))) {
for (i in seq_along(side[[1]])) {
for (j in seq_len(k)) {
heat_rows <- c(heat_rows, sprintf("%s (%s set)", side[[1]][i], side[[3]]))
heat_cols <- c(heat_cols, sprintf("Dimension %d", j))
heat_vals <- c(heat_vals, side[[2]][i, j])
}
}
}
charts[[2]] <- cs_chart("structure", "matrix-heatmap", "Structure correlations", list(
row = cs_col("Variable", heat_rows, "categorical"),
col = cs_col("Dimension", heat_cols, "categorical"),
value = cs_col("Correlation with its canonical variate", heat_vals),
label = cs_col("Value", sprintf("%.2f", heat_vals), "categorical")))
label <- if (method == "kernel") "Kernel CCA" else if (ridge > 0) "Ridge CCA" else "Canonical correlation analysis"
sig <- !is.null(perm) && perm$p < alpha
summary <- paste0(sprintf("%s of %s with %s (%d rows): the first canonical correlation is r = %.3f", label, xs, ys, n, r[1]),
if (!is.null(perm)) sprintf(", %s by %d permutations", cs_fmt_p(perm$p), n_perm) else "",
if (!is.null(cv)) sprintf("; on held-out rows the first pair correlates r = %.3f (%d-fold)", cv$mean, cv_folds) else "", ". ",
if (sig && method == "linear") "The two sets share a linear relation." else if (sig) "The two sets are related."
else if (!is.null(perm)) "No evidence that the sets are related." else "")
note <- paste0("Variables standardized; ",
if (method == "linear" && ridge > 0) sprintf("ridge %s added to each set's correlation matrix (regularized ρ is the maximized criterion, r the correlation of the resulting variates); ", format(ridge)) else "",
if (method == "kernel") paste0(sprintf("kernel %s", kernel_type),
if (kernel_type == "rbf" && bandwidth == 0) sprintf(", bandwidths %s and %s (median distance)", format(signif(fit$sigma_x, 3)), format(signif(fit$sigma_y, 3))) else "",
sprintf(", regularization κ = %s × (n − 1); ", format(reg))) else "",
"signs make each dimension's largest first-set structure correlation positive",
if (!is.null(perm)) sprintf("; permutation p for the first correlation from %d row permutations of the second set (seed %d)", n_perm, as.integer(seed)) else "",
if (!is.null(cv)) sprintf("; held-out r = mean over %d folds of the first pair's correlation on rows the fit did not see", cv_folds) else "", ".")
cs_publish(list(
method = "multivariate.cca",
methodVersion = "1.0.0",
title = label,
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = trimws(summary),
apa = paste0(sprintf("%s, first canonical r = %.2f", label, r[1]), if (!is.null(perm)) sprintf(", permutation %s", cs_fmt_p(perm$p)) else ""),
statistics = list(list(key = "r1", label = "First canonical r", value = r[1]),
list(key = "p_perm", label = "Permutation p", value = values$p_perm, format = "p"),
list(key = "cv_r", label = "Held-out r", value = values$cv_r)),
tables = tables,
effectSizes = list(list(key = "r1", label = "First canonical correlation", value = r[1], method = "Correlation of the first pair of canonical variates")),
assumptions = assumptions,
warnings = warnings,
notes = list(note),
values = values,
charts = charts
))
Canonical correlation analysis, first canonical r = 0.82, permutation p = .005
- First canonical r
- 0.8248
- Permutation p
- .005
- Held-out r
- 0.8131
Effect size
- First canonical correlation 0.8248
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Linear relations — Each canonical variate is a weighted sum of its set's variables; curved relations are missed (kernel CCA catches them).
- Multivariate normality (for Bartlett's test) — Bartlett's chi-square tests assume multivariate normal sets; the permutation p does not.
- Rows per variable — 50 rows for 5 variables (10.0 per variable). Enough for stable weights.
Canonical correlations
| Dimension | Canonical r | r² | Wilks Λ | χ² | df | p (dimensions i…k) |
|---|---|---|---|---|---|---|
| 1 | 0.8248 | 0.6803 | 0.2771 | 59.043 | 6 | < .001 |
| 2 | 0.3653 | 0.1334 | 0.8666 | 6.588 | 2 | .037 |
Structure correlations: first set with its canonical variates
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| pop15 | 0.9830 | 0.1837 |
| pop75 | −0.9698 | 0.2439 |
Structure correlations: second set with its canonical variates
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| sr | −0.4910 | −0.8558 |
| dpi | −0.9545 | 0.2637 |
| ddpi | −0.0473 | −0.1408 |
Standardized canonical weights: first set
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| pop15 | 0.5837 | 2.320 |
| pop75 | −0.4395 | 2.352 |
Standardized canonical weights: second set
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| sr | −0.2657 | −1.047 |
| dpi | −0.9068 | 0.5263 |
| ddpi | −0.0838 | 0.2465 |
Variance extracted and redundancy
| Dimension | First set: own variate | First set: by the other variate | Second set: own variate | Second set: by the other variate |
|---|---|---|---|---|
| 1 | 95.3% | 64.9% | 38.5% | 26.2% |
| 2 | 4.7% | 0.6% | 27.4% | 3.7% |
Held-out correlation of the first pair (5-fold)
| Fold | Held-out r |
|---|---|
| 1 | 0.7283 |
| 2 | 0.8361 |
| 3 | 0.9057 |
| 4 | 0.9140 |
| 5 | 0.6811 |
- Variables standardized; signs make each dimension's largest first-set structure correlation positive; permutation p for the first correlation from 199 row permutations of the second set (seed 42); held-out r = mean over 5 folds of the first pair's correlation on rows the fit did not see.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Canonical correlation analysis (CCA, ridge and kernel CCA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.cca 1.0.0 · spec 08dfc48621ffa8b6
# Dataset: rep2_lifecycle (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash.stats import multiview as mvw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/rep2_lifecycle.parquet", columns=["pop15", "pop75", "sr", "dpi", "ddpi"])
n_input = len(df)
df = df.dropna(subset=["pop15", "pop75", "sr", "dpi", "ddpi"]) # listwise deletion over the analysis columns
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, ["pop15", "pop75", "sr", "dpi", "ddpi"]) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Canonical correlation analysis (Hotelling 1936): pairs of weighted sums, one per set, that correlate as
# much as possible. Linear CCA (optional ridge, Vinod 1976) or regularized kernel CCA (Hardoon et al. 2004).
x_vars = ["pop15", "pop75"]
y_vars = ["sr", "dpi", "ddpi"]
method = "linear" # linear | kernel
ridge = float(0)
kernel_type = "rbf" # rbf | linear
bandwidth = float(0)
reg = float(0.1)
n_comp = int(2)
n_perm = int(199) if method == "linear" else int(199)
cv_folds = int(5)
alpha = 0.05
seed = 42
both = [v for v in x_vars if v in y_vars]
if both:
cs.cs_error("CS_E_INVALID_OPTION", option="The two sets", allowed="separate variables (none in both sets)", value=both[0])
n = len(df)
p, q = len(x_vars), len(y_vars)
cs.check_rows(n, p + q + 2 if method == "linear" and ridge == 0 else 5, "Canonical correlation analysis")
for v in x_vars + y_vars:
check_not_constant(df[v], v)
if method == "kernel" and n > 2000:
cs.cs_error("CS_E_UNDEFINED", what="Kernel CCA", reason=f"it uses n × n kernel matrices; {n} rows is too many (at most 2,000)")
X = df[x_vars].to_numpy(dtype=float)
Y = df[y_vars].to_numpy(dtype=float)
if method == "linear":
fit = mvw.cca(X, Y, ridge)
k = fit["k"]
r, rho = fit["r"], fit["rho"]
u, v = fit["u"][:, 0], fit["v"][:, 0]
struct_x, struct_y = fit["struct_x"], fit["struct_y"]
bart = mvw.bartlett(r, n, p, q) if ridge == 0 else None
else:
fit = mvw.kcca(X, Y, kernel_type, reg, n_comp, bandwidth)
k = len(fit["rho"])
r, rho = fit["r_train"], fit["rho"]
u, v = fit["F"][:, 0], fit["G"][:, 0]
u, v = (u - u.mean()) / u.std(ddof=1), (v - v.mean()) / v.std(ddof=1)
struct_x, struct_y = fit["struct_x"], fit["struct_y"]
bart = None
perm = None
if n_perm > 0:
perm = (mvw.cca_permutation(X, Y, ridge, n_perm, seed) if method == "linear"
else mvw.kcca_permutation(X, Y, kernel_type, reg, bandwidth, n_perm, seed))
cv = None
if cv_folds >= 2:
cv = (mvw.cca_cv(X, Y, ridge, cv_folds, seed) if method == "linear"
else mvw.kcca_cv(X, Y, kernel_type, reg, bandwidth, cv_folds, seed))
# %% Assumptions
ratio = n / (p + q)
assumptions = [
{"key": "linear", "label": "Linear relations" if method == "linear" else "Smooth relations (kernel)", "status": "info",
"detail": ("Each canonical variate is a weighted sum of its set's variables; curved relations are missed (kernel CCA catches them)."
if method == "linear" else "The RBF kernel lets each variate be a smooth nonlinear function; the regularization keeps it from fitting noise, so judge it by the held-out correlation.")},
{"key": "normality", "label": "Multivariate normality (for Bartlett's test)", "status": "info",
"detail": "Bartlett's chi-square tests assume multivariate normal sets; the permutation p does not." if bart is not None
else "No normal-theory test is reported here; the permutation p only assumes exchangeable rows."},
{"key": "rows_per_variable", "label": "Rows per variable", "status": "ok" if ratio >= 10 else "warn",
"detail": f"{n} rows for {p + q} variables ({ratio:.1f} per variable). " + ("Enough for stable weights." if ratio >= 10
else "Canonical weights and correlations are unstable below about 10 rows per variable; trust the held-out correlation and structure correlations more than the weights.")},
]
# %% Result
values = {"n": n, "p": p, "q": q, "k": k, "r1": float(r[0]), "rho1": float(rho[0]),
"ridge": ridge if method == "linear" else float("nan"), "reg": reg if method == "kernel" else float("nan"),
"p_perm": perm["p"] if perm else float("nan"), "n_perm": n_perm if perm else 0,
"cv_r": cv["mean"] if cv else float("nan"), "cv_folds": cv_folds if cv else 0,
"wilks": bart[0]["wilks"] if bart else float("nan"), "chisq": bart[0]["chisq"] if bart else float("nan"),
"df": bart[0]["df"] if bart else float("nan"), "p_bartlett": bart[0]["p"] if bart else float("nan"),
"redundancy_y": float(np.sum(fit["redundancy_y"])) if method == "linear" else float("nan"),
"redundancy_x": float(np.sum(fit["redundancy_x"])) if method == "linear" else float("nan"),
"sigma_x": fit["sigma_x"] if method == "kernel" and kernel_type == "rbf" else float("nan"),
"sigma_y": fit["sigma_y"] if method == "kernel" and kernel_type == "rbf" else float("nan")}
for j in range(k):
values[f"r[{j + 1}]"] = float(r[j])
values[f"rho[{j + 1}]"] = float(rho[j])
if bart:
values[f"p_dim[{j + 1}]"] = bart[j]["p"]
values["missing_share"] = n_dropped / n_input if n_input else 0.0
cols = [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "r", "label": "Canonical r", "type": "number"},
{"key": "r2", "label": "r²", "type": "number"}]
if method == "kernel" or ridge > 0:
cols.append({"key": "rho", "label": "Regularized ρ", "type": "number"})
if bart:
cols += [{"key": "wilks", "label": "Wilks Λ", "type": "number"}, {"key": "chisq", "label": "χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p (dimensions i…k)", "type": "pvalue"}]
rows = []
for j in range(k):
row = {"dimension": j + 1, "r": float(r[j]), "r2": float(r[j] ** 2), "rho": float(rho[j])}
if bart:
row.update({"wilks": bart[j]["wilks"], "chisq": bart[j]["chisq"], "df": bart[j]["df"], "p": bart[j]["p"]})
rows.append(row)
tables = [{"key": "canonical", "title": "Canonical correlations", "columns": cols, "rows": rows}]
def struct_table(key, title, names, M):
return {"key": key, "title": title,
"columns": [{"key": "variable", "label": "Variable", "type": "string"}]
+ [{"key": f"d{j + 1}", "label": f"Dimension {j + 1}", "type": "number"} for j in range(k)],
"rows": [{"variable": nm, **{f"d{j + 1}": float(M[i, j]) for j in range(k)}} for i, nm in enumerate(names)]}
tables.append(struct_table("structure_x", "Structure correlations: first set with its canonical variates", x_vars, struct_x))
tables.append(struct_table("structure_y", "Structure correlations: second set with its canonical variates", y_vars, struct_y))
if method == "linear":
tables.append(struct_table("coef_x", "Standardized canonical weights: first set", x_vars, fit["coef_x"]))
tables.append(struct_table("coef_y", "Standardized canonical weights: second set", y_vars, fit["coef_y"]))
tables.append({"key": "redundancy", "title": "Variance extracted and redundancy",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"},
{"key": "extracted_x", "label": "First set: own variate", "type": "percent"},
{"key": "redundancy_x", "label": "First set: by the other variate", "type": "percent"},
{"key": "extracted_y", "label": "Second set: own variate", "type": "percent"},
{"key": "redundancy_y", "label": "Second set: by the other variate", "type": "percent"}],
"rows": [{"dimension": j + 1, "extracted_x": float(fit["extracted_x"][j]), "redundancy_x": float(fit["redundancy_x"][j]),
"extracted_y": float(fit["extracted_y"][j]), "redundancy_y": float(fit["redundancy_y"][j])} for j in range(k)]})
if cv:
tables.append({"key": "cv", "title": f"Held-out correlation of the first pair ({cv_folds}-fold)",
"columns": [{"key": "fold", "label": "Fold", "type": "integer"}, {"key": "r", "label": "Held-out r", "type": "number"}],
"rows": [{"fold": i + 1, "r": float(x)} for i, x in enumerate(cv["folds"])]})
xs, ys = ", ".join(x_vars), ", ".join(y_vars)
charts = [cs.chart("pair", "scatter", "First canonical pair", {
"x": cs.col(f"Canonical variate 1 of {xs}", u),
"y": cs.col(f"Canonical variate 1 of {ys}", v)})]
heat_rows, heat_cols, heat_vals = [], [], []
for names, M, side in ((x_vars, struct_x, "first"), (y_vars, struct_y, "second")):
for i, nm in enumerate(names):
for j in range(k):
heat_rows.append(f"{nm} ({side} set)")
heat_cols.append(f"Dimension {j + 1}")
heat_vals.append(float(M[i, j]))
charts.append(cs.chart("structure", "matrix-heatmap", "Structure correlations", {
"row": cs.col("Variable", heat_rows, "categorical"),
"col": cs.col("Dimension", heat_cols, "categorical"),
"value": cs.col("Correlation with its canonical variate", np.array(heat_vals)),
"label": cs.col("Value", [f"{x:.2f}" for x in heat_vals], "categorical")}))
label = "Kernel CCA" if method == "kernel" else ("Ridge CCA" if ridge > 0 else "Canonical correlation analysis")
sig = perm is not None and perm["p"] < alpha
summary = (f"{label} of {xs} with {ys} ({n} rows): the first canonical correlation is r = {r[0]:.3f}"
+ (f", {cs.fmt_p(perm['p'])} by {n_perm} permutations" if perm else "")
+ (f"; on held-out rows the first pair correlates r = {cv['mean']:.3f} ({cv_folds}-fold)" if cv else "") + ". "
+ ("The two sets share a linear relation." if sig and method == "linear" else "The two sets are related." if sig
else "No evidence that the sets are related." if perm else ""))
cs.publish({
"method": "multivariate.cca",
"methodVersion": "1.0.0",
"title": label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary.strip(),
"apa": f"{label}, first canonical r = {r[0]:.2f}" + (f", permutation {cs.fmt_p(perm['p'])}" if perm else ""),
"statistics": [{"key": "r1", "label": "First canonical r", "value": float(r[0])},
{"key": "p_perm", "label": "Permutation p", "value": values["p_perm"], "format": "p"},
{"key": "cv_r", "label": "Held-out r", "value": values["cv_r"]}],
"tables": tables,
"effectSizes": [{"key": "r1", "label": "First canonical correlation", "value": float(r[0]), "method": "Correlation of the first pair of canonical variates"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [("Variables standardized; " + (f"ridge {ridge:g} added to each set's correlation matrix (regularized ρ is the maximized criterion, r the correlation of the resulting variates); " if method == "linear" and ridge > 0 else "")
+ (f"kernel {kernel_type}" + (f", bandwidths {fit['sigma_x']:.3g} and {fit['sigma_y']:.3g} (median distance)" if kernel_type == "rbf" and bandwidth == 0 else "")
+ f", regularization κ = {reg:g} × (n − 1); " if method == "kernel" else "")
+ "signs make each dimension's largest first-set structure correlation positive"
+ (f"; permutation p for the first correlation from {n_perm} row permutations of the second set (seed {seed})" if perm else "")
+ (f"; held-out r = mean over {cv_folds} folds of the first pair's correlation on rows the fit did not see" if cv else "") + ".")],
"values": values,
"charts": charts,
})
For 50 countries, the first canonical correlation between age structure and savings variables is 0.825. Held out by cross-validation it is 0.813, and the permutation p-value is 0.005. The second, 0.365, is much weaker.
Predict
PredictPredict first
Two tables of pure random noise share 30 rows; each has 12 columns. What will CCA's first in-sample canonical correlation be?
Reveal
Near 1. With 24 columns for 30 rows, CCA can almost always find weights that line the two tables up on the sample. Only held-out rows or a permutation test reveal that nothing is there.
Perfect correlation for free
ReadCCA picks the best weights from all possible ones. When approaches , it can always find weights that make the two sums agree on the sample, so the first canonical correlation climbs toward 1 even for unrelated tables.
Three defenses:
- Held-out correlation: apply the weights to rows they didn't see.
- Permutation: shuffle the rows of one table to break the pairing, refit, and see how often chance does as well.
- Ridge: add to and , which shrinks the weights and stabilizes them.
High correlation can also come from a shared nuisance, such as both tables measured in the same batch.
Curved relationships: kernel CCA
ReadKernel CCAKernel CCACCA on kernel similarities so each variate can be a smooth nonlinear function of its set; needs regularization. finds correlated functions of each table, and , using kernel matrices built from the rows. Without regularization it can interpolate any pairing perfectly, so the penalty is essential, not optional. It costs in memory.
Kernel CCA, first canonical r = 0.78, permutation p = .020
- First canonical r
- 0.7839
- Permutation p
- .020
- Held-out r
- 0.6800
Effect size
- First canonical correlation 0.7839
Plots
View data
| Canonical variate 1 of x1, x2, x3 | Canonical variate 1 of y1, y2, y3 |
|---|---|
| −0.8502 | −0.7638 |
| −0.6935 | −1.347 |
| 1.785 | 0.8367 |
| −0.4225 | 0.1521 |
| −1.099 | 0.2307 |
| −1.522 | −1.746 |
| 2.226 | 1.659 |
| 0.3800 | 1.608 |
| 0.4353 | 0.9213 |
| −1.018 | −1.585 |
| −0.7020 | −1.083 |
| −0.0531 | 1.196 |
| 0.7073 | 0.3407 |
| 0.0016 | 1.610 |
| 1.552 | 1.698 |
| −0.8916 | 0.3577 |
| −1.472 | −1.058 |
| 0.2144 | 0.0260 |
| −0.2073 | −0.4460 |
| 0.3963 | 0.6140 |
| 0.6487 | 1.102 |
| −0.3359 | −0.9375 |
| −0.3692 | −1.602 |
| 1.544 | 1.763 |
| −1.224 | −1.140 |
| 1.380 | 0.5320 |
| 1.112 | 0.9643 |
| 1.791 | 1.821 |
| −0.0588 | 0.4719 |
| 0.5609 | −0.5310 |
| −0.3429 | 0.0131 |
| −0.2882 | −0.8533 |
| 0.4780 | −0.1106 |
| −1.205 | −1.555 |
| −1.637 | −1.416 |
| −0.8158 | 0.1410 |
| 1.739 | 1.420 |
| −0.0186 | 0.2194 |
| −1.305 | −1.298 |
| 1.566 | 1.176 |
| −0.6363 | −0.9961 |
| −1.149 | −1.309 |
| 0.5221 | −0.5121 |
| −0.5757 | −0.0352 |
| 0.6686 | 0.6024 |
| 0.3662 | −0.3661 |
| −1.169 | −1.398 |
| −1.384 | −1.433 |
| 1.651 | 0.5379 |
| −1.475 | −0.9249 |
| −1.593 | −1.234 |
| −1.051 | −0.0744 |
| 1.874 | 1.816 |
| 1.054 | 0.5146 |
| −0.9440 | −0.8591 |
| −1.242 | −0.4394 |
| 0.9436 | 1.750 |
| −0.1764 | 0.1090 |
| 0.6361 | 1.347 |
| −0.2310 | 0.1585 |
First 60 of 120 rows.
View data
| Dimension | Value | Variable | Correlation with its canonical variate |
|---|---|---|---|
| Dimension 1 | 0.05 | x1 (first set) | 0.0457 |
| Dimension 2 | 0.71 | x1 (first set) | 0.7103 |
| Dimension 1 | 0.58 | x2 (first set) | 0.5752 |
| Dimension 2 | 0.15 | x2 (first set) | 0.1501 |
| Dimension 1 | 0.19 | x3 (first set) | 0.1911 |
| Dimension 2 | 0.16 | x3 (first set) | 0.1633 |
| Dimension 1 | -0.71 | y1 (second set) | −0.7144 |
| Dimension 2 | -0.68 | y1 (second set) | −0.6832 |
| Dimension 1 | 0.74 | y2 (second set) | 0.7446 |
| Dimension 2 | -0.65 | y2 (second set) | −0.6513 |
| Dimension 1 | -0.01 | y3 (second set) | −0.0115 |
| Dimension 2 | 0.07 | y3 (second set) | 0.0667 |
Assumptions
- Smooth relations (kernel) — The RBF kernel lets each variate be a smooth nonlinear function; the regularization keeps it from fitting noise, so judge it by the held-out correlation.
- Multivariate normality (for Bartlett's test) — No normal-theory test is reported here; the permutation p only assumes exchangeable rows.
- Rows per variable — 120 rows for 6 variables (20.0 per variable). Enough for stable weights.
Canonical correlations
| Dimension | Canonical r | r² | Regularized ρ |
|---|---|---|---|
| 1 | 0.7839 | 0.6146 | 0.2698 |
| 2 | 0.6510 | 0.4239 | 0.1881 |
Structure correlations: first set with its canonical variates
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| x1 | 0.0457 | 0.7103 |
| x2 | 0.5752 | 0.1501 |
| x3 | 0.1911 | 0.1633 |
Structure correlations: second set with its canonical variates
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| y1 | −0.7144 | −0.6832 |
| y2 | 0.7446 | −0.6513 |
| y3 | −0.0115 | 0.0667 |
Held-out correlation of the first pair (5-fold)
| Fold | Held-out r |
|---|---|
| 1 | 0.5474 |
| 2 | 0.6952 |
| 3 | 0.7686 |
| 4 | 0.7667 |
| 5 | 0.6223 |
- Variables standardized; kernel rbf, bandwidths 2.24 and 2.24 (median distance), regularization κ = 0.1 × (n − 1); signs make each dimension's largest first-set structure correlation positive; permutation p for the first correlation from 49 row permutations of the second set (seed 42); held-out r = mean over 5 folds of the first pair's correlation on rows the fit did not see.
The exact R script · R R version 4.5.1 (2025-06-13)
# Canonical correlation analysis (CCA, ridge and kernel CCA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.cca 1.0.0 · spec 3a234f38cea42900
# Dataset: rep2_nonlinear (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_nonlinear.parquet", col_select = c("x1", "x2", "x3", "y1", "y2", "y3")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x1", "x2", "x3", "y1", "y2", "y3")]), , 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("x1", "x2", "x3", "y1", "y2", "y3")) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Canonical correlation analysis (Hotelling 1936): pairs of weighted sums, one per set, that correlate as
# much as possible. Linear CCA (optional ridge, Vinod 1976) or regularized kernel CCA (Hardoon et al. 2004).
x_vars <- c("x1", "x2", "x3")
y_vars <- c("y1", "y2", "y3")
method <- "kernel" # linear | kernel
ridge <- as.numeric(0)
kernel_type <- "rbf" # rbf | linear
bandwidth <- as.numeric(0)
reg <- as.numeric(0.1)
n_comp <- as.integer(2)
n_perm <- if (method == "linear") as.integer(999) else as.integer(49)
cv_folds <- as.integer(5)
alpha <- 0.05
seed <- 42
both <- x_vars[x_vars %in% y_vars]
if (length(both)) cs_error("CS_E_INVALID_OPTION", option = "The two sets", allowed = "separate variables (none in both sets)", value = both[1])
n <- nrow(df)
p <- length(x_vars)
q <- length(y_vars)
cs_check_rows(n, if (method == "linear" && ridge == 0) p + q + 2 else 5, "Canonical correlation analysis")
for (v in c(x_vars, y_vars)) cs_check_not_constant(df[[v]], v)
if (method == "kernel" && n > 2000) {
cs_error("CS_E_UNDEFINED", what = "Kernel CCA", reason = sprintf("it uses n × n kernel matrices; %d rows is too many (at most 2,000)", n))
}
X <- as.matrix(df[x_vars])
Y <- as.matrix(df[y_vars])
storage.mode(X) <- "double"
storage.mode(Y) <- "double"
if (method == "linear") {
fit <- cs_mview_cca(X, Y, ridge)
k <- fit$k
r <- fit$r
rho <- fit$rho
u <- fit$u[, 1]
v <- fit$v[, 1]
struct_x <- fit$struct_x
struct_y <- fit$struct_y
bart <- if (ridge == 0) cs_mview_bartlett(r, n, p, q) else NULL
} else {
fit <- cs_mview_kcca(X, Y, kernel_type, reg, n_comp, bandwidth)
k <- length(fit$rho)
r <- fit$r_train
rho <- fit$rho
u <- fit$F[, 1]
v <- fit$G[, 1]
u <- (u - mean(u)) / stats::sd(u)
v <- (v - mean(v)) / stats::sd(v)
struct_x <- fit$struct_x
struct_y <- fit$struct_y
bart <- NULL
}
perm <- NULL
if (n_perm > 0) {
perm <- if (method == "linear") cs_mview_cca_permutation(X, Y, ridge, n_perm, seed)
else cs_mview_kcca_permutation(X, Y, kernel_type, reg, bandwidth, n_perm, seed)
}
cv <- NULL
if (cv_folds >= 2) {
cv <- if (method == "linear") cs_mview_cca_cv(X, Y, ridge, cv_folds, seed)
else cs_mview_kcca_cv(X, Y, kernel_type, reg, bandwidth, cv_folds, seed)
}
# %% Assumptions
ratio <- n / (p + q)
assumptions <- list(
list(key = "linear", label = if (method == "linear") "Linear relations" else "Smooth relations (kernel)", status = "info",
detail = if (method == "linear") "Each canonical variate is a weighted sum of its set's variables; curved relations are missed (kernel CCA catches them)."
else "The RBF kernel lets each variate be a smooth nonlinear function; the regularization keeps it from fitting noise, so judge it by the held-out correlation."),
list(key = "normality", label = "Multivariate normality (for Bartlett's test)", status = "info",
detail = if (!is.null(bart)) "Bartlett's chi-square tests assume multivariate normal sets; the permutation p does not."
else "No normal-theory test is reported here; the permutation p only assumes exchangeable rows."),
list(key = "rows_per_variable", label = "Rows per variable", status = if (ratio >= 10) "ok" else "warn",
detail = paste0(sprintf("%d rows for %d variables (%.1f per variable). ", n, p + q, ratio),
if (ratio >= 10) "Enough for stable weights."
else "Canonical weights and correlations are unstable below about 10 rows per variable; trust the held-out correlation and structure correlations more than the weights."))
)
# %% Result
nan_or <- function(cond, x) if (cond) x else NaN
values <- list(n = n, p = p, q = q, k = k, r1 = r[1], rho1 = rho[1],
ridge = nan_or(method == "linear", ridge), reg = nan_or(method == "kernel", reg),
p_perm = if (!is.null(perm)) perm$p else NaN, n_perm = if (!is.null(perm)) n_perm else 0L,
cv_r = if (!is.null(cv)) cv$mean else NaN, cv_folds = if (!is.null(cv)) cv_folds else 0L,
wilks = if (!is.null(bart)) bart[[1]]$wilks else NaN, chisq = if (!is.null(bart)) bart[[1]]$chisq else NaN,
df = if (!is.null(bart)) bart[[1]]$df else NaN, p_bartlett = if (!is.null(bart)) bart[[1]]$p else NaN,
redundancy_y = nan_or(method == "linear", sum(fit$redundancy_y)),
redundancy_x = nan_or(method == "linear", sum(fit$redundancy_x)),
sigma_x = nan_or(method == "kernel" && kernel_type == "rbf", fit$sigma_x),
sigma_y = nan_or(method == "kernel" && kernel_type == "rbf", fit$sigma_y))
for (j in seq_len(k)) {
values[[sprintf("r[%d]", j)]] <- r[j]
values[[sprintf("rho[%d]", j)]] <- rho[j]
if (!is.null(bart)) values[[sprintf("p_dim[%d]", j)]] <- bart[[j]]$p
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
cols <- list(list(key = "dimension", label = "Dimension", type = "integer"), list(key = "r", label = "Canonical r", type = "number"),
list(key = "r2", label = "r²", type = "number"))
if (method == "kernel" || ridge > 0) cols <- c(cols, list(list(key = "rho", label = "Regularized ρ", type = "number")))
if (!is.null(bart)) {
cols <- c(cols, list(list(key = "wilks", label = "Wilks Λ", type = "number"), list(key = "chisq", label = "χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p (dimensions i…k)", type = "pvalue")))
}
rows <- lapply(seq_len(k), function(j) {
row <- list(dimension = j, r = r[j], r2 = r[j]^2, rho = rho[j])
if (!is.null(bart)) row <- c(row, list(wilks = bart[[j]]$wilks, chisq = bart[[j]]$chisq, df = bart[[j]]$df, p = bart[[j]]$p))
row
})
tables <- list(list(key = "canonical", title = "Canonical correlations", columns = cols, rows = rows))
struct_table <- function(key, title, names, M) {
list(key = key, title = title,
columns = c(list(list(key = "variable", label = "Variable", type = "string")),
lapply(seq_len(k), function(j) list(key = sprintf("d%d", j), label = sprintf("Dimension %d", j), type = "number"))),
rows = lapply(seq_along(names), function(i) {
row <- list(variable = names[i])
for (j in seq_len(k)) row[[sprintf("d%d", j)]] <- M[i, j]
row
}))
}
tables[[length(tables) + 1]] <- struct_table("structure_x", "Structure correlations: first set with its canonical variates", x_vars, struct_x)
tables[[length(tables) + 1]] <- struct_table("structure_y", "Structure correlations: second set with its canonical variates", y_vars, struct_y)
if (method == "linear") {
tables[[length(tables) + 1]] <- struct_table("coef_x", "Standardized canonical weights: first set", x_vars, fit$coef_x)
tables[[length(tables) + 1]] <- struct_table("coef_y", "Standardized canonical weights: second set", y_vars, fit$coef_y)
tables[[length(tables) + 1]] <- list(key = "redundancy", title = "Variance extracted and redundancy",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"),
list(key = "extracted_x", label = "First set: own variate", type = "percent"),
list(key = "redundancy_x", label = "First set: by the other variate", type = "percent"),
list(key = "extracted_y", label = "Second set: own variate", type = "percent"),
list(key = "redundancy_y", label = "Second set: by the other variate", type = "percent")),
rows = lapply(seq_len(k), function(j) list(dimension = j, extracted_x = fit$extracted_x[j], redundancy_x = fit$redundancy_x[j],
extracted_y = fit$extracted_y[j], redundancy_y = fit$redundancy_y[j])))
}
if (!is.null(cv)) {
tables[[length(tables) + 1]] <- list(key = "cv", title = sprintf("Held-out correlation of the first pair (%d-fold)", cv_folds),
columns = list(list(key = "fold", label = "Fold", type = "integer"), list(key = "r", label = "Held-out r", type = "number")),
rows = lapply(seq_along(cv$folds), function(i) list(fold = i, r = cv$folds[i])))
}
xs <- paste(x_vars, collapse = ", ")
ys <- paste(y_vars, collapse = ", ")
charts <- list(cs_chart("pair", "scatter", "First canonical pair", list(
x = cs_col(sprintf("Canonical variate 1 of %s", xs), u),
y = cs_col(sprintf("Canonical variate 1 of %s", ys), v))))
heat_rows <- character(0); heat_cols <- character(0); heat_vals <- numeric(0)
for (side in list(list(x_vars, struct_x, "first"), list(y_vars, struct_y, "second"))) {
for (i in seq_along(side[[1]])) {
for (j in seq_len(k)) {
heat_rows <- c(heat_rows, sprintf("%s (%s set)", side[[1]][i], side[[3]]))
heat_cols <- c(heat_cols, sprintf("Dimension %d", j))
heat_vals <- c(heat_vals, side[[2]][i, j])
}
}
}
charts[[2]] <- cs_chart("structure", "matrix-heatmap", "Structure correlations", list(
row = cs_col("Variable", heat_rows, "categorical"),
col = cs_col("Dimension", heat_cols, "categorical"),
value = cs_col("Correlation with its canonical variate", heat_vals),
label = cs_col("Value", sprintf("%.2f", heat_vals), "categorical")))
label <- if (method == "kernel") "Kernel CCA" else if (ridge > 0) "Ridge CCA" else "Canonical correlation analysis"
sig <- !is.null(perm) && perm$p < alpha
summary <- paste0(sprintf("%s of %s with %s (%d rows): the first canonical correlation is r = %.3f", label, xs, ys, n, r[1]),
if (!is.null(perm)) sprintf(", %s by %d permutations", cs_fmt_p(perm$p), n_perm) else "",
if (!is.null(cv)) sprintf("; on held-out rows the first pair correlates r = %.3f (%d-fold)", cv$mean, cv_folds) else "", ". ",
if (sig && method == "linear") "The two sets share a linear relation." else if (sig) "The two sets are related."
else if (!is.null(perm)) "No evidence that the sets are related." else "")
note <- paste0("Variables standardized; ",
if (method == "linear" && ridge > 0) sprintf("ridge %s added to each set's correlation matrix (regularized ρ is the maximized criterion, r the correlation of the resulting variates); ", format(ridge)) else "",
if (method == "kernel") paste0(sprintf("kernel %s", kernel_type),
if (kernel_type == "rbf" && bandwidth == 0) sprintf(", bandwidths %s and %s (median distance)", format(signif(fit$sigma_x, 3)), format(signif(fit$sigma_y, 3))) else "",
sprintf(", regularization κ = %s × (n − 1); ", format(reg))) else "",
"signs make each dimension's largest first-set structure correlation positive",
if (!is.null(perm)) sprintf("; permutation p for the first correlation from %d row permutations of the second set (seed %d)", n_perm, as.integer(seed)) else "",
if (!is.null(cv)) sprintf("; held-out r = mean over %d folds of the first pair's correlation on rows the fit did not see", cv_folds) else "", ".")
cs_publish(list(
method = "multivariate.cca",
methodVersion = "1.0.0",
title = label,
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = trimws(summary),
apa = paste0(sprintf("%s, first canonical r = %.2f", label, r[1]), if (!is.null(perm)) sprintf(", permutation %s", cs_fmt_p(perm$p)) else ""),
statistics = list(list(key = "r1", label = "First canonical r", value = r[1]),
list(key = "p_perm", label = "Permutation p", value = values$p_perm, format = "p"),
list(key = "cv_r", label = "Held-out r", value = values$cv_r)),
tables = tables,
effectSizes = list(list(key = "r1", label = "First canonical correlation", value = r[1], method = "Correlation of the first pair of canonical variates")),
assumptions = assumptions,
warnings = warnings,
notes = list(note),
values = values,
charts = charts
))
Kernel CCA, first canonical r = 0.78, permutation p = .020
- First canonical r
- 0.7839
- Permutation p
- .020
- Held-out r
- 0.6800
Effect size
- First canonical correlation 0.7839
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Smooth relations (kernel) — The RBF kernel lets each variate be a smooth nonlinear function; the regularization keeps it from fitting noise, so judge it by the held-out correlation.
- Multivariate normality (for Bartlett's test) — No normal-theory test is reported here; the permutation p only assumes exchangeable rows.
- Rows per variable — 120 rows for 6 variables (20.0 per variable). Enough for stable weights.
Canonical correlations
| Dimension | Canonical r | r² | Regularized ρ |
|---|---|---|---|
| 1 | 0.7839 | 0.6146 | 0.2698 |
| 2 | 0.6510 | 0.4239 | 0.1881 |
Structure correlations: first set with its canonical variates
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| x1 | 0.0457 | 0.7103 |
| x2 | 0.5752 | 0.1501 |
| x3 | 0.1911 | 0.1633 |
Structure correlations: second set with its canonical variates
| Variable | Dimension 1 | Dimension 2 |
|---|---|---|
| y1 | −0.7144 | −0.6832 |
| y2 | 0.7446 | −0.6513 |
| y3 | −0.0115 | 0.0667 |
Held-out correlation of the first pair (5-fold)
| Fold | Held-out r |
|---|---|
| 1 | 0.5474 |
| 2 | 0.6952 |
| 3 | 0.7686 |
| 4 | 0.7667 |
| 5 | 0.6223 |
- Variables standardized; kernel rbf, bandwidths 2.24 and 2.24 (median distance), regularization κ = 0.1 × (n − 1); signs make each dimension's largest first-set structure correlation positive; permutation p for the first correlation from 49 row permutations of the second set (seed 42); held-out r = mean over 5 folds of the first pair's correlation on rows the fit did not see.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Canonical correlation analysis (CCA, ridge and kernel CCA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.cca 1.0.0 · spec 3a234f38cea42900
# Dataset: rep2_nonlinear (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash.stats import multiview as mvw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/rep2_nonlinear.parquet", columns=["x1", "x2", "x3", "y1", "y2", "y3"])
n_input = len(df)
df = df.dropna(subset=["x1", "x2", "x3", "y1", "y2", "y3"]) # listwise deletion over the analysis columns
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, ["x1", "x2", "x3", "y1", "y2", "y3"]) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Canonical correlation analysis (Hotelling 1936): pairs of weighted sums, one per set, that correlate as
# much as possible. Linear CCA (optional ridge, Vinod 1976) or regularized kernel CCA (Hardoon et al. 2004).
x_vars = ["x1", "x2", "x3"]
y_vars = ["y1", "y2", "y3"]
method = "kernel" # linear | kernel
ridge = float(0)
kernel_type = "rbf" # rbf | linear
bandwidth = float(0)
reg = float(0.1)
n_comp = int(2)
n_perm = int(999) if method == "linear" else int(49)
cv_folds = int(5)
alpha = 0.05
seed = 42
both = [v for v in x_vars if v in y_vars]
if both:
cs.cs_error("CS_E_INVALID_OPTION", option="The two sets", allowed="separate variables (none in both sets)", value=both[0])
n = len(df)
p, q = len(x_vars), len(y_vars)
cs.check_rows(n, p + q + 2 if method == "linear" and ridge == 0 else 5, "Canonical correlation analysis")
for v in x_vars + y_vars:
check_not_constant(df[v], v)
if method == "kernel" and n > 2000:
cs.cs_error("CS_E_UNDEFINED", what="Kernel CCA", reason=f"it uses n × n kernel matrices; {n} rows is too many (at most 2,000)")
X = df[x_vars].to_numpy(dtype=float)
Y = df[y_vars].to_numpy(dtype=float)
if method == "linear":
fit = mvw.cca(X, Y, ridge)
k = fit["k"]
r, rho = fit["r"], fit["rho"]
u, v = fit["u"][:, 0], fit["v"][:, 0]
struct_x, struct_y = fit["struct_x"], fit["struct_y"]
bart = mvw.bartlett(r, n, p, q) if ridge == 0 else None
else:
fit = mvw.kcca(X, Y, kernel_type, reg, n_comp, bandwidth)
k = len(fit["rho"])
r, rho = fit["r_train"], fit["rho"]
u, v = fit["F"][:, 0], fit["G"][:, 0]
u, v = (u - u.mean()) / u.std(ddof=1), (v - v.mean()) / v.std(ddof=1)
struct_x, struct_y = fit["struct_x"], fit["struct_y"]
bart = None
perm = None
if n_perm > 0:
perm = (mvw.cca_permutation(X, Y, ridge, n_perm, seed) if method == "linear"
else mvw.kcca_permutation(X, Y, kernel_type, reg, bandwidth, n_perm, seed))
cv = None
if cv_folds >= 2:
cv = (mvw.cca_cv(X, Y, ridge, cv_folds, seed) if method == "linear"
else mvw.kcca_cv(X, Y, kernel_type, reg, bandwidth, cv_folds, seed))
# %% Assumptions
ratio = n / (p + q)
assumptions = [
{"key": "linear", "label": "Linear relations" if method == "linear" else "Smooth relations (kernel)", "status": "info",
"detail": ("Each canonical variate is a weighted sum of its set's variables; curved relations are missed (kernel CCA catches them)."
if method == "linear" else "The RBF kernel lets each variate be a smooth nonlinear function; the regularization keeps it from fitting noise, so judge it by the held-out correlation.")},
{"key": "normality", "label": "Multivariate normality (for Bartlett's test)", "status": "info",
"detail": "Bartlett's chi-square tests assume multivariate normal sets; the permutation p does not." if bart is not None
else "No normal-theory test is reported here; the permutation p only assumes exchangeable rows."},
{"key": "rows_per_variable", "label": "Rows per variable", "status": "ok" if ratio >= 10 else "warn",
"detail": f"{n} rows for {p + q} variables ({ratio:.1f} per variable). " + ("Enough for stable weights." if ratio >= 10
else "Canonical weights and correlations are unstable below about 10 rows per variable; trust the held-out correlation and structure correlations more than the weights.")},
]
# %% Result
values = {"n": n, "p": p, "q": q, "k": k, "r1": float(r[0]), "rho1": float(rho[0]),
"ridge": ridge if method == "linear" else float("nan"), "reg": reg if method == "kernel" else float("nan"),
"p_perm": perm["p"] if perm else float("nan"), "n_perm": n_perm if perm else 0,
"cv_r": cv["mean"] if cv else float("nan"), "cv_folds": cv_folds if cv else 0,
"wilks": bart[0]["wilks"] if bart else float("nan"), "chisq": bart[0]["chisq"] if bart else float("nan"),
"df": bart[0]["df"] if bart else float("nan"), "p_bartlett": bart[0]["p"] if bart else float("nan"),
"redundancy_y": float(np.sum(fit["redundancy_y"])) if method == "linear" else float("nan"),
"redundancy_x": float(np.sum(fit["redundancy_x"])) if method == "linear" else float("nan"),
"sigma_x": fit["sigma_x"] if method == "kernel" and kernel_type == "rbf" else float("nan"),
"sigma_y": fit["sigma_y"] if method == "kernel" and kernel_type == "rbf" else float("nan")}
for j in range(k):
values[f"r[{j + 1}]"] = float(r[j])
values[f"rho[{j + 1}]"] = float(rho[j])
if bart:
values[f"p_dim[{j + 1}]"] = bart[j]["p"]
values["missing_share"] = n_dropped / n_input if n_input else 0.0
cols = [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "r", "label": "Canonical r", "type": "number"},
{"key": "r2", "label": "r²", "type": "number"}]
if method == "kernel" or ridge > 0:
cols.append({"key": "rho", "label": "Regularized ρ", "type": "number"})
if bart:
cols += [{"key": "wilks", "label": "Wilks Λ", "type": "number"}, {"key": "chisq", "label": "χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p (dimensions i…k)", "type": "pvalue"}]
rows = []
for j in range(k):
row = {"dimension": j + 1, "r": float(r[j]), "r2": float(r[j] ** 2), "rho": float(rho[j])}
if bart:
row.update({"wilks": bart[j]["wilks"], "chisq": bart[j]["chisq"], "df": bart[j]["df"], "p": bart[j]["p"]})
rows.append(row)
tables = [{"key": "canonical", "title": "Canonical correlations", "columns": cols, "rows": rows}]
def struct_table(key, title, names, M):
return {"key": key, "title": title,
"columns": [{"key": "variable", "label": "Variable", "type": "string"}]
+ [{"key": f"d{j + 1}", "label": f"Dimension {j + 1}", "type": "number"} for j in range(k)],
"rows": [{"variable": nm, **{f"d{j + 1}": float(M[i, j]) for j in range(k)}} for i, nm in enumerate(names)]}
tables.append(struct_table("structure_x", "Structure correlations: first set with its canonical variates", x_vars, struct_x))
tables.append(struct_table("structure_y", "Structure correlations: second set with its canonical variates", y_vars, struct_y))
if method == "linear":
tables.append(struct_table("coef_x", "Standardized canonical weights: first set", x_vars, fit["coef_x"]))
tables.append(struct_table("coef_y", "Standardized canonical weights: second set", y_vars, fit["coef_y"]))
tables.append({"key": "redundancy", "title": "Variance extracted and redundancy",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"},
{"key": "extracted_x", "label": "First set: own variate", "type": "percent"},
{"key": "redundancy_x", "label": "First set: by the other variate", "type": "percent"},
{"key": "extracted_y", "label": "Second set: own variate", "type": "percent"},
{"key": "redundancy_y", "label": "Second set: by the other variate", "type": "percent"}],
"rows": [{"dimension": j + 1, "extracted_x": float(fit["extracted_x"][j]), "redundancy_x": float(fit["redundancy_x"][j]),
"extracted_y": float(fit["extracted_y"][j]), "redundancy_y": float(fit["redundancy_y"][j])} for j in range(k)]})
if cv:
tables.append({"key": "cv", "title": f"Held-out correlation of the first pair ({cv_folds}-fold)",
"columns": [{"key": "fold", "label": "Fold", "type": "integer"}, {"key": "r", "label": "Held-out r", "type": "number"}],
"rows": [{"fold": i + 1, "r": float(x)} for i, x in enumerate(cv["folds"])]})
xs, ys = ", ".join(x_vars), ", ".join(y_vars)
charts = [cs.chart("pair", "scatter", "First canonical pair", {
"x": cs.col(f"Canonical variate 1 of {xs}", u),
"y": cs.col(f"Canonical variate 1 of {ys}", v)})]
heat_rows, heat_cols, heat_vals = [], [], []
for names, M, side in ((x_vars, struct_x, "first"), (y_vars, struct_y, "second")):
for i, nm in enumerate(names):
for j in range(k):
heat_rows.append(f"{nm} ({side} set)")
heat_cols.append(f"Dimension {j + 1}")
heat_vals.append(float(M[i, j]))
charts.append(cs.chart("structure", "matrix-heatmap", "Structure correlations", {
"row": cs.col("Variable", heat_rows, "categorical"),
"col": cs.col("Dimension", heat_cols, "categorical"),
"value": cs.col("Correlation with its canonical variate", np.array(heat_vals)),
"label": cs.col("Value", [f"{x:.2f}" for x in heat_vals], "categorical")}))
label = "Kernel CCA" if method == "kernel" else ("Ridge CCA" if ridge > 0 else "Canonical correlation analysis")
sig = perm is not None and perm["p"] < alpha
summary = (f"{label} of {xs} with {ys} ({n} rows): the first canonical correlation is r = {r[0]:.3f}"
+ (f", {cs.fmt_p(perm['p'])} by {n_perm} permutations" if perm else "")
+ (f"; on held-out rows the first pair correlates r = {cv['mean']:.3f} ({cv_folds}-fold)" if cv else "") + ". "
+ ("The two sets share a linear relation." if sig and method == "linear" else "The two sets are related." if sig
else "No evidence that the sets are related." if perm else ""))
cs.publish({
"method": "multivariate.cca",
"methodVersion": "1.0.0",
"title": label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary.strip(),
"apa": f"{label}, first canonical r = {r[0]:.2f}" + (f", permutation {cs.fmt_p(perm['p'])}" if perm else ""),
"statistics": [{"key": "r1", "label": "First canonical r", "value": float(r[0])},
{"key": "p_perm", "label": "Permutation p", "value": values["p_perm"], "format": "p"},
{"key": "cv_r", "label": "Held-out r", "value": values["cv_r"]}],
"tables": tables,
"effectSizes": [{"key": "r1", "label": "First canonical correlation", "value": float(r[0]), "method": "Correlation of the first pair of canonical variates"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [("Variables standardized; " + (f"ridge {ridge:g} added to each set's correlation matrix (regularized ρ is the maximized criterion, r the correlation of the resulting variates); " if method == "linear" and ridge > 0 else "")
+ (f"kernel {kernel_type}" + (f", bandwidths {fit['sigma_x']:.3g} and {fit['sigma_y']:.3g} (median distance)" if kernel_type == "rbf" and bandwidth == 0 else "")
+ f", regularization κ = {reg:g} × (n − 1); " if method == "kernel" else "")
+ "signs make each dimension's largest first-set structure correlation positive"
+ (f"; permutation p for the first correlation from {n_perm} row permutations of the second set (seed {seed})" if perm else "")
+ (f"; held-out r = mean over {cv_folds} folds of the first pair's correlation on rows the fit did not see" if cv else "") + ".")],
"values": values,
"charts": charts,
})
On data whose two views are linked by a curve, linear CCA finds first correlation 0.23, held-out −0.04: nothing. Kernel CCA finds 0.78, held-out 0.68. Its regularized criterion, ρRegularized canonical criterion (ρ)The value ridge or kernel CCA maximizes; below the plain correlation of its variates because the penalty shrinks it. = 0.27, is lower by design: the penalty shrinks it.
Three or more views: GCCA
ReadGeneralized CCAGeneralized canonical correlation analysisCCA for three or more sets: shared row scores that every set predicts as well as possible (MAXVAR criterion). joins tables through one shared score matrix . The MAXVAR form solves
It is a family: SUMCOR and other criteria optimize different things, so name the one you use. With two tables, MAXVAR reduces to CCA: each table's correlation with the shared score is . On the savings data that is 0.955, from = 0.825.
Who drives the shared score?
ReadGeneralized CCA (MAXVAR), first eigenvalue = 2.43 of 3
- Mean set correlation (dim. 1)
- 0.8999
- Weakest set (dim. 1)
- 0.8733
Plots
View data
| Dimension | Value | Set | Correlation |
|---|---|---|---|
| Dimension 1 | 0.92 | Set 1 | 0.9203 |
| Dimension 2 | 0.88 | Set 1 | 0.8767 |
| Dimension 1 | 0.91 | Set 2 | 0.9061 |
| Dimension 2 | 0.77 | Set 2 | 0.7668 |
| Dimension 1 | 0.87 | Set 3 | 0.8733 |
| Dimension 2 | 0.89 | Set 3 | 0.8868 |
View data
| Shared dimension 1 | Shared dimension 2 |
|---|---|
| −0.8662 | 0.5033 |
| 1.037 | 0.9927 |
| 0.7787 | 0.3418 |
| 0.0710 | −0.1070 |
| −0.2455 | −1.331 |
| −0.5462 | −0.1637 |
| 1.343 | 0.0275 |
| 0.6741 | −2.689 |
| 0.3498 | −0.9516 |
| 1.362 | −0.8360 |
| −0.4604 | 0.8087 |
| −1.056 | −1.351 |
| −0.1895 | 1.828 |
| 0.7390 | 0.5620 |
| −1.785 | 0.1106 |
| 0.2522 | 1.231 |
| 0.2042 | 0.1727 |
| 2.029 | 0.5799 |
| 0.7797 | 0.5404 |
| 0.7448 | −0.3454 |
| 0.4782 | 1.817 |
| 0.0821 | −0.1918 |
| 0.2032 | −2.765 |
| 0.6022 | 1.296 |
| −1.083 | −1.339 |
| 0.8620 | −0.6666 |
| 1.654 | −0.4891 |
| 0.8789 | −0.1138 |
| 1.558 | −0.1575 |
| −0.5571 | −0.9393 |
| −0.7213 | −0.0910 |
| −1.806 | 1.276 |
| 1.232 | 0.5551 |
| −0.4271 | 0.5967 |
| 0.5641 | −0.9546 |
| −2.179 | 0.1793 |
| −1.035 | −0.2902 |
| −2.523 | −0.1192 |
| −0.2719 | 1.970 |
| 0.2229 | −0.3587 |
| 1.779 | 0.5179 |
| 0.5536 | 0.1476 |
| 0.2503 | 0.2582 |
| 0.5204 | −1.391 |
| −0.2905 | 0.4761 |
| −1.972 | −1.756 |
| −0.1687 | −0.6290 |
| −1.430 | 0.8774 |
| 1.413 | −0.0755 |
| −0.1792 | −0.8273 |
| 0.5390 | 0.1927 |
| −0.0386 | −2.187 |
| −0.7827 | 0.8405 |
| −0.1266 | −0.5320 |
| 0.5925 | 0.1294 |
| −0.6335 | 0.2093 |
| 1.818 | −0.2780 |
| −0.7667 | 0.8926 |
| −0.4076 | −1.769 |
| 0.8147 | 0.8312 |
First 60 of 90 rows.
Assumptions
- Linear relations — Each set enters through a weighted sum of its variables; curved relations between sets are missed.
- Rows per variable — 90 rows for 9 variables (10.0 per variable). Enough for stable weights.
Shared dimensions (MAXVAR eigenvalues)
| Dimension | Eigenvalue (out of 3) | Mean r² with the sets |
|---|---|---|
| 1 | 2.431 | 0.8102 |
| 2 | 2.143 | 0.7143 |
How well each set matches the shared scores (correlation)
| Set | Variables | Dimension 1 | Dimension 2 |
|---|---|---|---|
| Set 1 | a1, a2, a3 | 0.9203 | 0.8767 |
| Set 2 | b1, b2 | 0.9061 | 0.7668 |
| Set 3 | c1, c2, c3, c4 | 0.8733 | 0.8868 |
Structure correlations with the shared scores
| Variable | Set | Dimension 1 | Dimension 2 |
|---|---|---|---|
| a1 | Set 1 | 0.6952 | −0.5237 |
| a2 | Set 1 | 0.7979 | 0.0866 |
| a3 | Set 1 | 0.4949 | 0.7093 |
| b1 | Set 2 | 0.8363 | −0.3055 |
| b2 | Set 2 | 0.6700 | 0.5079 |
| c1 | Set 3 | 0.6097 | −0.5935 |
| c2 | Set 3 | 0.5053 | 0.6999 |
| c3 | Set 3 | 0.4050 | 0.0908 |
| c4 | Set 3 | −0.0839 | −0.0761 |
Leave one set out: do the shared scores hold?
| Set left out | |r| of dimension 1 | Subspace similarity |
|---|---|---|
| Set 1 | 0.9720 | 0.9201 |
| Set 2 | 0.5046 | 0.9167 |
| Set 3 | 0.9674 | 0.9074 |
- Criterion: MAXVAR (Kettenring 1971) — the shared scores maximize the sum of squared correlations with each set's best weighted sum; variables standardized; signs make each dimension's largest structure correlation positive. Subspace similarity = mean squared cosine between the shared-score subspaces with and without the set (1 = identical).
The exact R script · R R version 4.5.1 (2025-06-13)
# Generalized canonical correlation analysis (GCCA, MAXVAR)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.gcca 1.0.0 · spec c2971b0f8274c4c1
# Dataset: rep2_views (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_views.parquet", col_select = c("a1", "a2", "a3", "b1", "b2", "c1", "c2", "c3", "c4")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("a1", "a2", "a3", "b1", "b2", "c1", "c2", "c3", "c4")]), , 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("a1", "a2", "a3", "b1", "b2", "c1", "c2", "c3", "c4")) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Generalized canonical correlation analysis, MAXVAR criterion (Kettenring 1971) with a ridge: shared
# scores G that every set predicts as well as possible (G = leading eigenvectors of the sum of the sets'
# ridge projection matrices). With two sets and no ridge it is CCA (eigenvalue = 1 + canonical r).
VIEW_ROLES <- list(c("a1", "a2", "a3"), c("b1", "b2"), c("c1", "c2", "c3", "c4"))
views_vars <- Filter(length, VIEW_ROLES)
ridge <- as.numeric(0)
n_comp <- as.integer(2)
loo <- TRUE
m <- length(views_vars)
seen <- character(0)
for (vs in views_vars) {
for (v in vs) {
if (v %in% seen) cs_error("CS_E_INVALID_OPTION", option = "The sets", allowed = "separate variables (each in one set only)", value = v)
seen <- c(seen, v)
}
}
n <- nrow(df)
cs_check_rows(n, if (ridge == 0) max(lengths(views_vars)) + 2 else 5, "Generalized CCA")
for (vs in views_vars) for (v in vs) cs_check_not_constant(df[[v]], v)
views <- lapply(views_vars, function(vs) { M <- as.matrix(df[vs]); storage.mode(M) <- "double"; M })
fit <- cs_mview_gcca(views, ridge, n_comp)
k <- fit$k
lovo <- if (loo && m >= 3) cs_mview_gcca_leave_one_out(views, ridge, k) else NULL
set_names <- sprintf("Set %d", seq_len(m))
# %% Assumptions
p_total <- sum(lengths(views_vars))
ratio <- n / p_total
assumptions <- list(
list(key = "linear", label = "Linear relations", status = "info",
detail = "Each set enters through a weighted sum of its variables; curved relations between sets are missed."),
list(key = "rows_per_variable", label = "Rows per variable", status = if (ratio >= 10) "ok" else "warn",
detail = paste0(sprintf("%d rows for %d variables (%.1f per variable). ", n, p_total, ratio),
if (ratio >= 10) "Enough for stable weights." else "Below about 10 rows per variable the weights are unstable; a ridge helps."))
)
# %% Result
values <- list(n = n, m = m, k = k, ridge = ridge, mean_view_r1 = mean(fit$view_r[, 1]), min_view_r1 = min(fit$view_r[, 1]))
for (j in seq_len(k)) values[[sprintf("eigen[%d]", j)]] <- fit$eigen[j]
for (i in seq_len(m)) {
values[[sprintf("view_r1[%d]", i)]] <- fit$view_r[i, 1]
if (!is.null(lovo)) values[[sprintf("loo_r1[%d]", i)]] <- lovo[[i]]$r1
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
dimcols <- lapply(seq_len(k), function(j) list(key = sprintf("d%d", j), label = sprintf("Dimension %d", j), type = "number"))
tables <- list(
list(key = "eigen", title = "Shared dimensions (MAXVAR eigenvalues)",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"),
list(key = "eigen", label = sprintf("Eigenvalue (out of %d)", m), type = "number"),
list(key = "mean_r2", label = "Mean r² with the sets", type = "number")),
rows = lapply(seq_len(k), function(j) list(dimension = j, eigen = fit$eigen[j], mean_r2 = mean(fit$view_r[, j]^2)))),
list(key = "views", title = "How well each set matches the shared scores (correlation)",
columns = c(list(list(key = "set", label = "Set", type = "string"), list(key = "variables", label = "Variables", type = "string")), dimcols),
rows = lapply(seq_len(m), function(i) {
row <- list(set = set_names[i], variables = paste(views_vars[[i]], collapse = ", "))
for (j in seq_len(k)) row[[sprintf("d%d", j)]] <- fit$view_r[i, j]
row
})),
list(key = "structure", title = "Structure correlations with the shared scores",
columns = c(list(list(key = "variable", label = "Variable", type = "string"), list(key = "set", label = "Set", type = "string")), dimcols),
rows = unlist(lapply(seq_len(m), function(i) lapply(seq_along(views_vars[[i]]), function(c) {
row <- list(variable = views_vars[[i]][c], set = set_names[i])
for (j in seq_len(k)) row[[sprintf("d%d", j)]] <- fit$struct[[i]][c, j]
row
})), recursive = FALSE))
)
if (!is.null(lovo)) {
tables[[length(tables) + 1]] <- list(key = "leave_one_out", title = "Leave one set out: do the shared scores hold?",
columns = list(list(key = "set", label = "Set left out", type = "string"), list(key = "r1", label = "|r| of dimension 1", type = "number"),
list(key = "subspace", label = "Subspace similarity", type = "number")),
rows = lapply(lovo, function(d) list(set = set_names[d$view + 1L], r1 = d$r1, subspace = d$subspace)))
}
hr <- character(0); hc <- character(0); hv <- numeric(0)
for (i in seq_len(m)) for (j in seq_len(k)) { hr <- c(hr, set_names[i]); hc <- c(hc, sprintf("Dimension %d", j)); hv <- c(hv, fit$view_r[i, j]) }
charts <- list(cs_chart("views", "matrix-heatmap", "Each set's correlation with the shared scores", list(
row = cs_col("Set", hr, "categorical"), col = cs_col("Dimension", hc, "categorical"),
value = cs_col("Correlation", hv), label = cs_col("Value", sprintf("%.2f", hv), "categorical"))))
if (k >= 2) {
charts[[2]] <- cs_chart("scores", "scatter", "Shared scores", list(
x = cs_col("Shared dimension 1", fit$scores[, 1]), y = cs_col("Shared dimension 2", fit$scores[, 2])))
}
weakest <- which.min(fit$view_r[, 1])
summary <- paste0(sprintf("Generalized CCA (MAXVAR%s) of %d sets on %d rows: the first shared dimension has eigenvalue %.3f of %d, and the sets correlate with it between r = %.2f and %.2f (%s least).",
if (ridge > 0) paste0(", ridge ", format(ridge)) else "", m, n, fit$eigen[1], m, min(fit$view_r[, 1]), max(fit$view_r[, 1]), set_names[weakest]),
if (!is.null(lovo)) sprintf(" Leaving one set out, dimension 1 keeps |r| ≥ %.2f.", min(vapply(lovo, function(d) d$r1, 0))) else "")
cs_publish(list(
method = "multivariate.gcca",
methodVersion = "1.0.0",
title = "Generalized canonical correlation analysis",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("Generalized CCA (MAXVAR), first eigenvalue = %.2f of %d", fit$eigen[1], m),
statistics = list(list(key = "mean_view_r1", label = "Mean set correlation (dim. 1)", value = values$mean_view_r1),
list(key = "min_view_r1", label = "Weakest set (dim. 1)", value = values$min_view_r1)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0("Criterion: MAXVAR (Kettenring 1971) — the shared scores maximize the sum of squared correlations with each set's best weighted sum; ",
if (ridge > 0) sprintf("ridge %s added to each set's correlation matrix; ", format(ridge)) else "",
"variables standardized; signs make each dimension's largest structure correlation positive.",
if (!is.null(lovo)) " Subspace similarity = mean squared cosine between the shared-score subspaces with and without the set (1 = identical)." else "")),
values = values,
charts = charts
))
Generalized CCA (MAXVAR), first eigenvalue = 2.43 of 3
- Mean set correlation (dim. 1)
- 0.8999
- Weakest set (dim. 1)
- 0.8733
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Linear relations — Each set enters through a weighted sum of its variables; curved relations between sets are missed.
- Rows per variable — 90 rows for 9 variables (10.0 per variable). Enough for stable weights.
Shared dimensions (MAXVAR eigenvalues)
| Dimension | Eigenvalue (out of 3) | Mean r² with the sets |
|---|---|---|
| 1 | 2.431 | 0.8102 |
| 2 | 2.143 | 0.7143 |
How well each set matches the shared scores (correlation)
| Set | Variables | Dimension 1 | Dimension 2 |
|---|---|---|---|
| Set 1 | a1, a2, a3 | 0.9203 | 0.8767 |
| Set 2 | b1, b2 | 0.9061 | 0.7668 |
| Set 3 | c1, c2, c3, c4 | 0.8733 | 0.8868 |
Structure correlations with the shared scores
| Variable | Set | Dimension 1 | Dimension 2 |
|---|---|---|---|
| a1 | Set 1 | 0.6952 | −0.5237 |
| a2 | Set 1 | 0.7979 | 0.0866 |
| a3 | Set 1 | 0.4949 | 0.7093 |
| b1 | Set 2 | 0.8363 | −0.3055 |
| b2 | Set 2 | 0.6700 | 0.5079 |
| c1 | Set 3 | 0.6097 | −0.5935 |
| c2 | Set 3 | 0.5053 | 0.6999 |
| c3 | Set 3 | 0.4050 | 0.0908 |
| c4 | Set 3 | −0.0839 | −0.0761 |
Leave one set out: do the shared scores hold?
| Set left out | |r| of dimension 1 | Subspace similarity |
|---|---|---|
| Set 1 | 0.9720 | 0.9201 |
| Set 2 | 0.5046 | 0.9167 |
| Set 3 | 0.9674 | 0.9074 |
- Criterion: MAXVAR (Kettenring 1971) — the shared scores maximize the sum of squared correlations with each set's best weighted sum; variables standardized; signs make each dimension's largest structure correlation positive. Subspace similarity = mean squared cosine between the shared-score subspaces with and without the set (1 = identical).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Generalized canonical correlation analysis (GCCA, MAXVAR)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.gcca 1.0.0 · spec c2971b0f8274c4c1
# Dataset: rep2_views (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash.stats import multiview as mvw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/rep2_views.parquet", columns=["a1", "a2", "a3", "b1", "b2", "c1", "c2", "c3", "c4"])
n_input = len(df)
df = df.dropna(subset=["a1", "a2", "a3", "b1", "b2", "c1", "c2", "c3", "c4"]) # listwise deletion over the analysis columns
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, ["a1", "a2", "a3", "b1", "b2", "c1", "c2", "c3", "c4"]) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Generalized canonical correlation analysis, MAXVAR criterion (Kettenring 1971) with a ridge: shared
# scores G that every set predicts as well as possible (G = leading eigenvectors of the sum of the sets'
# ridge projection matrices). With two sets and no ridge it is CCA (eigenvalue = 1 + canonical r).
VIEW_ROLES = [["a1", "a2", "a3"], ["b1", "b2"], ["c1", "c2", "c3", "c4"]]
views_vars = [v for v in VIEW_ROLES if v]
ridge = float(0)
n_comp = int(2)
loo = True
m = len(views_vars)
seen = {}
for i, vs in enumerate(views_vars):
for v in vs:
if v in seen:
cs.cs_error("CS_E_INVALID_OPTION", option="The sets", allowed="separate variables (each in one set only)", value=v)
seen[v] = i
n = len(df)
cs.check_rows(n, max(len(vs) for vs in views_vars) + 2 if ridge == 0 else 5, "Generalized CCA")
for vs in views_vars:
for v in vs:
check_not_constant(df[v], v)
views = [df[vs].to_numpy(dtype=float) for vs in views_vars]
fit = mvw.gcca(views, ridge, n_comp)
k = fit["k"]
lovo = mvw.gcca_leave_one_out(views, ridge, k) if loo and m >= 3 else None
set_names = [f"Set {i + 1}" for i in range(m)]
# %% Assumptions
p_total = sum(len(vs) for vs in views_vars)
ratio = n / p_total
assumptions = [
{"key": "linear", "label": "Linear relations", "status": "info",
"detail": "Each set enters through a weighted sum of its variables; curved relations between sets are missed."},
{"key": "rows_per_variable", "label": "Rows per variable", "status": "ok" if ratio >= 10 else "warn",
"detail": f"{n} rows for {p_total} variables ({ratio:.1f} per variable). " + ("Enough for stable weights." if ratio >= 10
else "Below about 10 rows per variable the weights are unstable; a ridge helps.")},
]
# %% Result
values = {"n": n, "m": m, "k": k, "ridge": ridge,
"mean_view_r1": float(np.mean(fit["view_r"][:, 0])), "min_view_r1": float(np.min(fit["view_r"][:, 0]))}
for j in range(k):
values[f"eigen[{j + 1}]"] = float(fit["eigen"][j])
for i in range(m):
values[f"view_r1[{i + 1}]"] = float(fit["view_r"][i, 0])
if lovo:
values[f"loo_r1[{i + 1}]"] = lovo[i]["r1"]
values["missing_share"] = n_dropped / n_input if n_input else 0.0
tables = [{"key": "eigen", "title": "Shared dimensions (MAXVAR eigenvalues)",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"},
{"key": "eigen", "label": f"Eigenvalue (out of {m})", "type": "number"},
{"key": "mean_r2", "label": "Mean r² with the sets", "type": "number"}],
"rows": [{"dimension": j + 1, "eigen": float(fit["eigen"][j]), "mean_r2": float(np.mean(fit["view_r"][:, j] ** 2))} for j in range(k)]},
{"key": "views", "title": "How well each set matches the shared scores (correlation)",
"columns": [{"key": "set", "label": "Set", "type": "string"}, {"key": "variables", "label": "Variables", "type": "string"}]
+ [{"key": f"d{j + 1}", "label": f"Dimension {j + 1}", "type": "number"} for j in range(k)],
"rows": [{"set": set_names[i], "variables": ", ".join(views_vars[i]), **{f"d{j + 1}": float(fit["view_r"][i, j]) for j in range(k)}} for i in range(m)]},
{"key": "structure", "title": "Structure correlations with the shared scores",
"columns": [{"key": "variable", "label": "Variable", "type": "string"}, {"key": "set", "label": "Set", "type": "string"}]
+ [{"key": f"d{j + 1}", "label": f"Dimension {j + 1}", "type": "number"} for j in range(k)],
"rows": [{"variable": v, "set": set_names[i], **{f"d{j + 1}": float(fit["struct"][i][c, j]) for j in range(k)}}
for i, vs in enumerate(views_vars) for c, v in enumerate(vs)]}]
if lovo:
tables.append({"key": "leave_one_out", "title": "Leave one set out: do the shared scores hold?",
"columns": [{"key": "set", "label": "Set left out", "type": "string"},
{"key": "r1", "label": "|r| of dimension 1", "type": "number"},
{"key": "subspace", "label": "Subspace similarity", "type": "number"}],
"rows": [{"set": set_names[d["view"]], "r1": d["r1"], "subspace": d["subspace"]} for d in lovo]})
hr, hc, hv = [], [], []
for i in range(m):
for j in range(k):
hr.append(set_names[i]); hc.append(f"Dimension {j + 1}"); hv.append(float(fit["view_r"][i, j]))
charts = [cs.chart("views", "matrix-heatmap", "Each set's correlation with the shared scores", {
"row": cs.col("Set", hr, "categorical"), "col": cs.col("Dimension", hc, "categorical"),
"value": cs.col("Correlation", np.array(hv)), "label": cs.col("Value", [f"{x:.2f}" for x in hv], "categorical")})]
if k >= 2:
charts.append(cs.chart("scores", "scatter", "Shared scores", {
"x": cs.col("Shared dimension 1", fit["scores"][:, 0]), "y": cs.col("Shared dimension 2", fit["scores"][:, 1])}))
weakest = int(np.argmin(fit["view_r"][:, 0]))
summary = (f"Generalized CCA (MAXVAR{', ridge ' + format(ridge, 'g') if ridge > 0 else ''}) of {m} sets on {n} rows: the first shared dimension "
f"has eigenvalue {fit['eigen'][0]:.3f} of {m}, and the sets correlate with it between r = {fit['view_r'][:, 0].min():.2f} and "
f"{fit['view_r'][:, 0].max():.2f} ({set_names[weakest]} least)."
+ (f" Leaving one set out, dimension 1 keeps |r| ≥ {min(d['r1'] for d in lovo):.2f}." if lovo else ""))
cs.publish({
"method": "multivariate.gcca",
"methodVersion": "1.0.0",
"title": "Generalized canonical correlation analysis",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"Generalized CCA (MAXVAR), first eigenvalue = {fit['eigen'][0]:.2f} of {m}",
"statistics": [{"key": "mean_view_r1", "label": "Mean set correlation (dim. 1)", "value": values["mean_view_r1"]},
{"key": "min_view_r1", "label": "Weakest set (dim. 1)", "value": values["min_view_r1"]}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Criterion: MAXVAR (Kettenring 1971) — the shared scores maximize the sum of squared correlations with each set's best weighted sum; "
+ (f"ridge {ridge:g} added to each set's correlation matrix; " if ridge > 0 else "")
+ "variables standardized; signs make each dimension's largest structure correlation positive."
+ (" Subspace similarity = mean squared cosine between the shared-score subspaces with and without the set (1 = identical)." if lovo else "")],
"values": values,
"charts": charts,
})
Each of the three tables correlates strongly with the first shared score (0.92, 0.91, 0.87). The leave-one-set-out checkLeave-one-set-out checkRefits GCCA without each set and correlates the new first shared score with the old one; low values mean one set drives it. tells a different story: refit without table 2 and the new score correlates only 0.50 with the old one. Table 2 drives that dimension.
Large or noisy tables can dominate unless weighted, and an agreed dimension can be a shared batch effect.
Check: CCA family
CheckpointCheck yourself
With 40 rows, 20 columns in and 18 in , CCA reports a first canonical correlation of 0.99. What should you do?
Show the answer
Answer: a
CCA chooses weights to maximize sample correlation. With few rows per column, it can match the two tables on noise alone.
Check yourself
How does a permutation test for CCA build its null distribution?
Show the answer
Answer: a
Shuffling one table's rows keeps each table's own structure but destroys the pairing, which is exactly the null of no cross-table relationship. Repeated rows from one person need a matching shuffle scheme.
Check yourself
Why must kernel CCA be regularized?
Show the answer
Answer: a
A flexible enough function of each table can be made to match the other on the sample. The penalty restricts flexibility; held-out rows check it.
Check yourself
Linear CCA finds nothing between two views, but kernel CCA finds a strong held-out correlation. What is the most likely reading?
Show the answer
Answer: a
Held-out correlation guards against overfitting. A curved link, such as one view depending on the square of the other, is invisible to linear CCA.
Check yourself
With two tables, MAXVAR GCCA gives each table a correlation of with the shared score. If the canonical correlation is , what is that correlation?
Show the answer
Answer: 0.9
.
Check yourself
Leaving out table 3 barely changes the first shared score; leaving out table 1 changes it a lot. What does that tell you?
Show the answer
Answer: a
A score that survives without a table didn't depend on it. A low leave-one-out correlation flags the table that defines the dimension.
Recap
Recap- CCA finds weighted sums of two tables with maximal correlation; check held-out correlation and permutations, because overfitting is easy.
- Kernel CCA finds correlated nonlinear functions and needs regularization.
- GCCA joins three or more tables through one shared score; it is a family of criteria, and leave-one-out shows which table drives it.
Concepts in this lesson