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.
What runs in CodeSplash
- Biclustering (rows × columns) Verified in Python and R
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
When rows only agree on some columns
Readk-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.
Coherence: the mean squared residue
ReadCheng–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.
Shrink, then grow
ReadThe 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.
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
View data
| Bicluster | Column | Row | Value (standardized) |
|---|---|---|---|
| -1 | x1 | r01 | 1.166 |
| -1 | x2 | r01 | −0.1202 |
| -1 | x3 | r01 | 0.2679 |
| -1 | x4 | r01 | 0.6042 |
| -1 | x5 | r01 | −0.9826 |
| -1 | x6 | r01 | 0.0277 |
| -1 | x7 | r01 | 0.4645 |
| -1 | x8 | r01 | −0.0677 |
| -1 | x9 | r01 | 2.850 |
| -1 | x10 | r01 | 0.2368 |
| -1 | x11 | r01 | −0.4948 |
| -1 | x12 | r01 | −0.1775 |
| -1 | x1 | r02 | 0.0436 |
| -1 | x2 | r02 | −1.401 |
| -1 | x3 | r02 | −0.6471 |
| -1 | x4 | r02 | −0.3771 |
| -1 | x5 | r02 | 0.8307 |
| -1 | x6 | r02 | −0.0856 |
| -1 | x7 | r02 | 0.6873 |
| -1 | x8 | r02 | 1.283 |
| -1 | x9 | r02 | 0.9333 |
| -1 | x10 | r02 | −1.728 |
| -1 | x11 | r02 | −0.5257 |
| -1 | x12 | r02 | −1.081 |
| 2 | x1 | r03 | 0.8580 |
| 2 | x2 | r03 | −0.5201 |
| 2 | x3 | r03 | 0.0291 |
| 2 | x4 | r03 | 0.3487 |
| 2 | x5 | r03 | 0.0055 |
| -1 | x6 | r03 | −0.5167 |
| -1 | x7 | r03 | −1.908 |
| -1 | x8 | r03 | −0.4464 |
| -1 | x9 | r03 | 1.701 |
| -1 | x10 | r03 | 0.1065 |
| -1 | x11 | r03 | −0.3729 |
| -1 | x12 | r03 | 1.107 |
| 2 | x1 | r04 | 1.781 |
| 2 | x2 | r04 | 0.4723 |
| 2 | x3 | r04 | 0.8519 |
| 2 | x4 | r04 | 1.131 |
| 2 | x5 | r04 | 1.343 |
| -1 | x6 | r04 | 1.051 |
| -1 | x7 | r04 | 0.7797 |
| -1 | x8 | r04 | −0.9918 |
| -1 | x9 | r04 | 0.0180 |
| -1 | x10 | r04 | 1.769 |
| -1 | x11 | r04 | −0.1224 |
| -1 | x12 | r04 | 0.1363 |
| -1 | x1 | r05 | 1.355 |
| -1 | x2 | r05 | −0.0224 |
| -1 | x3 | r05 | 0.4606 |
| -1 | x4 | r05 | 0.7913 |
| -1 | x5 | r05 | 1.000 |
| -1 | x6 | r05 | −1.513 |
| -1 | x7 | r05 | −1.417 |
| -1 | x8 | r05 | −1.134 |
| -1 | x9 | r05 | 0.6560 |
| -1 | x10 | r05 | 2.149 |
| -1 | x11 | r05 | 0.8723 |
| -1 | x12 | r05 | −0.1323 |
First 60 of 720 rows.
Biclusters
| Bicluster | Rows | Columns | Which columns | Mean squared residue | Mean value |
|---|---|---|---|---|---|
| 1 | 10 | 4 | x7, x8, x9, x10 | 0.0027 | −0.3418 |
| 2 | 8 | 5 | x1, x2, x3, x4, x5 | 0.0112 | 0.0863 |
| 3 | 4 | 4 | x4, x6, x9, x11 | 0.0138 | 0.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
))
))
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
| Bicluster | Rows | Columns | Which columns | Mean squared residue | Mean value |
|---|---|---|---|---|---|
| 1 | 10 | 4 | x7, x8, x9, x10 | 0.0027 | −0.3418 |
| 2 | 8 | 5 | x1, x2, x3, x4, x5 | 0.0112 | 0.0863 |
| 3 | 4 | 4 | x4, x6, x9, x11 | 0.0138 | 0.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,
}},
})
View data
| gene | sample | expression (log scale) | bicluster |
|---|---|---|---|
| gene 01 | sample 01 | 0.8330 | -1 |
| gene 01 | sample 02 | −1.025 | -1 |
| gene 01 | sample 03 | 0.4180 | -1 |
| gene 01 | sample 04 | 1.147 | -1 |
| gene 01 | sample 05 | −0.4030 | -1 |
| gene 01 | sample 06 | 1.160 | -1 |
| gene 01 | sample 07 | 0.9440 | -1 |
| gene 01 | sample 08 | −0.7910 | -1 |
| gene 01 | sample 09 | −1.156 | -1 |
| gene 01 | sample 10 | 0.1760 | -1 |
| gene 01 | sample 11 | 1.090 | -1 |
| gene 01 | sample 12 | 1.399 | -1 |
| gene 01 | sample 13 | −0.7610 | -1 |
| gene 01 | sample 14 | −0.3570 | -1 |
| gene 02 | sample 01 | 4.570 | 1 |
| gene 02 | sample 02 | 0.2720 | -1 |
| gene 02 | sample 03 | 0.1030 | -1 |
| gene 02 | sample 04 | 3.481 | 1 |
| gene 02 | sample 05 | 0.5420 | -1 |
| gene 02 | sample 06 | 0.8290 | -1 |
| gene 02 | sample 07 | 4.280 | 1 |
| gene 02 | sample 08 | 0.1560 | -1 |
| gene 02 | sample 09 | 0.8460 | -1 |
| gene 02 | sample 10 | 2.722 | 1 |
| gene 02 | sample 11 | 0.0230 | -1 |
| gene 02 | sample 12 | −0.2100 | -1 |
| gene 02 | sample 13 | 2.584 | 1 |
| gene 02 | sample 14 | 0.0170 | -1 |
| gene 03 | sample 01 | −0.2430 | -1 |
| gene 03 | sample 02 | −0.2460 | -1 |
| gene 03 | sample 03 | −0.4660 | -1 |
| gene 03 | sample 04 | −0.6590 | -1 |
| gene 03 | sample 05 | 1.155 | -1 |
| gene 03 | sample 06 | 0.4950 | -1 |
| gene 03 | sample 07 | −0.3270 | -1 |
| gene 03 | sample 08 | 0.0700 | -1 |
| gene 03 | sample 09 | −0.3500 | -1 |
| gene 03 | sample 10 | −1.105 | -1 |
| gene 03 | sample 11 | 1.886 | -1 |
| gene 03 | sample 12 | −0.9110 | -1 |
| gene 03 | sample 13 | −1.615 | -1 |
| gene 03 | sample 14 | 0.1000 | -1 |
| gene 04 | sample 01 | 0.0090 | -1 |
| gene 04 | sample 02 | −2.186 | 2 |
| gene 04 | sample 03 | 0.1620 | -1 |
| gene 04 | sample 04 | −0.4650 | -1 |
| gene 04 | sample 05 | −1.706 | 2 |
| gene 04 | sample 06 | −0.3010 | -1 |
| gene 04 | sample 07 | −0.0390 | -1 |
| gene 04 | sample 08 | −1.990 | 2 |
| gene 04 | sample 09 | 1.293 | -1 |
| gene 04 | sample 10 | 0.3880 | -1 |
| gene 04 | sample 11 | −4.118 | 2 |
| gene 04 | sample 12 | −0.1250 | -1 |
| gene 04 | sample 13 | 0.8840 | -1 |
| gene 04 | sample 14 | −2.581 | 2 |
| gene 05 | sample 01 | 0.2000 | -1 |
| gene 05 | sample 02 | 1.892 | -1 |
| gene 05 | sample 03 | 0.6110 | -1 |
| gene 05 | sample 04 | 0.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.
Blocks of large values: spectral co-clustering
ReadCounts 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.
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
View data
| Bicluster | Column | Row | Value |
|---|---|---|---|
| 1 | w1 | r01 | 9.570 |
| 1 | w2 | r01 | 11.898 |
| 1 | w3 | r01 | 8.122 |
| -1 | w4 | r01 | 0.2424 |
| -1 | w5 | r01 | 0.6986 |
| -1 | w6 | r01 | 0.8396 |
| -1 | w7 | r01 | 0.5654 |
| -1 | w8 | r01 | 0.7511 |
| -1 | w9 | r01 | 0.4712 |
| 1 | w1 | r02 | 11.719 |
| 1 | w2 | r02 | 11.150 |
| 1 | w3 | r02 | 11.123 |
| -1 | w4 | r02 | 0.2408 |
| -1 | w5 | r02 | 0.8105 |
| -1 | w6 | r02 | 0.4153 |
| -1 | w7 | r02 | 0.8588 |
| -1 | w8 | r02 | 0.6674 |
| -1 | w9 | r02 | 0.4725 |
| 1 | w1 | r03 | 10.277 |
| 1 | w2 | r03 | 11.542 |
| 1 | w3 | r03 | 10.511 |
| -1 | w4 | r03 | 0.8614 |
| -1 | w5 | r03 | 0.4387 |
| -1 | w6 | r03 | 0.4035 |
| -1 | w7 | r03 | 0.7155 |
| -1 | w8 | r03 | 0.3125 |
| -1 | w9 | r03 | 0.6034 |
| 1 | w1 | r04 | 9.755 |
| 1 | w2 | r04 | 10.772 |
| 1 | w3 | r04 | 9.594 |
| -1 | w4 | r04 | 0.3186 |
| -1 | w5 | r04 | 0.5174 |
| -1 | w6 | r04 | 0.2591 |
| -1 | w7 | r04 | 0.2653 |
| -1 | w8 | r04 | 0.1000 |
| -1 | w9 | r04 | 0.2405 |
| 1 | w1 | r05 | 11.118 |
| 1 | w2 | r05 | 11.377 |
| 1 | w3 | r05 | 8.737 |
| -1 | w4 | r05 | 0.0714 |
| -1 | w5 | r05 | 0.3758 |
| -1 | w6 | r05 | 0.0486 |
| -1 | w7 | r05 | 0.3771 |
| -1 | w8 | r05 | 0.5283 |
| -1 | w9 | r05 | 0.0044 |
| 1 | w1 | r06 | 11.662 |
| 1 | w2 | r06 | 10.468 |
| 1 | w3 | r06 | 9.867 |
| -1 | w4 | r06 | 0.7775 |
| -1 | w5 | r06 | 0.8947 |
| -1 | w6 | r06 | 0.3795 |
| -1 | w7 | r06 | 0.8201 |
| -1 | w8 | r06 | 0.6985 |
| -1 | w9 | r06 | 0.1334 |
| 1 | w1 | r07 | 11.408 |
| 1 | w2 | r07 | 10.928 |
| 1 | w3 | r07 | 9.814 |
| -1 | w4 | r07 | 0.0852 |
| -1 | w5 | r07 | 0.6383 |
| -1 | w6 | r07 | 0.1997 |
First 60 of 405 rows.
Biclusters
| Bicluster | Rows | Columns | Which columns | Mean squared residue | Mean value |
|---|---|---|---|---|---|
| 1 | 15 | 3 | w1, w2, w3 | 0.5361 | 10.443 |
| 2 | 15 | 3 | w4, w5, w6 | 1.041 | 10.118 |
| 3 | 15 | 3 | w7, w8, w9 | 0.9168 | 9.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
))
))
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
| Bicluster | Rows | Columns | Which columns | Mean squared residue | Mean value |
|---|---|---|---|---|---|
| 1 | 15 | 3 | w1, w2, w3 | 0.5361 | 10.443 |
| 2 | 15 | 3 | w4, w5, w6 | 1.041 | 10.118 |
| 3 | 15 | 3 | w7, w8, w9 | 0.9168 | 9.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,
}},
})
Row groups × column groups: the checkerboard
ReadSometimes 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.
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
View data
| Bicluster | Column | Row | Value |
|---|---|---|---|
| 1 | v1 | row 1 | 11.977 |
| 1 | v2 | row 1 | 17.666 |
| 1 | v3 | row 1 | 10.238 |
| 1 | v4 | row 1 | 20.097 |
| 2 | v5 | row 1 | 1.477 |
| 2 | v6 | row 1 | 2.760 |
| 2 | v7 | row 1 | 3.376 |
| 2 | v8 | row 1 | 2.105 |
| 1 | v1 | row 2 | 10.039 |
| 1 | v2 | row 2 | 15.610 |
| 1 | v3 | row 2 | 9.316 |
| 1 | v4 | row 2 | 16.079 |
| 2 | v5 | row 2 | 1.358 |
| 2 | v6 | row 2 | 2.305 |
| 2 | v7 | row 2 | 3.147 |
| 2 | v8 | row 2 | 1.693 |
| 1 | v1 | row 3 | 11.159 |
| 1 | v2 | row 3 | 16.173 |
| 1 | v3 | row 3 | 9.284 |
| 1 | v4 | row 3 | 18.923 |
| 2 | v5 | row 3 | 1.330 |
| 2 | v6 | row 3 | 2.411 |
| 2 | v7 | row 3 | 3.527 |
| 2 | v8 | row 3 | 1.847 |
| 1 | v1 | row 4 | 10.578 |
| 1 | v2 | row 4 | 16.248 |
| 1 | v3 | row 4 | 8.815 |
| 1 | v4 | row 4 | 16.851 |
| 2 | v5 | row 4 | 1.343 |
| 2 | v6 | row 4 | 2.334 |
| 2 | v7 | row 4 | 2.830 |
| 2 | v8 | row 4 | 1.717 |
| 1 | v1 | row 5 | 4.510 |
| 1 | v2 | row 5 | 7.518 |
| 1 | v3 | row 5 | 4.484 |
| 1 | v4 | row 5 | 7.968 |
| 2 | v5 | row 5 | 0.6367 |
| 2 | v6 | row 5 | 1.093 |
| 2 | v7 | row 5 | 1.568 |
| 2 | v8 | row 5 | 0.8548 |
| 1 | v1 | row 6 | 11.199 |
| 1 | v2 | row 6 | 17.397 |
| 1 | v3 | row 6 | 9.725 |
| 1 | v4 | row 6 | 17.329 |
| 2 | v5 | row 6 | 1.408 |
| 2 | v6 | row 6 | 2.374 |
| 2 | v7 | row 6 | 3.361 |
| 2 | v8 | row 6 | 2.125 |
| 1 | v1 | row 7 | 7.186 |
| 1 | v2 | row 7 | 11.353 |
| 1 | v3 | row 7 | 6.999 |
| 1 | v4 | row 7 | 11.277 |
| 2 | v5 | row 7 | 1.007 |
| 2 | v6 | row 7 | 1.782 |
| 2 | v7 | row 7 | 2.217 |
| 2 | v8 | row 7 | 1.203 |
| 1 | v1 | row 8 | 12.093 |
| 1 | v2 | row 8 | 18.963 |
| 1 | v3 | row 8 | 11.068 |
| 1 | v4 | row 8 | 18.971 |
First 60 of 320 rows.
Biclusters
| Bicluster | Rows | Columns | Which columns | Mean squared residue | Mean value |
|---|---|---|---|---|---|
| 1 | 20 | 4 | v1, v2, v3, v4 | 1.012 | 12.136 |
| 2 | 20 | 4 | v5, v6, v7, v8 | 0.0368 | 2.008 |
| 3 | 20 | 4 | v1, v2, v3, v4 | 0.0819 | 3.445 |
| 4 | 20 | 4 | v5, v6, v7, v8 | 0.4306 | 6.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
))
))
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
| Bicluster | Rows | Columns | Which columns | Mean squared residue | Mean value |
|---|---|---|---|---|---|
| 1 | 20 | 4 | v1, v2, v3, v4 | 1.012 | 12.136 |
| 2 | 20 | 4 | v5, v6, v7, v8 | 0.0368 | 2.008 |
| 3 | 20 | 4 | v1, v2, v3, v4 | 0.0819 | 3.445 |
| 4 | 20 | 4 | v5, v6, v7, v8 | 0.4306 | 6.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,
}},
})
Check your understanding
CheckpointCheck 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