Skip to content

Biclusters: rows that agree on some columns

When no grouping of rows fits every column, look for blocks instead. Cheng–Church finds coherent blocks one at a time; spectral co-clustering and the checkerboard split rows and columns together.

Applied ~12 min6 steps

What runs in CodeSplash

You will be able to

  • Explain what a bicluster is and when whole-row clustering misses it
  • Read the mean squared residue and the residue threshold δ
  • Choose between Cheng–Church, spectral co-clustering and the checkerboard

Read first

01

When rows only agree on some columns

Read

k-means puts every row in one group using every column. Real tables are often messier: a set of genes rises and falls together under some conditions and does its own thing under the rest, or a set of customers buys alike in a few categories only. A biclusterBiclusterA set of rows that behave alike on a set of columns — a block of the table — while differing on the other columns. is that block: some rows, some columns, behaving alike inside the block.

The data below has two blocks hidden in noise. Inside each, every value is a row effect plus a column effect, so the rows move in parallel over those columns. Outside the blocks the same rows are plain noise, so no clustering of whole rows can find them.

02

Coherence: the mean squared residue

Read

Cheng–Church measures how well a block fits "each row and each column shifts by its own amount." The misfit of a cell is its value minus its row mean, minus its column mean, plus the block mean. The mean squared residueMean squared residueAverage squared misfit of a block to rows and columns that each shift by their own amount; 0 = a perfectly additive block. averages the squared misfits: 0 means a perfectly additive block.

03

Shrink, then grow

Read

The search starts from the whole table and drops the row or column that fits worst until the residue falls below a threshold δResidue threshold (δ)Cheng–Church keeps shrinking a block until its mean squared residue is at most δ; here δ = a share of the whole table's residue., then adds back any row or column that fits. The found cells are masked with random values and the search runs again for the next block. Smaller δ gives tighter, smaller blocks.

Biclustering (rows × columns)Recorded · Python and R agreeRecorded 2026-11-21 · 21 values compared
R

3 biclusters in 60 rows × 12 columns covering 37% of the rows; mean squared residue 0.00923.

Biclusters
3
Rows covered
36.7%
Mean squared residue
0.0092

Plots

Biclusters in the tableWhich subsets of rows share a pattern on a subset of columns?
View data
BiclusterColumnRowValue (standardized)
-1x1r011.166
-1x2r01−0.1202
-1x3r010.2679
-1x4r010.6042
-1x5r01−0.9826
-1x6r010.0277
-1x7r010.4645
-1x8r01−0.0677
-1x9r012.850
-1x10r010.2368
-1x11r01−0.4948
-1x12r01−0.1775
-1x1r020.0436
-1x2r02−1.401
-1x3r02−0.6471
-1x4r02−0.3771
-1x5r020.8307
-1x6r02−0.0856
-1x7r020.6873
-1x8r021.283
-1x9r020.9333
-1x10r02−1.728
-1x11r02−0.5257
-1x12r02−1.081
2x1r030.8580
2x2r03−0.5201
2x3r030.0291
2x4r030.3487
2x5r030.0055
-1x6r03−0.5167
-1x7r03−1.908
-1x8r03−0.4464
-1x9r031.701
-1x10r030.1065
-1x11r03−0.3729
-1x12r031.107
2x1r041.781
2x2r040.4723
2x3r040.8519
2x4r041.131
2x5r041.343
-1x6r041.051
-1x7r040.7797
-1x8r04−0.9918
-1x9r040.0180
-1x10r041.769
-1x11r04−0.1224
-1x12r040.1363
-1x1r051.355
-1x2r05−0.0224
-1x3r050.4606
-1x4r050.7913
-1x5r051.000
-1x6r05−1.513
-1x7r05−1.417
-1x8r05−1.134
-1x9r050.6560
-1x10r052.149
-1x11r050.8723
-1x12r05−0.1323

First 60 of 720 rows.

Biclusters

BiclusterRowsColumnsWhich columnsMean squared residueMean value
1104x7, x8, x9, x100.0027−0.3418
285x1, x2, x3, x4, x50.01120.0863
344x4, x6, x9, x110.01380.1289
The exact R script · R R version 4.5.1 (2025-06-13)
# Biclustering (rows × columns)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bicluster 1.0.0 · spec 31b304c79ce1b41c
# Dataset: clu4_bicluster (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12")
ROW_ID <- "id"  # row labels for the heatmap
SEED <- 42
ALGORITHM <- "cheng_church"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_bicluster.parquet", col_select = unique(c(FEATURES, ROW_ID))))
n_input <- nrow(df)
cs_check_finite_columns(df, FEATURES)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, FEATURES)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 4, "Biclustering")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
dimnames(X) <- NULL
n <- nrow(X)
p <- ncol(X)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
out <- cs_ml_out_dir("target/academy-parity/run-85263/discover.bicluster/planted_cheng_church/out-r")
rng <- cs_rng(SEED)
delta <- NULL
iterations <- NULL

need_nonnegative <- function(strict) {
  bad <- if (strict) X <= 0 else X < 0
  for (j in seq_along(FEATURES)) {
    if (any(bad[, j])) cs_error("CS_E_INVALID_VALUES", column = FEATURES[j], requirement = if (strict) "positive" else "zero or more", count = sum(bad[, j]))
  }
  if (any(rowSums(X) <= 0)) cs_error("CS_E_INVALID_VALUES", column = "Row totals", requirement = "positive", count = sum(rowSums(X) <= 0))
  if (any(colSums(X) <= 0)) cs_error("CS_E_INVALID_VALUES", column = "Column totals", requirement = "positive", count = sum(colSums(X) <= 0))
}

# %% Biclusters
if (ALGORITHM == "cheng_church") {
  A <- X
  if ("standard" == "standard") {
    flat <- apply(A, 2, function(v) max(v) - min(v)) == 0
    sd0 <- apply(A, 2, function(v) sqrt(mean((v - mean(v))^2)))
    sd0[flat] <- 1
    A <- sweep(sweep(A, 2, colMeans(A)), 2, sd0, "/")
    A[, flat] <- 0  # constant columns exactly 0 in both engines
  }
  h_full <- cs_ml_bicluster_msr(A, rep(TRUE, n), rep(TRUE, p))
  if (h_full <= 0) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
  delta <- as.numeric(0.02) * h_full
  found <- cs_ml_bicluster_cheng_church(A, 3, delta, as.numeric(1.2), rng)
  biclusters <- found
  if (!length(biclusters)) warnings <- c(warnings, "No block came below the residue threshold with at least two rows and two columns; raise the threshold.")
} else if (ALGORITHM == "cocluster") {
  need_nonnegative(FALSE)
  K <- 3
  n_sv <- if (K > 1) 1 + ceiling(log2(K)) else 1
  if (K < 2 || n_sv > min(n, p) || K > n) {
    cs_error("CS_E_INVALID_OPTION", option = "Biclusters", allowed = sprintf("between 2 and %d for this table", as.integer(min(n, 2^(min(n, p) - 1)))), value = K)
  }
  A <- X
  co <- cs_ml_bicluster_cocluster(A, K, rng, 10)
  biclusters <- lapply(seq_len(K) - 1L, function(b) list(I = co$rows == b, J = co$cols == b))
} else {
  METHOD <- "bistochastic"
  need_nonnegative(METHOD == "log")
  NR <- 3
  NC <- 3
  NCOMP <- 6
  NBEST <- 3
  if (NCOMP > min(n, p)) cs_error("CS_E_INVALID_OPTION", option = "Singular vectors", allowed = sprintf("at most %d for this table", min(n, p)), value = NCOMP)
  usable <- NCOMP - (if (METHOD == "log") 0 else 1)
  if (NBEST > usable) cs_error("CS_E_INVALID_OPTION", option = "Vectors kept", allowed = sprintf("at most %d with %d singular vectors", usable, NCOMP), value = NBEST)
  if (NR > n || NC > p) {
    cs_error("CS_E_INVALID_OPTION", option = if (NR > n) "Row groups" else "Column groups", allowed = sprintf("at most %d", if (NR > n) n else p), value = if (NR > n) NR else NC)
  }
  A <- X
  ch <- cs_ml_bicluster_checkerboard(A, NR, NC, METHOD, NCOMP, NBEST, rng, 10)
  iterations <- ch$iterations
  biclusters <- list()
  for (r in seq_len(NR) - 1L) for (cc in seq_len(NC) - 1L) biclusters[[length(biclusters) + 1L]] <- list(I = ch$rows == r, J = ch$cols == cc)
}

