Skip to content

Relating two or more sets of variables: CCA and generalized CCA

Canonical correlation analysis finds the weighted sums of two sets that move together most. Learn to read structure correlations, check the relation on held-out rows, reach for kernel CCA when it bends, and extend to three or more sets.

Advanced ~15 min7 steps

What runs in CodeSplash

You will be able to

  • Explain what a canonical pair and a canonical correlation are
  • Read structure correlations instead of raw weights
  • Judge a relation by its held-out correlation and permutation p
  • Choose ridge or kernel CCA, and generalized CCA for three or more sets

Read first

01

Two sets, one question

Read

A correlation relates two variables. Often you have two sets: savings and income growth on one side, a country's age structure on the other; test scores on one side, study habits on the other.

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. looks for a weighted sum of each set so the two sums correlate as much as possible. That pair of sums is the first canonical pair; its correlation is the first canonical correlation. The next pair does the same, uncorrelated with the first, and so on, up to the size of the smaller set.

02

Run it

In the app
Canonical correlation analysisRecorded · Python and R agreeRecorded 2026-11-21 · 27 values compared
R

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

Plots

First canonical pairHow do two numeric variables move together?
View data
Canonical variate 1 of pop15, pop75Canonical variate 1 of sr, dpi, ddpi
−0.5625−1.198
−1.472−0.5145
−1.448−1.126
0.64591.176
0.95100.1325
−0.4046−1.626
0.62110.9759
1.1690.5354
1.1571.058
1.1930.5438
−1.238−1.704
1.0911.156
−0.4886−0.6352
−1.459−1.211
−1.111−1.397
−0.87870.0830
1.1841.209
1.3630.9336
−0.3356−0.1509
0.85061.036
−0.8966−0.1069
−1.078−0.5262
−0.3849−0.9454
0.89511.100
−1.337−1.205
−0.2229−0.0090
−1.052−1.059
−0.9879−0.9893
−0.4568−0.3494
1.0030.8928
0.91240.8070
0.81171.344
0.92530.5573
1.1120.7407
−0.58060.2067
−0.19640.3757
0.06110.6193
−0.66520.1675
−1.636−1.818
−1.229−1.628
0.94430.9488
1.0721.268
−1.492−0.4858
−0.7239−2.486
1.1960.3895
1.2380.3188
0.57630.5914
−0.58930.3917
0.62440.5680
1.3281.046
Structure correlationsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
DimensionValueVariableCorrelation with its canonical variate
Dimension 10.98pop15 (first set)0.9830
Dimension 20.18pop15 (first set)0.1837
Dimension 1-0.97pop75 (first set)−0.9698
Dimension 20.24pop75 (first set)0.2439
Dimension 1-0.49sr (second set)−0.4910
Dimension 2-0.86sr (second set)−0.8558
Dimension 1-0.95dpi (second set)−0.9545
Dimension 20.26dpi (second set)0.2637
Dimension 1-0.05ddpi (second set)−0.0473
Dimension 2-0.14ddpi (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

DimensionCanonical rr²Wilks Λχ²dfp (dimensions i…k)
10.82480.68030.277159.0436< .001
20.36530.13340.86666.5882.037

Structure correlations: first set with its canonical variates

VariableDimension 1Dimension 2
pop150.98300.1837
pop75−0.96980.2439

Structure correlations: second set with its canonical variates

VariableDimension 1Dimension 2
sr−0.4910−0.8558
dpi−0.95450.2637
ddpi−0.0473−0.1408

Standardized canonical weights: first set

VariableDimension 1Dimension 2
pop150.58372.320
pop75−0.43952.352

Standardized canonical weights: second set

VariableDimension 1Dimension 2
sr−0.2657−1.047
dpi−0.90680.5263
ddpi−0.08380.2465

Variance extracted and redundancy

DimensionFirst set: own variateFirst set: by the other variateSecond set: own variateSecond set: by the other variate
195.3%64.9%38.5%26.2%
24.7%0.6%27.4%3.7%

Held-out correlation of the first pair (5-fold)

FoldHeld-out r
10.7283
20.8361
30.9057
40.9140
50.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
))
Python

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

DimensionCanonical rr²Wilks Λχ²dfp (dimensions i…k)
10.82480.68030.277159.0436< .001
20.36530.13340.86666.5882.037

Structure correlations: first set with its canonical variates

VariableDimension 1Dimension 2
pop150.98300.1837
pop75−0.96980.2439

Structure correlations: second set with its canonical variates

VariableDimension 1Dimension 2
sr−0.4910−0.8558
dpi−0.95450.2637
ddpi−0.0473−0.1408

Standardized canonical weights: first set

VariableDimension 1Dimension 2
pop150.58372.320
pop75−0.43952.352