# %% Summaries
k <- length(biclusters)
summ <- cs_ml_bicluster_summary(A, biclusters)
values <- list(n = n, p = p, k = k)
values["delta"] <- list(delta)
values["iterations"] <- list(iterations)
values$membership_check <- cs_ml_bicluster_checksum(biclusters)
covered_rows <- rep(FALSE, n)
covered_cells <- matrix(FALSE, n, p)
for (b in biclusters) {
  covered_rows <- covered_rows | b$I
  covered_cells[b$I, b$J] <- TRUE
}
values$rows_covered <- mean(covered_rows)
values$cells_covered <- mean(covered_cells)
msrs <- vapply(summ, function(s) s$msr, numeric(1))
msrs <- msrs[!is.nan(msrs)]
values["msr_mean"] <- list(if (length(msrs)) mean(msrs) else NULL)
for (b in seq_along(summ)) {
  values[[sprintf("n_rows[%d]", b)]] <- summ[[b]]$n_rows
  values[[sprintf("n_cols[%d]", b)]] <- summ[[b]]$n_cols
  values[[sprintf("msr[%d]", b)]] <- summ[[b]]$msr
  values[[sprintf("mean[%d]", b)]] <- summ[[b]]$mean
}
tables <- list(list(
  key = "biclusters", title = "Biclusters",
  columns = list(
    list(key = "bicluster", label = "Bicluster", type = "integer"),
    list(key = "rows", label = "Rows", type = "integer"),
    list(key = "cols", label = "Columns", type = "integer"),
    list(key = "columns", label = "Which columns", type = "string"),
    list(key = "msr", label = "Mean squared residue", type = "number"),
    list(key = "mean", label = "Mean value", type = "number")
  ),
  rows = lapply(seq_along(biclusters), function(b) {
    J <- biclusters[[b]]$J
    nm <- FEATURES[which(J)]
    list(bicluster = b, rows = summ[[b]]$n_rows, cols = summ[[b]]$n_cols,
         columns = paste0(paste(utils::head(nm, 12), collapse = ", "), if (sum(J) > 12) " …" else ""),
         msr = summ[[b]]$msr, mean = summ[[b]]$mean)
  })
))

# %% Artifacts: labels.parquet (row, first bicluster, one flag per bicluster) and biclusters.json
first <- rep(-1L, n)
flags <- list()
for (b in seq_along(biclusters)) {
  I <- biclusters[[b]]$I
  first[first == -1L & I] <- b
  flags[[sprintf("in_%d", b)]] <- I
}
path <- do.call(cs_ml_write_labels, c(list(out, rows, first), flags))
bpath <- file.path(out, "biclusters.json")
bj <- list(k = k,
           rows = lapply(biclusters, function(b) I(as.integer(rows[which(b$I)]))),
           cols = lapply(biclusters, function(b) I(FEATURES[which(b$J)])))
writeLines(as.character(jsonlite::toJSON(bj, auto_unbox = TRUE)), bpath, useBytes = TRUE)

# %% Heatmap
charts <- list()
if (p <= 120 && k > 0) {
  show <- if (n <= 400) seq_len(n) else which(covered_rows)[cs_ml_even_sample(sum(covered_rows), 400) + 1L]
  if (!is.null(ROW_ID)) {
    names <- cs_ml_label_text(df[[ROW_ID]][rows + 1L])
    names[is.na(names)] <- ""
    if (length(unique(names)) < n) names <- sprintf("%s #%d", names, seq_len(n))
  } else {
    names <- sprintf("row %d", rows + 1L)
  }
  cell_b <- matrix(-1L, n, p)
  for (b in seq_along(biclusters)) {
    I <- biclusters[[b]]$I
    J <- biclusters[[b]]$J
    blk <- cell_b[I, J, drop = FALSE]
    blk[blk == -1L] <- b
    cell_b[I, J] <- blk
  }
  rr <- rep(show, each = p)
  jj <- rep(seq_len(p), times = length(show))
  vlabel <- if (ALGORITHM == "cheng_church" && "standard" == "standard") "Value (standardized)" else "Value"
  roles <- list(
    row = cs_col("Row", names[rr], "categorical", levels = names[show]),
    column = cs_col("Column", FEATURES[jj], "categorical", levels = FEATURES),
    value = cs_col(vlabel, A[cbind(rr, jj)], "numeric")
  )
  if (k <= 29) roles$bicluster <- cs_col("Bicluster", as.character(cell_b[cbind(rr, jj)]), "categorical", levels = c(as.character(seq_len(k)), "-1"))
  charts[[1]] <- cs_chart("heatmap", "bicluster-heatmap", "Biclusters in the table", roles,
                          note = if (length(show) == n) NULL else sprintf("%s of %s rows shown (rows in a bicluster, evenly sampled).", format(length(show), big.mark = ","), format(n, big.mark = ",")))
}

# %% Result
cs_publish(list(
  title = "Biclustering (rows × columns)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = n,
  summary = paste0(sprintf("%d bicluster%s in %s rows × %d columns covering %.0f%% of the rows", k, if (k != 1) "s" else "", format(n, big.mark = ","), p, values$rows_covered * 100),
                   if (!is.null(values$msr_mean)) sprintf("; mean squared residue %s.", format(signif(values$msr_mean, 3))) else "."),
  statistics = list(list(key = "k", label = "Biclusters", value = k, format = "integer"),
                    list(key = "rows_covered", label = "Rows covered", value = values$rows_covered, format = "percent"),
                    list(key = "msr_mean", label = "Mean squared residue", value = values$msr_mean)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet"), list(key = "biclusters", path = bpath, format = "json")),
  model = list(kind = "bicluster", features = I(FEATURES), params = list(
    algorithm = "cheng_church",
    k = 3,
    delta_share = 0.02,
    alpha = 1.2,
    scale = "standard",
    n_row_clusters = 3,
    n_col_clusters = 3,
    normalize = "bistochastic",
    n_components = 6,
    n_best = 3,
    n_init = 10
  ))
))
Python

3 biclusters in 60 rows × 12 columns covering 37% of the rows; mean squared residue 0.00923.

Biclusters
3
Rows covered
36.7%
Mean squared residue
0.0092

To keep this page light, the plots are shown once, under the R tab.

Biclusters

BiclusterRowsColumnsWhich columnsMean squared residueMean value
1104x7, x8, x9, x100.0027−0.3418
285x1, x2, x3, x4, x50.01120.0863
344x4, x6, x9, x110.01380.1289
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Biclustering (rows × columns)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bicluster 1.0.0 · spec 31b304c79ce1b41c
# Dataset: clu4_bicluster (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.ml import cluster_bicluster as cb
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng

# %% Data
FEATURES = ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12"]
ROW_ID = "id"  # row labels for the heatmap
SEED = 42
ALGORITHM = "cheng_church"
df = pd.read_parquet("tests/parity/fixtures/clu4_bicluster.parquet", columns=list(dict.fromkeys(FEATURES + ([ROW_ID] if ROW_ID else []))))
n_input = len(df)
cs.check_finite_columns(df, FEATURES)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, FEATURES)
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 4, "Biclustering")
X = csembed.numeric_matrix(df, FEATURES, rows)
n, p = X.shape
if np.all(np.ptp(X, axis=0) == 0):
    cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
out = csml.out_dir("target/academy-parity/run-85263/discover.bicluster/planted_cheng_church/out-python")
rng = Rng(SEED)
delta = None
iterations = None


def need_nonnegative(strict: bool) -> None:
    bad = (X <= 0) if strict else (X < 0)
    for j, f in enumerate(FEATURES):
        if np.any(bad[:, j]):
            cs.cs_error("CS_E_INVALID_VALUES", column=f, requirement="positive" if strict else "zero or more", count=int(np.sum(bad[:, j])))
    if np.any(X.sum(axis=1) <= 0):
        cs.cs_error("CS_E_INVALID_VALUES", column="Row totals", requirement="positive", count=int(np.sum(X.sum(axis=1) <= 0)))
    if np.any(X.sum(axis=0) <= 0):
        cs.cs_error("CS_E_INVALID_VALUES", column="Column totals", requirement="positive", count=int(np.sum(X.sum(axis=0) <= 0)))


# %% Biclusters
if ALGORITHM == "cheng_church":
    A = X.copy()
    if "standard" == "standard":
        flat = np.ptp(A, axis=0) == 0
        sd = A.std(axis=0, ddof=0)
        sd[flat] = 1.0
        A = (A - A.mean(axis=0)) / sd
        A[:, flat] = 0.0  # constant columns exactly 0 in both engines
    h_full = cb.msr(A, np.ones(n, dtype=bool), np.ones(p, dtype=bool))
    if h_full <= 0:
        cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
    delta = float(0.02) * h_full
    biclusters = cb.cheng_church(A, 3, delta, float(1.2), rng)
    if not biclusters:
        warnings.append("No block came below the residue threshold with at least two rows and two columns; raise the threshold.")
elif ALGORITHM == "cocluster":
    need_nonnegative(strict=False)
    K = 3
    n_sv = 1 + int(np.ceil(np.log2(K))) if K > 1 else 1
    if K < 2 or n_sv > min(n, p) or K > n:
        cs.cs_error("CS_E_INVALID_OPTION", option="Biclusters", allowed=f"between 2 and {min(n, 2 ** (min(n, p) - 1))} for this table", value=K)
    A = X
    rl, cl = cb.cocluster(A, K, rng, 10)
    biclusters = [(rl == b, cl == b) for b in range(K)]
else:
    METHOD = "bistochastic"
    need_nonnegative(strict=(METHOD == "log"))
    NR, NC = 3, 3
    NCOMP, NBEST = 6, 3
    if NCOMP > min(n, p):
        cs.cs_error("CS_E_INVALID_OPTION", option="Singular vectors", allowed=f"at most {min(n, p)} for this table", value=NCOMP)
    usable = NCOMP - (0 if METHOD == "log" else 1)
    if NBEST > usable:
        cs.cs_error("CS_E_INVALID_OPTION", option="Vectors kept", allowed=f"at most {usable} with {NCOMP} singular vectors", value=NBEST)
    if NR > n or NC > p:
        cs.cs_error("CS_E_INVALID_OPTION", option="Row groups" if NR > n else "Column groups", allowed=f"at most {n if NR > n else p}", value=NR if NR > n else NC)
    A = X
    rl, cl, iterations = cb.checkerboard(A, NR, NC, METHOD, NCOMP, NBEST, rng, 10)
    biclusters = [(rl == r, cl == c) for r in range(NR) for c in range(NC)]

# %% Summaries
k = len(biclusters)
summ = cb.summarize(A, biclusters)
values = {
    "n": n, "p": p, "k": k, "delta": delta, "iterations": iterations,
    "membership_check": cb.membership_checksum(biclusters, n, p),
}
covered_rows = np.zeros(n, dtype=bool)
covered_cells = np.zeros((n, p), dtype=bool)
for I, J in biclusters:
    covered_rows |= I
    covered_cells[np.ix_(I, J)] = True
values["rows_covered"] = float(np.mean(covered_rows))
values["cells_covered"] = float(np.mean(covered_cells))
msrs = [s["msr"] for s in summ if s["msr"] == s["msr"]]
values["msr_mean"] = float(np.mean(msrs)) if msrs else None
for b, s in enumerate(summ, start=1):
    values[f"n_rows[{b}]"] = s["n_rows"]
    values[f"n_cols[{b}]"] = s["n_cols"]
    values[f"msr[{b}]"] = s["msr"]
    values[f"mean[{b}]"] = s["mean"]
tables = [{
    "key": "biclusters",
    "title": "Biclusters",
    "columns": [
        {"key": "bicluster", "label": "Bicluster", "type": "integer"},
        {"key": "rows", "label": "Rows", "type": "integer"},
        {"key": "cols", "label": "Columns", "type": "integer"},
        {"key": "columns", "label": "Which columns", "type": "string"},
        {"key": "msr", "label": "Mean squared residue", "type": "number"},
        {"key": "mean", "label": "Mean value", "type": "number"},
    ],
    "rows": [
        {"bicluster": b, "rows": s["n_rows"], "cols": s["n_cols"],
         "columns": ", ".join([FEATURES[j] for j in np.flatnonzero(J)][:12]) + (" …" if int(J.sum()) > 12 else ""),
         "msr": s["msr"], "mean": s["mean"]}
        for b, ((I, J), s) in enumerate(zip(biclusters, summ), start=1)
    ],
}]

# %% Artifacts: labels.parquet (row, first bicluster, one flag per bicluster) and biclusters.json
first = np.full(n, -1, dtype=np.int64)
flags = {}
for b, (I, J) in enumerate(biclusters, start=1):
    first[(first == -1) & I] = b
    flags[f"in_{b}"] = I.copy()
path = csc.write_labels(out, rows, first, **flags)
bpath = os.path.join(out, "biclusters.json")
with open(bpath, "w", encoding="utf-8") as fh:
    json.dump({"k": k, "rows": [[int(rows[i]) for i in np.flatnonzero(I)] for I, _ in biclusters],
               "cols": [[FEATURES[j] for j in np.flatnonzero(J)] for _, J in biclusters]}, fh)

# %% Heatmap
charts = []
if p <= 120 and k > 0:
    show = np.arange(n) if n <= 400 else np.flatnonzero(covered_rows)[csc.even_sample(int(covered_rows.sum()), 400)]
    if ROW_ID:
        names = cc.label_text(df[ROW_ID].iloc[rows].tolist())
        names = np.array(["" if v is None else v for v in names], dtype=object)
        if len(set(names.tolist())) < n:
            names = np.array([f"{v} #{i + 1}" for i, v in enumerate(names)], dtype=object)
    else:
        names = np.array([f"row {int(r) + 1}" for r in rows], dtype=object)
    cell_b = np.full((n, p), -1, dtype=np.int64)
    for b, (I, J) in enumerate(biclusters, start=1):
        sub = np.ix_(I, J)
        blk = cell_b[sub]
        blk[blk == -1] = b
        cell_b[sub] = blk
    rr = [int(i) for i in show for _ in range(p)]
    jj = [j for _ in show for j in range(p)]
    charts.append(cs.chart(
        "heatmap", "bicluster-heatmap", "Biclusters in the table",
        {
            "row": cs.col("Row", [names[i] for i in rr], "categorical", levels=[names[i] for i in show]),
            "column": cs.col("Column", [FEATURES[j] for j in jj], "categorical", levels=FEATURES),
            "value": cs.col("Value (standardized)" if ALGORITHM == "cheng_church" and "standard" == "standard" else "Value",
                            [float(A[i, j]) for i, j in zip(rr, jj)], "numeric"),
            "bicluster": cs.col("Bicluster", [str(cell_b[i, j]) for i, j in zip(rr, jj)], "categorical",
                                levels=[str(b) for b in range(1, k + 1)] + ["-1"]) if k <= 29 else None,
        },
        note=None if len(show) == n else f"{len(show):,} of {n:,} rows shown (rows in a bicluster, evenly sampled).",
    ))

# %% Result
cs.publish({
    "title": "Biclustering (rows × columns)",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": (f"{k} bicluster{'s' if k != 1 else ''} in {n:,} rows × {p} columns covering {values['rows_covered'] * 100:.0f}% of the rows"
                + (f"; mean squared residue {values['msr_mean']:.3g}." if values["msr_mean"] is not None else ".")),
    "statistics": [
        {"key": "k", "label": "Biclusters", "value": k, "format": "integer"},
        {"key": "rows_covered", "label": "Rows covered", "value": values["rows_covered"], "format": "percent"},
        {"key": "msr_mean", "label": "Mean squared residue", "value": values["msr_mean"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}, {"key": "biclusters", "path": bpath, "format": "json"}],
    "model": {"kind": "bicluster", "features": FEATURES, "params": {
        "algorithm": "cheng_church",
        "k": 3,
        "delta_share": 0.02,
        "alpha": 1.2,
        "scale": "standard",
        "n_row_clusters": 3,
        "n_col_clusters": 3,
        "normalize": "bistochastic",
        "n_components": 6,
        "n_best": 3,
        "n_init": 10,
    }},
})
Bicluster heatmapWhich subsets of rows share a pattern on a subset of columns?
View data
genesampleexpression (log scale)bicluster
gene 01sample 010.8330-1
gene 01sample 02−1.025-1
gene 01sample 030.4180-1
gene 01sample 041.147-1
gene 01sample 05−0.4030-1
gene 01sample 061.160-1
gene 01sample 070.9440-1
gene 01sample 08−0.7910-1
gene 01sample 09−1.156-1
gene 01sample 100.1760-1
gene 01sample 111.090-1
gene 01sample 121.399-1
gene 01sample 13−0.7610-1
gene 01sample 14−0.3570-1
gene 02sample 014.5701
gene 02sample 020.2720-1
gene 02sample 030.1030-1
gene 02sample 043.4811
gene 02sample 050.5420-1
gene 02sample 060.8290-1
gene 02sample 074.2801
gene 02sample 080.1560-1
gene 02sample 090.8460-1
gene 02sample 102.7221
gene 02sample 110.0230-1
gene 02sample 12−0.2100-1
gene 02sample 132.5841
gene 02sample 140.0170-1
gene 03sample 01−0.2430-1
gene 03sample 02−0.2460-1
gene 03sample 03−0.4660-1
gene 03sample 04−0.6590-1
gene 03sample 051.155-1
gene 03sample 060.4950-1
gene 03sample 07−0.3270-1
gene 03sample 080.0700-1
gene 03sample 09−0.3500-1
gene 03sample 10−1.105-1
gene 03sample 111.886-1
gene 03sample 12−0.9110-1
gene 03sample 13−1.615-1
gene 03sample 140.1000-1
gene 04sample 010.0090-1
gene 04sample 02−2.1862
gene 04sample 030.1620-1
gene 04sample 04−0.4650-1
gene 04sample 05−1.7062
gene 04sample 06−0.3010-1
gene 04sample 07−0.0390-1
gene 04sample 08−1.9902
gene 04sample 091.293-1
gene 04sample 100.3880-1
gene 04sample 11−4.1182
gene 04sample 12−0.1250-1
gene 04sample 130.8840-1
gene 04sample 14−2.5812
gene 05sample 010.2000-1
gene 05sample 021.892-1
gene 05sample 030.6110-1
gene 05sample 040.8230-1

First 60 of 336 rows.

The first two blocks sit inside the planted ones, with exactly the planted columns. The search can miss a few rows of a block, and later blocks may be small leftovers: Cheng–Church is greedy, so treat each block as a candidate to check, not a final answer.

04

Blocks of large values: spectral co-clustering

Read

Counts such as documents × words often hold blocks of large values instead. Spectral co-clusteringSpectral co-clusteringPuts every row and every column in one of k blocks using singular vectors of the scaled table; needs non-negative values. scales the table by its row and column totals, takes singular vectors, and clusters rows and columns together, so each block gets its documents and its words. It needs non-negative values.

Biclustering (rows × columns)Recorded · Python and R agreeRecorded 2026-11-21 · 21 values compared
R

3 biclusters in 45 rows × 9 columns covering 100% of the rows; mean squared residue 0.831.