Standardized canonical weights: second set

VariableDimension 1Dimension 2
sr−0.2657−1.047
dpi−0.90680.5263
ddpi−0.08380.2465

Variance extracted and redundancy

DimensionFirst set: own variateFirst set: by the other variateSecond set: own variateSecond set: by the other variate
195.3%64.9%38.5%26.2%
24.7%0.6%27.4%3.7%

Held-out correlation of the first pair (5-fold)

FoldHeld-out r
10.7283
20.8361
30.9057
40.9140
50.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,
})

Fifty countries: the share of the population under 15 and over 75 against the savings ratio and income growth. The first canonical correlation is 0.825, with a permutation p of p = .005. On rows the fit did not see, the first pair still correlates 0.813.

03

Read structure, not weights

Read

Each side's canonical weights say how to build its sum. With correlated variables they swing in sign and size, so don't read them as importance.

Read the structure correlationsStructure correlationThe correlation of one variable with a canonical variate or shared score; shows which variables carry that dimension. instead: the correlation of each variable with its side's canonical variate. The heatmap shows them. The variables with the largest absolute values name the dimension.

Matrix heatmapWhat do the values of a square or rectangular result matrix look like at a glance?
View data
variablewithr
ageage1
ageBMI0.1207
agesystolic BP0.1471
agecholesterol0.1467
ageglucose0.1912
ageactivity−0.1247
BMIage0.1207
BMIBMI1
BMIsystolic BP0.3132
BMIcholesterol0.3194
BMIglucose0.3629
BMIactivity−0.1770
systolic BPage0.1471
systolic BPBMI0.3132
systolic BPsystolic BP1
systolic BPcholesterol0.4537
systolic BPglucose0.5647
systolic BPactivity−0.3672
cholesterolage0.1467
cholesterolBMI0.3194
cholesterolsystolic BP0.4537
cholesterolcholesterol1
cholesterolglucose0.6006
cholesterolactivity−0.3861
glucoseage0.1912
glucoseBMI0.3629
glucosesystolic BP0.5647
glucosecholesterol0.6006
glucoseglucose1
glucoseactivity−0.4105
activityage−0.1247
activityBMI−0.1770
activitysystolic BP−0.3672
activitycholesterol−0.3861
activityglucose−0.4105
activityactivity1

The redundancy index adds a caution: here the age-structure variates explain 29.8% of the variance in savings and income growth. A high canonical r can rest on a thin slice of a set.

04

Make a guess

Predict

Predict first

In a simulated set, y1 is a cosine of x1 and y2 is x2 squared, each plus noise, with every x spread evenly around 0. Which method finds a strong relation on held-out rows?

Linear CCA finds itOnly kernel CCA finds itNeither finds it
Reveal

Only kernel CCA. Linear CCA's held-out r is −0.0357: a cosine and a parabola centered on 0 have no linear trend. Kernel CCA's is 0.680, because each variate can bend.

05

When the relation bends

Read

Kernel CCAKernel CCACCA on kernel similarities so each variate can be a smooth nonlinear function of its set; needs regularization. replaces each set by similarities between rows (a Gaussian kernel), so each variate can be a smooth nonlinear function. It needs regularization: without it every kernel correlation reaches 1, even for unrelated sets.

That is why the held-out correlation is the number to report for kernel CCA. Its in-sample correlation, 0.784 here, flatters it.

A ridge helps linear CCA in a similar way when a set has many or collinear variables: it steadies the weights at the cost of a slightly smaller criterion.

06

Three or more sets

Read

Generalized CCAGeneralized canonical correlation analysisCCA for three or more sets: shared row scores that every set predicts as well as possible (MAXVAR criterion). finds shared scores for the rows that every set predicts as well as possible (the MAXVAR criterion). Each shared dimension has an eigenvalue between 0 and the number of sets.

Generalized canonical correlation analysisRecorded · Python and R agreeRecorded 2026-11-21 · 15 values compared
R

Generalized CCA (MAXVAR), first eigenvalue = 2.43 of 3

Mean set correlation (dim. 1)
0.8999
Weakest set (dim. 1)
0.8733

Plots