Biclusters
3
Rows covered
100.0%
Mean squared residue
0.8313

Plots

Biclusters in the tableWhich subsets of rows share a pattern on a subset of columns?
View data
BiclusterColumnRowValue
1w1r019.570
1w2r0111.898
1w3r018.122
-1w4r010.2424
-1w5r010.6986
-1w6r010.8396
-1w7r010.5654
-1w8r010.7511
-1w9r010.4712
1w1r0211.719
1w2r0211.150
1w3r0211.123
-1w4r020.2408
-1w5r020.8105
-1w6r020.4153
-1w7r020.8588
-1w8r020.6674
-1w9r020.4725
1w1r0310.277
1w2r0311.542
1w3r0310.511
-1w4r030.8614
-1w5r030.4387
-1w6r030.4035
-1w7r030.7155
-1w8r030.3125
-1w9r030.6034
1w1r049.755
1w2r0410.772
1w3r049.594
-1w4r040.3186
-1w5r040.5174
-1w6r040.2591
-1w7r040.2653
-1w8r040.1000
-1w9r040.2405
1w1r0511.118
1w2r0511.377
1w3r058.737
-1w4r050.0714
-1w5r050.3758
-1w6r050.0486
-1w7r050.3771
-1w8r050.5283
-1w9r050.0044
1w1r0611.662
1w2r0610.468
1w3r069.867
-1w4r060.7775
-1w5r060.8947
-1w6r060.3795
-1w7r060.8201
-1w8r060.6985
-1w9r060.1334
1w1r0711.408
1w2r0710.928
1w3r079.814
-1w4r070.0852
-1w5r070.6383
-1w6r070.1997

First 60 of 405 rows.

Biclusters

BiclusterRowsColumnsWhich columnsMean squared residueMean value
1153w1, w2, w30.536110.443
2153w4, w5, w61.04110.118
3153w7, w8, w90.91689.859
The exact R script · R R version 4.5.1 (2025-06-13)
# Biclustering (rows × columns)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bicluster 1.0.0 · spec 8d7d88aff2abea30
# Dataset: clu4_cocluster (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8", "w9")
ROW_ID <- "id"  # row labels for the heatmap
SEED <- 42
ALGORITHM <- "cocluster"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_cocluster.parquet", col_select = unique(c(FEATURES, ROW_ID))))
n_input <- nrow(df)
cs_check_finite_columns(df, FEATURES)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, FEATURES)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 4, "Biclustering")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
dimnames(X) <- NULL
n <- nrow(X)
p <- ncol(X)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
out <- cs_ml_out_dir("target/academy-parity/run-85263/discover.bicluster/blocks_cocluster/out-r")
rng <- cs_rng(SEED)
delta <- NULL
iterations <- NULL

need_nonnegative <- function(strict) {
  bad <- if (strict) X <= 0 else X < 0
  for (j in seq_along(FEATURES)) {
    if (any(bad[, j])) cs_error("CS_E_INVALID_VALUES", column = FEATURES[j], requirement = if (strict) "positive" else "zero or more", count = sum(bad[, j]))
  }
  if (any(rowSums(X) <= 0)) cs_error("CS_E_INVALID_VALUES", column = "Row totals", requirement = "positive", count = sum(rowSums(X) <= 0))
  if (any(colSums(X) <= 0)) cs_error("CS_E_INVALID_VALUES", column = "Column totals", requirement = "positive", count = sum(colSums(X) <= 0))
}

# %% Biclusters
if (ALGORITHM == "cheng_church") {
  A <- X
  if ("standard" == "standard") {
    flat <- apply(A, 2, function(v) max(v) - min(v)) == 0
    sd0 <- apply(A, 2, function(v) sqrt(mean((v - mean(v))^2)))
    sd0[flat] <- 1
    A <- sweep(sweep(A, 2, colMeans(A)), 2, sd0, "/")
    A[, flat] <- 0  # constant columns exactly 0 in both engines
  }
  h_full <- cs_ml_bicluster_msr(A, rep(TRUE, n), rep(TRUE, p))
  if (h_full <= 0) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
  delta <- as.numeric(0.02) * h_full
  found <- cs_ml_bicluster_cheng_church(A, 3, delta, as.numeric(1.2), rng)
  biclusters <- found
  if (!length(biclusters)) warnings <- c(warnings, "No block came below the residue threshold with at least two rows and two columns; raise the threshold.")
} else if (ALGORITHM == "cocluster") {
  need_nonnegative(FALSE)
  K <- 3
  n_sv <- if (K > 1) 1 + ceiling(log2(K)) else 1
  if (K < 2 || n_sv > min(n, p) || K > n) {
    cs_error("CS_E_INVALID_OPTION", option = "Biclusters", allowed = sprintf("between 2 and %d for this table", as.integer(min(n, 2^(min(n, p) - 1)))), value = K)
  }
  A <- X
  co <- cs_ml_bicluster_cocluster(A, K, rng, 10)
  biclusters <- lapply(seq_len(K) - 1L, function(b) list(I = co$rows == b, J = co$cols == b))
} else {
  METHOD <- "bistochastic"
  need_nonnegative(METHOD == "log")
  NR <- 3
  NC <- 3
  NCOMP <- 6
  NBEST <- 3
  if (NCOMP > min(n, p)) cs_error("CS_E_INVALID_OPTION", option = "Singular vectors", allowed = sprintf("at most %d for this table", min(n, p)), value = NCOMP)
  usable <- NCOMP - (if (METHOD == "log") 0 else 1)
  if (NBEST > usable) cs_error("CS_E_INVALID_OPTION", option = "Vectors kept", allowed = sprintf("at most %d with %d singular vectors", usable, NCOMP), value = NBEST)
  if (NR > n || NC > p) {
    cs_error("CS_E_INVALID_OPTION", option = if (NR > n) "Row groups" else "Column groups", allowed = sprintf("at most %d", if (NR > n) n else p), value = if (NR > n) NR else NC)
  }
  A <- X
  ch <- cs_ml_bicluster_checkerboard(A, NR, NC, METHOD, NCOMP, NBEST, rng, 10)
  iterations <- ch$iterations
  biclusters <- list()
  for (r in seq_len(NR) - 1L) for (cc in seq_len(NC) - 1L) biclusters[[length(biclusters) + 1L]] <- list(I = ch$rows == r, J = ch$cols == cc)
}

# %% Summaries
k <- length(biclusters)
summ <- cs_ml_bicluster_summary(A, biclusters)
values <- list(n = n, p = p, k = k)
values["delta"] <- list(delta)
values["iterations"] <- list(iterations)
values$membership_check <- cs_ml_bicluster_checksum(biclusters)
covered_rows <- rep(FALSE, n)
covered_cells <- matrix(FALSE, n, p)
for (b in biclusters) {
  covered_rows <- covered_rows | b$I
  covered_cells[b$I, b$J] <- TRUE
}
values$rows_covered <- mean(covered_rows)
values$cells_covered <- mean(covered_cells)
msrs <- vapply(summ, function(s) s$msr, numeric(1))
msrs <- msrs[!is.nan(msrs)]
values["msr_mean"] <- list(if (length(msrs)) mean(msrs) else NULL)
for (b in seq_along(summ)) {
  values[[sprintf("n_rows[%d]", b)]] <- summ[[b]]$n_rows
  values[[sprintf("n_cols[%d]", b)]] <- summ[[b]]$n_cols
  values[[sprintf("msr[%d]", b)]] <- summ[[b]]$msr
  values[[sprintf("mean[%d]", b)]] <- summ[[b]]$mean
}
tables <- list(list(
  key = "biclusters", title = "Biclusters",
  columns = list(
    list(key = "bicluster", label = "Bicluster", type = "integer"),
    list(key = "rows", label = "Rows", type = "integer"),
    list(key = "cols", label = "Columns", type = "integer"),
    list(key = "columns", label = "Which columns", type = "string"),
    list(key = "msr", label = "Mean squared residue", type = "number"),
    list(key = "mean", label = "Mean value", type = "number")
  ),
  rows = lapply(seq_along(biclusters), function(b) {
    J <- biclusters[[b]]$J
    nm <- FEATURES[which(J)]
    list(bicluster = b, rows = summ[[b]]$n_rows, cols = summ[[b]]$n_cols,
         columns = paste0(paste(utils::head(nm, 12), collapse = ", "), if (sum(J) > 12) " …" else ""),
         msr = summ[[b]]$msr, mean = summ[[b]]$mean)
  })
))

# %% Artifacts: labels.parquet (row, first bicluster, one flag per bicluster) and biclusters.json
first <- rep(-1L, n)
flags <- list()
for (b in seq_along(biclusters)) {
  I <- biclusters[[b]]$I
  first[first == -1L & I] <- b
  flags[[sprintf("in_%d", b)]] <- I
}
path <- do.call(cs_ml_write_labels, c(list(out, rows, first), flags))
bpath <- file.path(out, "biclusters.json")
bj <- list(k = k,
           rows = lapply(biclusters, function(b) I(as.integer(rows[which(b$I)]))),
           cols = lapply(biclusters, function(b) I(FEATURES[which(b$J)])))
writeLines(as.character(jsonlite::toJSON(bj, auto_unbox = TRUE)), bpath, useBytes = TRUE)

# %% Heatmap
charts <- list()
if (p <= 120 && k > 0) {
  show <- if (n <= 400) seq_len(n) else which(covered_rows)[cs_ml_even_sample(sum(covered_rows), 400) + 1L]
  if (!is.null(ROW_ID)) {
    names <- cs_ml_label_text(df[[ROW_ID]][rows + 1L])
    names[is.na(names)] <- ""
    if (length(unique(names)) < n) names <- sprintf("%s #%d", names, seq_len(n))
  } else {
    names <- sprintf("row %d", rows + 1L)
  }
  cell_b <- matrix(-1L, n, p)
  for (b in seq_along(biclusters)) {
    I <- biclusters[[b]]$I
    J <- biclusters[[b]]$J
    blk <- cell_b[I, J, drop = FALSE]
    blk[blk == -1L] <- b
    cell_b[I, J] <- blk
  }
  rr <- rep(show, each = p)
  jj <- rep(seq_len(p), times = length(show))
  vlabel <- if (ALGORITHM == "cheng_church" && "standard" == "standard") "Value (standardized)" else "Value"
  roles <- list(
    row = cs_col("Row", names[rr], "categorical", levels = names[show]),
    column = cs_col("Column", FEATURES[jj], "categorical", levels = FEATURES),
    value = cs_col(vlabel, A[cbind(rr, jj)], "numeric")
  )
  if (k <= 29) roles$bicluster <- cs_col("Bicluster", as.character(cell_b[cbind(rr, jj)]), "categorical", levels = c(as.character(seq_len(k)), "-1"))
  charts[[1]] <- cs_chart("heatmap", "bicluster-heatmap", "Biclusters in the table", roles,
                          note = if (length(show) == n) NULL else sprintf("%s of %s rows shown (rows in a bicluster, evenly sampled).", format(length(show), big.mark = ","), format(n, big.mark = ",")))
}

# %% Result
cs_publish(list(
  title = "Biclustering (rows × columns)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = n,
  summary = paste0(sprintf("%d bicluster%s in %s rows × %d columns covering %.0f%% of the rows", k, if (k != 1) "s" else "", format(n, big.mark = ","), p, values$rows_covered * 100),
                   if (!is.null(values$msr_mean)) sprintf("; mean squared residue %s.", format(signif(values$msr_mean, 3))) else "."),
  statistics = list(list(key = "k", label = "Biclusters", value = k, format = "integer"),
                    list(key = "rows_covered", label = "Rows covered", value = values$rows_covered, format = "percent"),
                    list(key = "msr_mean", label = "Mean squared residue", value = values$msr_mean)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet"), list(key = "biclusters", path = bpath, format = "json")),
  model = list(kind = "bicluster", features = I(FEATURES), params = list(
    algorithm = "cocluster",
    k = 3,
    delta_share = 0.02,
    alpha = 1.2,
    scale = "standard",
    n_row_clusters = 3,
    n_col_clusters = 3,
    normalize = "bistochastic",
    n_components = 6,
    n_best = 3,
    n_init = 10
  ))
))
Python

3 biclusters in 45 rows × 9 columns covering 100% of the rows; mean squared residue 0.831.

Biclusters
3
Rows covered
100.0%
Mean squared residue
0.8313

To keep this page light, the plots are shown once, under the R tab.

Biclusters

BiclusterRowsColumnsWhich columnsMean squared residueMean value
1153w1, w2, w30.536110.443
2153w4, w5, w61.04110.118
3153w7, w8, w90.91689.859
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Biclustering (rows × columns)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bicluster 1.0.0 · spec 8d7d88aff2abea30
# Dataset: clu4_cocluster (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.ml import cluster_bicluster as cb
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng

# %% Data
FEATURES = ["w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8", "w9"]
ROW_ID = "id"  # row labels for the heatmap
SEED = 42
ALGORITHM = "cocluster"
df = pd.read_parquet("tests/parity/fixtures/clu4_cocluster.parquet", columns=list(dict.fromkeys(FEATURES + ([ROW_ID] if ROW_ID else []))))
n_input = len(df)
cs.check_finite_columns(df, FEATURES)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, FEATURES)
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 4, "Biclustering")
X = csembed.numeric_matrix(df, FEATURES, rows)
n, p = X.shape
if np.all(np.ptp(X, axis=0) == 0):
    cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
out = csml.out_dir("target/academy-parity/run-85263/discover.bicluster/blocks_cocluster/out-python")
rng = Rng(SEED)
delta = None
iterations = None


def need_nonnegative(strict: bool) -> None:
    bad = (X <= 0) if strict else (X < 0)
    for j, f in enumerate(FEATURES):
        if np.any(bad[:, j]):
            cs.cs_error("CS_E_INVALID_VALUES", column=f, requirement="positive" if strict else "zero or more", count=int(np.sum(bad[:, j])))
    if np.any(X.sum(axis=1) <= 0):
        cs.cs_error("CS_E_INVALID_VALUES", column="Row totals", requirement="positive", count=int(np.sum(X.sum(axis=1) <= 0)))
    if np.any(X.sum(axis=0) <= 0):
        cs.cs_error("CS_E_INVALID_VALUES", column="Column totals", requirement="positive", count=int(np.sum(X.sum(axis=0) <= 0)))


# %% Biclusters
if ALGORITHM == "cheng_church":
    A = X.copy()
    if "standard" == "standard":
        flat = np.ptp(A, axis=0) == 0
        sd = A.std(axis=0, ddof=0)
        sd[flat] = 1.0
        A = (A - A.mean(axis=0)) / sd
        A[:, flat] = 0.0  # constant columns exactly 0 in both engines
    h_full = cb.msr(A, np.ones(n, dtype=bool), np.ones(p, dtype=bool))
    if h_full <= 0:
        cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
    delta = float(0.02) * h_full
    biclusters = cb.cheng_church(A, 3, delta, float(1.2), rng)
    if not biclusters:
        warnings.append("No block came below the residue threshold with at least two rows and two columns; raise the threshold.")
elif ALGORITHM == "cocluster":
    need_nonnegative(strict=False)
    K = 3
    n_sv = 1 + int(np.ceil(np.log2(K))) if K > 1 else 1
    if K < 2 or n_sv > min(n, p) or K > n:
        cs.cs_error("CS_E_INVALID_OPTION", option="Biclusters", allowed=f"between 2 and {min(n, 2 ** (min(n, p) - 1))} for this table", value=K)
    A = X
    rl, cl = cb.cocluster(A, K, rng, 10)
    biclusters = [(rl == b, cl == b) for b in range(K)]
else:
    METHOD = "bistochastic"
    need_nonnegative(strict=(METHOD == "log"))
    NR, NC = 3, 3
    NCOMP, NBEST = 6, 3
    if NCOMP > min(n, p):
        cs.cs_error("CS_E_INVALID_OPTION", option="Singular vectors", allowed=f"at most {min(n, p)} for this table", value=NCOMP)
    usable = NCOMP - (0 if METHOD == "log" else 1)
    if NBEST > usable:
        cs.cs_error("CS_E_INVALID_OPTION", option="Vectors kept", allowed=f"at most {usable} with {NCOMP} singular vectors", value=NBEST)
    if NR > n or NC > p:
        cs.cs_error("CS_E_INVALID_OPTION", option="Row groups" if NR > n else "Column groups", allowed=f"at most {n if NR > n else p}", value=NR if NR > n else NC)
    A = X
    rl, cl, iterations = cb.checkerboard(A, NR, NC, METHOD, NCOMP, NBEST, rng, 10)
    biclusters = [(rl == r, cl == c) for r in range(NR) for c in range(NC)]

# %% Summaries
k = len(biclusters)
summ = cb.summarize(A, biclusters)
values = {
    "n": n, "p": p, "k": k, "delta": delta, "iterations": iterations,
    "membership_check": cb.membership_checksum(biclusters, n, p),
}
covered_rows = np.zeros(n, dtype=bool)
covered_cells = np.zeros((n, p), dtype=bool)
for I, J in biclusters:
    covered_rows |= I
    covered_cells[np.ix_(I, J)] = True
values["rows_covered"] = float(np.mean(covered_rows))
values["cells_covered"] = float(np.mean(covered_cells))
msrs = [s["msr"] for s in summ if s["msr"] == s["msr"]]
values["msr_mean"] = float(np.mean(msrs)) if msrs else None
for b, s in enumerate(summ, start=1):
    values[f"n_rows[{b}]"] = s["n_rows"]
    values[f"n_cols[{b}]"] = s["n_cols"]
    values[f"msr[{b}]"] = s["msr"]
    values[f"mean[{b}]"] = s["mean"]
tables = [{
    "key": "biclusters",
    "title": "Biclusters",
    "columns": [
        {"key": "bicluster", "label": "Bicluster", "type": "integer"},
        {"key": "rows", "label": "Rows", "type": "integer"},
        {"key": "cols", "label": "Columns", "type": "integer"},
        {"key": "columns", "label": "Which columns", "type": "string"},
        {"key": "msr", "label": "Mean squared residue", "type": "number"},
        {"key": "mean", "label": "Mean value", "type": "number"},
    ],
    "rows": [
        {"bicluster": b, "rows": s["n_rows"], "cols": s["n_cols"],
         "columns": ", ".join([FEATURES[j] for j in np.flatnonzero(J)][:12]) + (" …" if int(J.sum()) > 12 else ""),
         "msr": s["msr"], "mean": s["mean"]}
        for b, ((I, J), s) in enumerate(zip(biclusters, summ), start=1)
    ],
}]