Each set's correlation with the shared scoresWhat do the values of a square or rectangular result matrix look like at a glance?
View data
DimensionValueSetCorrelation
Dimension 10.92Set 10.9203
Dimension 20.88Set 10.8767
Dimension 10.91Set 20.9061
Dimension 20.77Set 20.7668
Dimension 10.87Set 30.8733
Dimension 20.89Set 30.8868
Shared scoresHow do two numeric variables move together?
View data
Shared dimension 1Shared dimension 2
−0.86620.5033
1.0370.9927
0.77870.3418
0.0710−0.1070
−0.2455−1.331
−0.5462−0.1637
1.3430.0275
0.6741−2.689
0.3498−0.9516
1.362−0.8360
−0.46040.8087
−1.056−1.351
−0.18951.828
0.73900.5620
−1.7850.1106
0.25221.231
0.20420.1727
2.0290.5799
0.77970.5404
0.7448−0.3454
0.47821.817
0.0821−0.1918
0.2032−2.765
0.60221.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.8061.276
1.2320.5551
−0.42710.5967
0.5641−0.9546
−2.1790.1793
−1.035−0.2902
−2.523−0.1192
−0.27191.970
0.2229−0.3587
1.7790.5179
0.55360.1476
0.25030.2582
0.5204−1.391
−0.29050.4761
−1.972−1.756
−0.1687−0.6290
−1.4300.8774
1.413−0.0755
−0.1792−0.8273
0.53900.1927
−0.0386−2.187
−0.78270.8405
−0.1266−0.5320
0.59250.1294
−0.63350.2093
1.818−0.2780
−0.76670.8926
−0.4076−1.769
0.81470.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)

DimensionEigenvalue (out of 3)Mean r² with the sets
12.4310.8102
22.1430.7143

How well each set matches the shared scores (correlation)

SetVariablesDimension 1Dimension 2
Set 1a1, a2, a30.92030.8767
Set 2b1, b20.90610.7668
Set 3c1, c2, c3, c40.87330.8868

Structure correlations with the shared scores

VariableSetDimension 1Dimension 2
a1Set 10.6952−0.5237
a2Set 10.79790.0866
a3Set 10.49490.7093
b1Set 20.8363−0.3055
b2Set 20.67000.5079
c1Set 30.6097−0.5935
c2Set 30.50530.6999
c3Set 30.40500.0908
c4Set 3−0.0839−0.0761

Leave one set out: do the shared scores hold?

Set left out|r| of dimension 1Subspace similarity
Set 10.97200.9201
Set 20.50460.9167
Set 30.96740.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
))
Python

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)

DimensionEigenvalue (out of 3)Mean r² with the sets
12.4310.8102
22.1430.7143

How well each set matches the shared scores (correlation)

SetVariablesDimension 1Dimension 2
Set 1a1, a2, a30.92030.8767
Set 2b1, b20.90610.7668
Set 3c1, c2, c3, c40.87330.8868

Structure correlations with the shared scores

VariableSetDimension 1Dimension 2
a1Set 10.6952−0.5237
a2Set 10.79790.0866
a3Set 10.49490.7093
b1Set 20.8363−0.3055
b2Set 20.67000.5079
c1Set 30.6097−0.5935
c2Set 30.50530.6999
c3Set 30.40500.0908
c4Set 3−0.0839−0.0761

Leave one set out: do the shared scores hold?

Set left out|r| of dimension 1Subspace similarity
Set 10.97200.9201
Set 20.50460.9167
Set 30.96740.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,
})

With three simulated sets built from two shared factors, the first eigenvalue is 2.43 of 3, and every set correlates at least 0.873 with the first shared score. The leave-one-set-out table shows whether one set alone drives a dimension.

With two sets, generalized CCA is CCA: its first eigenvalue on the savings data is 1.82, one plus the canonical correlation.

07

Check your understanding

Checkpoint

Check yourself

Two predictors in one set are highly correlated, and one has a negative canonical weight. What should you look at to say how that variable relates to the canonical dimension?

Show the answer

Answer: b

Weights share out the work among correlated variables and can flip sign. The structure correlation is the variable's own correlation with the variate.

Check yourself

A kernel CCA reports an in-sample canonical correlation of 0.97 and a held-out correlation of 0.12. What's the honest summary?

Show the answer

Answer: b

With flexible kernels the in-sample correlation can be close to 1 for unrelated sets. The held-out correlation measures what generalizes.

Check yourself

Generalized CCA of four sets gives a first eigenvalue of 3.6. What does that tell you?

Show the answer

Answer: a

Each set adds up to 1 to a MAXVAR eigenvalue, so 3.6 of 4 means the sets agree closely on the first shared score. Check which set falls short in the set correlations.

Check yourself

Why does ridge CCA report a regularized ρ that is smaller than the correlation of its variates?

Show the answer

Answer: b

Ridge CCA maximizes a penalized criterion. The penalty lowers ρ, while the variates it produces are correlated as usual.

Check yourself

In generalized CCA of three sets, leaving out set 2 drops the |r| of the first shared dimension to 0.3, while leaving out sets 1 or 3 keeps it above 0.95. What does that say?

Show the answer

Answer: b

The leave-one-set-out check shows whether a shared dimension is common to all sets or carried by one of them.