# %% Artifacts: labels.parquet (row, first bicluster, one flag per bicluster) and biclusters.json
first = np.full(n, -1, dtype=np.int64)
flags = {}
for b, (I, J) in enumerate(biclusters, start=1):
    first[(first == -1) & I] = b
    flags[f"in_{b}"] = I.copy()
path = csc.write_labels(out, rows, first, **flags)
bpath = os.path.join(out, "biclusters.json")
with open(bpath, "w", encoding="utf-8") as fh:
    json.dump({"k": k, "rows": [[int(rows[i]) for i in np.flatnonzero(I)] for I, _ in biclusters],
               "cols": [[FEATURES[j] for j in np.flatnonzero(J)] for _, J in biclusters]}, fh)

# %% Heatmap
charts = []
if p <= 120 and k > 0:
    show = np.arange(n) if n <= 400 else np.flatnonzero(covered_rows)[csc.even_sample(int(covered_rows.sum()), 400)]
    if ROW_ID:
        names = cc.label_text(df[ROW_ID].iloc[rows].tolist())
        names = np.array(["" if v is None else v for v in names], dtype=object)
        if len(set(names.tolist())) < n:
            names = np.array([f"{v} #{i + 1}" for i, v in enumerate(names)], dtype=object)
    else:
        names = np.array([f"row {int(r) + 1}" for r in rows], dtype=object)
    cell_b = np.full((n, p), -1, dtype=np.int64)
    for b, (I, J) in enumerate(biclusters, start=1):
        sub = np.ix_(I, J)
        blk = cell_b[sub]
        blk[blk == -1] = b
        cell_b[sub] = blk
    rr = [int(i) for i in show for _ in range(p)]
    jj = [j for _ in show for j in range(p)]
    charts.append(cs.chart(
        "heatmap", "bicluster-heatmap", "Biclusters in the table",
        {
            "row": cs.col("Row", [names[i] for i in rr], "categorical", levels=[names[i] for i in show]),
            "column": cs.col("Column", [FEATURES[j] for j in jj], "categorical", levels=FEATURES),
            "value": cs.col("Value (standardized)" if ALGORITHM == "cheng_church" and "standard" == "standard" else "Value",
                            [float(A[i, j]) for i, j in zip(rr, jj)], "numeric"),
            "bicluster": cs.col("Bicluster", [str(cell_b[i, j]) for i, j in zip(rr, jj)], "categorical",
                                levels=[str(b) for b in range(1, k + 1)] + ["-1"]) if k <= 29 else None,
        },
        note=None if len(show) == n else f"{len(show):,} of {n:,} rows shown (rows in a bicluster, evenly sampled).",
    ))

# %% Result
cs.publish({
    "title": "Biclustering (rows × columns)",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": (f"{k} bicluster{'s' if k != 1 else ''} in {n:,} rows × {p} columns covering {values['rows_covered'] * 100:.0f}% of the rows"
                + (f"; mean squared residue {values['msr_mean']:.3g}." if values["msr_mean"] is not None else ".")),
    "statistics": [
        {"key": "k", "label": "Biclusters", "value": k, "format": "integer"},
        {"key": "rows_covered", "label": "Rows covered", "value": values["rows_covered"], "format": "percent"},
        {"key": "msr_mean", "label": "Mean squared residue", "value": values["msr_mean"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}, {"key": "biclusters", "path": bpath, "format": "json"}],
    "model": {"kind": "bicluster", "features": FEATURES, "params": {
        "algorithm": "cocluster",
        "k": 3,
        "delta_share": 0.02,
        "alpha": 1.2,
        "scale": "standard",
        "n_row_clusters": 3,
        "n_col_clusters": 3,
        "normalize": "bistochastic",
        "n_components": 6,
        "n_best": 3,
        "n_init": 10,
    }},
})
05

Row groups × column groups: the checkerboard

Read

Sometimes every row group has its own level on every column group, like a checkerboard. Spectral biclusteringCheckerboard biclusteringRow groups × column groups, each pair with its own level, found after row and column effects are scaled away. first removes row and column effects (bistochastic scaling by default), keeps the singular vectors that look most like steps, then clusters rows and columns separately. Every row group × column group pair is a bicluster.

Biclustering (rows × columns)Recorded · Python and R agreeRecorded 2026-11-21 · 25 values compared
R

4 biclusters in 40 rows × 8 columns covering 100% of the rows; mean squared residue 0.39.

Biclusters
4
Rows covered
100.0%
Mean squared residue
0.3904

Plots

Biclusters in the tableWhich subsets of rows share a pattern on a subset of columns?
View data
BiclusterColumnRowValue
1v1row 111.977
1v2row 117.666
1v3row 110.238
1v4row 120.097
2v5row 11.477
2v6row 12.760
2v7row 13.376
2v8row 12.105
1v1row 210.039
1v2row 215.610
1v3row 29.316
1v4row 216.079
2v5row 21.358
2v6row 22.305
2v7row 23.147
2v8row 21.693
1v1row 311.159
1v2row 316.173
1v3row 39.284
1v4row 318.923
2v5row 31.330
2v6row 32.411
2v7row 33.527
2v8row 31.847
1v1row 410.578
1v2row 416.248
1v3row 48.815
1v4row 416.851
2v5row 41.343
2v6row 42.334
2v7row 42.830
2v8row 41.717
1v1row 54.510
1v2row 57.518
1v3row 54.484
1v4row 57.968
2v5row 50.6367
2v6row 51.093
2v7row 51.568
2v8row 50.8548
1v1row 611.199
1v2row 617.397
1v3row 69.725
1v4row 617.329
2v5row 61.408
2v6row 62.374
2v7row 63.361
2v8row 62.125
1v1row 77.186
1v2row 711.353
1v3row 76.999
1v4row 711.277
2v5row 71.007
2v6row 71.782
2v7row 72.217
2v8row 71.203
1v1row 812.093
1v2row 818.963
1v3row 811.068
1v4row 818.971

First 60 of 320 rows.

Biclusters

BiclusterRowsColumnsWhich columnsMean squared residueMean value
1204v1, v2, v3, v41.01212.136
2204v5, v6, v7, v80.03682.008
3204v1, v2, v3, v40.08193.445
4204v5, v6, v7, v80.43066.750
The exact R script · R R version 4.5.1 (2025-06-13)
# Biclustering (rows × columns)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bicluster 1.0.0 · spec a75c1bced7cdb3d6
# Dataset: clu4_checker (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8")
ROW_ID <- NULL  # row labels for the heatmap
SEED <- 42
ALGORITHM <- "checkerboard"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_checker.parquet", col_select = unique(c(FEATURES, ROW_ID))))
n_input <- nrow(df)
cs_check_finite_columns(df, FEATURES)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, FEATURES)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 4, "Biclustering")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
dimnames(X) <- NULL
n <- nrow(X)
p <- ncol(X)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
out <- cs_ml_out_dir("target/academy-parity/run-85263/discover.bicluster/checker_bistochastic/out-r")
rng <- cs_rng(SEED)
delta <- NULL
iterations <- NULL

need_nonnegative <- function(strict) {
  bad <- if (strict) X <= 0 else X < 0
  for (j in seq_along(FEATURES)) {
    if (any(bad[, j])) cs_error("CS_E_INVALID_VALUES", column = FEATURES[j], requirement = if (strict) "positive" else "zero or more", count = sum(bad[, j]))
  }
  if (any(rowSums(X) <= 0)) cs_error("CS_E_INVALID_VALUES", column = "Row totals", requirement = "positive", count = sum(rowSums(X) <= 0))
  if (any(colSums(X) <= 0)) cs_error("CS_E_INVALID_VALUES", column = "Column totals", requirement = "positive", count = sum(colSums(X) <= 0))
}

# %% Biclusters
if (ALGORITHM == "cheng_church") {
  A <- X
  if ("standard" == "standard") {
    flat <- apply(A, 2, function(v) max(v) - min(v)) == 0
    sd0 <- apply(A, 2, function(v) sqrt(mean((v - mean(v))^2)))
    sd0[flat] <- 1
    A <- sweep(sweep(A, 2, colMeans(A)), 2, sd0, "/")
    A[, flat] <- 0  # constant columns exactly 0 in both engines
  }
  h_full <- cs_ml_bicluster_msr(A, rep(TRUE, n), rep(TRUE, p))
  if (h_full <= 0) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
  delta <- as.numeric(0.02) * h_full
  found <- cs_ml_bicluster_cheng_church(A, 3, delta, as.numeric(1.2), rng)
  biclusters <- found
  if (!length(biclusters)) warnings <- c(warnings, "No block came below the residue threshold with at least two rows and two columns; raise the threshold.")
} else if (ALGORITHM == "cocluster") {
  need_nonnegative(FALSE)
  K <- 3
  n_sv <- if (K > 1) 1 + ceiling(log2(K)) else 1
  if (K < 2 || n_sv > min(n, p) || K > n) {
    cs_error("CS_E_INVALID_OPTION", option = "Biclusters", allowed = sprintf("between 2 and %d for this table", as.integer(min(n, 2^(min(n, p) - 1)))), value = K)
  }
  A <- X
  co <- cs_ml_bicluster_cocluster(A, K, rng, 10)
  biclusters <- lapply(seq_len(K) - 1L, function(b) list(I = co$rows == b, J = co$cols == b))
} else {
  METHOD <- "bistochastic"
  need_nonnegative(METHOD == "log")
  NR <- 2
  NC <- 2
  NCOMP <- 6
  NBEST <- 3
  if (NCOMP > min(n, p)) cs_error("CS_E_INVALID_OPTION", option = "Singular vectors", allowed = sprintf("at most %d for this table", min(n, p)), value = NCOMP)
  usable <- NCOMP - (if (METHOD == "log") 0 else 1)
  if (NBEST > usable) cs_error("CS_E_INVALID_OPTION", option = "Vectors kept", allowed = sprintf("at most %d with %d singular vectors", usable, NCOMP), value = NBEST)
  if (NR > n || NC > p) {
    cs_error("CS_E_INVALID_OPTION", option = if (NR > n) "Row groups" else "Column groups", allowed = sprintf("at most %d", if (NR > n) n else p), value = if (NR > n) NR else NC)
  }
  A <- X
  ch <- cs_ml_bicluster_checkerboard(A, NR, NC, METHOD, NCOMP, NBEST, rng, 10)
  iterations <- ch$iterations
  biclusters <- list()
  for (r in seq_len(NR) - 1L) for (cc in seq_len(NC) - 1L) biclusters[[length(biclusters) + 1L]] <- list(I = ch$rows == r, J = ch$cols == cc)
}

# %% Summaries
k <- length(biclusters)
summ <- cs_ml_bicluster_summary(A, biclusters)
values <- list(n = n, p = p, k = k)
values["delta"] <- list(delta)
values["iterations"] <- list(iterations)
values$membership_check <- cs_ml_bicluster_checksum(biclusters)
covered_rows <- rep(FALSE, n)
covered_cells <- matrix(FALSE, n, p)
for (b in biclusters) {
  covered_rows <- covered_rows | b$I
  covered_cells[b$I, b$J] <- TRUE
}
values$rows_covered <- mean(covered_rows)
values$cells_covered <- mean(covered_cells)
msrs <- vapply(summ, function(s) s$msr, numeric(1))
msrs <- msrs[!is.nan(msrs)]
values["msr_mean"] <- list(if (length(msrs)) mean(msrs) else NULL)
for (b in seq_along(summ)) {
  values[[sprintf("n_rows[%d]", b)]] <- summ[[b]]$n_rows
  values[[sprintf("n_cols[%d]", b)]] <- summ[[b]]$n_cols
  values[[sprintf("msr[%d]", b)]] <- summ[[b]]$msr
  values[[sprintf("mean[%d]", b)]] <- summ[[b]]$mean
}
tables <- list(list(
  key = "biclusters", title = "Biclusters",
  columns = list(
    list(key = "bicluster", label = "Bicluster", type = "integer"),
    list(key = "rows", label = "Rows", type = "integer"),
    list(key = "cols", label = "Columns", type = "integer"),
    list(key = "columns", label = "Which columns", type = "string"),
    list(key = "msr", label = "Mean squared residue", type = "number"),
    list(key = "mean", label = "Mean value", type = "number")
  ),
  rows = lapply(seq_along(biclusters), function(b) {
    J <- biclusters[[b]]$J
    nm <- FEATURES[which(J)]
    list(bicluster = b, rows = summ[[b]]$n_rows, cols = summ[[b]]$n_cols,
         columns = paste0(paste(utils::head(nm, 12), collapse = ", "), if (sum(J) > 12) " …" else ""),
         msr = summ[[b]]$msr, mean = summ[[b]]$mean)
  })
))

# %% Artifacts: labels.parquet (row, first bicluster, one flag per bicluster) and biclusters.json
first <- rep(-1L, n)
flags <- list()
for (b in seq_along(biclusters)) {
  I <- biclusters[[b]]$I
  first[first == -1L & I] <- b
  flags[[sprintf("in_%d", b)]] <- I
}
path <- do.call(cs_ml_write_labels, c(list(out, rows, first), flags))
bpath <- file.path(out, "biclusters.json")
bj <- list(k = k,
           rows = lapply(biclusters, function(b) I(as.integer(rows[which(b$I)]))),
           cols = lapply(biclusters, function(b) I(FEATURES[which(b$J)])))
writeLines(as.character(jsonlite::toJSON(bj, auto_unbox = TRUE)), bpath, useBytes = TRUE)

# %% Heatmap
charts <- list()
if (p <= 120 && k > 0) {
  show <- if (n <= 400) seq_len(n) else which(covered_rows)[cs_ml_even_sample(sum(covered_rows), 400) + 1L]
  if (!is.null(ROW_ID)) {
    names <- cs_ml_label_text(df[[ROW_ID]][rows + 1L])
    names[is.na(names)] <- ""
    if (length(unique(names)) < n) names <- sprintf("%s #%d", names, seq_len(n))
  } else {
    names <- sprintf("row %d", rows + 1L)
  }
  cell_b <- matrix(-1L, n, p)
  for (b in seq_along(biclusters)) {
    I <- biclusters[[b]]$I
    J <- biclusters[[b]]$J
    blk <- cell_b[I, J, drop = FALSE]
    blk[blk == -1L] <- b
    cell_b[I, J] <- blk
  }
  rr <- rep(show, each = p)
  jj <- rep(seq_len(p), times = length(show))
  vlabel <- if (ALGORITHM == "cheng_church" && "standard" == "standard") "Value (standardized)" else "Value"
  roles <- list(
    row = cs_col("Row", names[rr], "categorical", levels = names[show]),
    column = cs_col("Column", FEATURES[jj], "categorical", levels = FEATURES),
    value = cs_col(vlabel, A[cbind(rr, jj)], "numeric")
  )
  if (k <= 29) roles$bicluster <- cs_col("Bicluster", as.character(cell_b[cbind(rr, jj)]), "categorical", levels = c(as.character(seq_len(k)), "-1"))
  charts[[1]] <- cs_chart("heatmap", "bicluster-heatmap", "Biclusters in the table", roles,
                          note = if (length(show) == n) NULL else sprintf("%s of %s rows shown (rows in a bicluster, evenly sampled).", format(length(show), big.mark = ","), format(n, big.mark = ",")))
}

# %% Result
cs_publish(list(
  title = "Biclustering (rows × columns)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = n,
  summary = paste0(sprintf("%d bicluster%s in %s rows × %d columns covering %.0f%% of the rows", k, if (k != 1) "s" else "", format(n, big.mark = ","), p, values$rows_covered * 100),
                   if (!is.null(values$msr_mean)) sprintf("; mean squared residue %s.", format(signif(values$msr_mean, 3))) else "."),
  statistics = list(list(key = "k", label = "Biclusters", value = k, format = "integer"),
                    list(key = "rows_covered", label = "Rows covered", value = values$rows_covered, format = "percent"),
                    list(key = "msr_mean", label = "Mean squared residue", value = values$msr_mean)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet"), list(key = "biclusters", path = bpath, format = "json")),
  model = list(kind = "bicluster", features = I(FEATURES), params = list(
    algorithm = "checkerboard",
    k = 3,
    delta_share = 0.02,
    alpha = 1.2,
    scale = "standard",
    n_row_clusters = 2,
    n_col_clusters = 2,
    normalize = "bistochastic",
    n_components = 6,
    n_best = 3,
    n_init = 10
  ))
))
Python

4 biclusters in 40 rows × 8 columns covering 100% of the rows; mean squared residue 0.39.

Biclusters
4
Rows covered
100.0%
Mean squared residue
0.3904

To keep this page light, the plots are shown once, under the R tab.

Biclusters

BiclusterRowsColumnsWhich columnsMean squared residueMean value
1204v1, v2, v3, v41.01212.136
2204v5, v6, v7, v80.03682.008
3204v1, v2, v3, v40.08193.445
4204v5, v6, v7, v80.43066.750
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Biclustering (rows × columns)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bicluster 1.0.0 · spec a75c1bced7cdb3d6
# Dataset: clu4_checker (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.ml import cluster_bicluster as cb
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng

# %% Data
FEATURES = ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8"]
ROW_ID = None  # row labels for the heatmap
SEED = 42
ALGORITHM = "checkerboard"
df = pd.read_parquet("tests/parity/fixtures/clu4_checker.parquet", columns=list(dict.fromkeys(FEATURES + ([ROW_ID] if ROW_ID else []))))
n_input = len(df)
cs.check_finite_columns(df, FEATURES)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, FEATURES)
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 4, "Biclustering")
X = csembed.numeric_matrix(df, FEATURES, rows)
n, p = X.shape
if np.all(np.ptp(X, axis=0) == 0):
    cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
out = csml.out_dir("target/academy-parity/run-85263/discover.bicluster/checker_bistochastic/out-python")
rng = Rng(SEED)
delta = None
iterations = None


def need_nonnegative(strict: bool) -> None:
    bad = (X <= 0) if strict else (X < 0)
    for j, f in enumerate(FEATURES):
        if np.any(bad[:, j]):
            cs.cs_error("CS_E_INVALID_VALUES", column=f, requirement="positive" if strict else "zero or more", count=int(np.sum(bad[:, j])))
    if np.any(X.sum(axis=1) <= 0):
        cs.cs_error("CS_E_INVALID_VALUES", column="Row totals", requirement="positive", count=int(np.sum(X.sum(axis=1) <= 0)))
    if np.any(X.sum(axis=0) <= 0):
        cs.cs_error("CS_E_INVALID_VALUES", column="Column totals", requirement="positive", count=int(np.sum(X.sum(axis=0) <= 0)))


# %% Biclusters
if ALGORITHM == "cheng_church":
    A = X.copy()
    if "standard" == "standard":
        flat = np.ptp(A, axis=0) == 0
        sd = A.std(axis=0, ddof=0)
        sd[flat] = 1.0
        A = (A - A.mean(axis=0)) / sd
        A[:, flat] = 0.0  # constant columns exactly 0 in both engines
    h_full = cb.msr(A, np.ones(n, dtype=bool), np.ones(p, dtype=bool))
    if h_full <= 0:
        cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
    delta = float(0.02) * h_full
    biclusters = cb.cheng_church(A, 3, delta, float(1.2), rng)
    if not biclusters:
        warnings.append("No block came below the residue threshold with at least two rows and two columns; raise the threshold.")
elif ALGORITHM == "cocluster":
    need_nonnegative(strict=False)
    K = 3
    n_sv = 1 + int(np.ceil(np.log2(K))) if K > 1 else 1
    if K < 2 or n_sv > min(n, p) or K > n:
        cs.cs_error("CS_E_INVALID_OPTION", option="Biclusters", allowed=f"between 2 and {min(n, 2 ** (min(n, p) - 1))} for this table", value=K)
    A = X
    rl, cl = cb.cocluster(A, K, rng, 10)
    biclusters = [(rl == b, cl == b) for b in range(K)]
else:
    METHOD = "bistochastic"
    need_nonnegative(strict=(METHOD == "log"))
    NR, NC = 2, 2
    NCOMP, NBEST = 6, 3
    if NCOMP > min(n, p):
        cs.cs_error("CS_E_INVALID_OPTION", option="Singular vectors", allowed=f"at most {min(n, p)} for this table", value=NCOMP)
    usable = NCOMP - (0 if METHOD == "log" else 1)
    if NBEST > usable:
        cs.cs_error("CS_E_INVALID_OPTION", option="Vectors kept", allowed=f"at most {usable} with {NCOMP} singular vectors", value=NBEST)
    if NR > n or NC > p:
        cs.cs_error("CS_E_INVALID_OPTION", option="Row groups" if NR > n else "Column groups", allowed=f"at most {n if NR > n else p}", value=NR if NR > n else NC)
    A = X
    rl, cl, iterations = cb.checkerboard(A, NR, NC, METHOD, NCOMP, NBEST, rng, 10)
    biclusters = [(rl == r, cl == c) for r in range(NR) for c in range(NC)]

# %% Summaries
k = len(biclusters)
summ = cb.summarize(A, biclusters)
values = {
    "n": n, "p": p, "k": k, "delta": delta, "iterations": iterations,
    "membership_check": cb.membership_checksum(biclusters, n, p),
}
covered_rows = np.zeros(n, dtype=bool)
covered_cells = np.zeros((n, p), dtype=bool)
for I, J in biclusters:
    covered_rows |= I
    covered_cells[np.ix_(I, J)] = True
values["rows_covered"] = float(np.mean(covered_rows))
values["cells_covered"] = float(np.mean(covered_cells))
msrs = [s["msr"] for s in summ if s["msr"] == s["msr"]]
values["msr_mean"] = float(np.mean(msrs)) if msrs else None
for b, s in enumerate(summ, start=1):
    values[f"n_rows[{b}]"] = s["n_rows"]
    values[f"n_cols[{b}]"] = s["n_cols"]
    values[f"msr[{b}]"] = s["msr"]
    values[f"mean[{b}]"] = s["mean"]
tables = [{
    "key": "biclusters",
    "title": "Biclusters",
    "columns": [
        {"key": "bicluster", "label": "Bicluster", "type": "integer"},
        {"key": "rows", "label": "Rows", "type": "integer"},
        {"key": "cols", "label": "Columns", "type": "integer"},
        {"key": "columns", "label": "Which columns", "type": "string"},
        {"key": "msr", "label": "Mean squared residue", "type": "number"},
        {"key": "mean", "label": "Mean value", "type": "number"},
    ],
    "rows": [
        {"bicluster": b, "rows": s["n_rows"], "cols": s["n_cols"],
         "columns": ", ".join([FEATURES[j] for j in np.flatnonzero(J)][:12]) + (" …" if int(J.sum()) > 12 else ""),
         "msr": s["msr"], "mean": s["mean"]}
        for b, ((I, J), s) in enumerate(zip(biclusters, summ), start=1)
    ],
}]

# %% Artifacts: labels.parquet (row, first bicluster, one flag per bicluster) and biclusters.json
first = np.full(n, -1, dtype=np.int64)
flags = {}
for b, (I, J) in enumerate(biclusters, start=1):
    first[(first == -1) & I] = b
    flags[f"in_{b}"] = I.copy()
path = csc.write_labels(out, rows, first, **flags)
bpath = os.path.join(out, "biclusters.json")
with open(bpath, "w", encoding="utf-8") as fh:
    json.dump({"k": k, "rows": [[int(rows[i]) for i in np.flatnonzero(I)] for I, _ in biclusters],
               "cols": [[FEATURES[j] for j in np.flatnonzero(J)] for _, J in biclusters]}, fh)

# %% Heatmap
charts = []
if p <= 120 and k > 0:
    show = np.arange(n) if n <= 400 else np.flatnonzero(covered_rows)[csc.even_sample(int(covered_rows.sum()), 400)]
    if ROW_ID:
        names = cc.label_text(df[ROW_ID].iloc[rows].tolist())
        names = np.array(["" if v is None else v for v in names], dtype=object)
        if len(set(names.tolist())) < n:
            names = np.array([f"{v} #{i + 1}" for i, v in enumerate(names)], dtype=object)
    else:
        names = np.array([f"row {int(r) + 1}" for r in rows], dtype=object)
    cell_b = np.full((n, p), -1, dtype=np.int64)
    for b, (I, J) in enumerate(biclusters, start=1):
        sub = np.ix_(I, J)
        blk = cell_b[sub]
        blk[blk == -1] = b
        cell_b[sub] = blk
    rr = [int(i) for i in show for _ in range(p)]
    jj = [j for _ in show for j in range(p)]
    charts.append(cs.chart(
        "heatmap", "bicluster-heatmap", "Biclusters in the table",
        {
            "row": cs.col("Row", [names[i] for i in rr], "categorical", levels=[names[i] for i in show]),
            "column": cs.col("Column", [FEATURES[j] for j in jj], "categorical", levels=FEATURES),
            "value": cs.col("Value (standardized)" if ALGORITHM == "cheng_church" and "standard" == "standard" else "Value",
                            [float(A[i, j]) for i, j in zip(rr, jj)], "numeric"),
            "bicluster": cs.col("Bicluster", [str(cell_b[i, j]) for i, j in zip(rr, jj)], "categorical",
                                levels=[str(b) for b in range(1, k + 1)] + ["-1"]) if k <= 29 else None,
        },
        note=None if len(show) == n else f"{len(show):,} of {n:,} rows shown (rows in a bicluster, evenly sampled).",
    ))

# %% Result
cs.publish({
    "title": "Biclustering (rows × columns)",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": (f"{k} bicluster{'s' if k != 1 else ''} in {n:,} rows × {p} columns covering {values['rows_covered'] * 100:.0f}% of the rows"
                + (f"; mean squared residue {values['msr_mean']:.3g}." if values["msr_mean"] is not None else ".")),
    "statistics": [
        {"key": "k", "label": "Biclusters", "value": k, "format": "integer"},
        {"key": "rows_covered", "label": "Rows covered", "value": values["rows_covered"], "format": "percent"},
        {"key": "msr_mean", "label": "Mean squared residue", "value": values["msr_mean"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}, {"key": "biclusters", "path": bpath, "format": "json"}],
    "model": {"kind": "bicluster", "features": FEATURES, "params": {
        "algorithm": "checkerboard",
        "k": 3,
        "delta_share": 0.02,
        "alpha": 1.2,
        "scale": "standard",
        "n_row_clusters": 2,
        "n_col_clusters": 2,
        "normalize": "bistochastic",
        "n_components": 6,
        "n_best": 3,
        "n_init": 10,
    }},
})
06

Check your understanding

Checkpoint

Check yourself

A set of patients share a pattern on five lab tests but differ on the other forty. Why might k-means on all 45 tests miss them?

Show the answer

Answer: b

Whole-row clustering uses every column. A bicluster looks for rows that agree on a subset of columns, which is exactly this case.

Check yourself

A block's mean squared residue is 0. What does that mean?

Show the answer

Answer: b

Constant blocks also have residue 0, but so do blocks where rows differ by a constant shift. The residue measures additive coherence, not equality.

Check yourself

You have word counts for 2,000 documents and want groups of documents together with the words that mark them. Which method fits?

Show the answer

Answer: b

Co-clustering puts each document and each word in one block of large counts. The log normalization needs every value to be positive, and counts have zeros.

Concepts in this lesson