Point clouds: PointNet, PointNet++ and DGCNN
A point cloud is a set of coordinates. PointNet pools shared point features with a max; PointNet++ pools within local neighborhoods; DGCNN links each point to its nearest neighbors and rebuilds those links as features change.
What runs in CodeSplash
- SPE007PointNet Partly runs in CodeSplash (Experimental)
- SPE008PointNet++ Needs a data type CodeSplash doesn't load yet
- SPE009Dynamic Graph CNN (DGCNN) Needs a data type CodeSplash doesn't load yet
- Set model (Deep Sets, Set Transformer) Experimental
You will be able to
- Compute PointNet's global feature and say why max pooling is order-free
- Explain how radius grouping gives PointNet++ local structure
- Build one EdgeConv update from nearest neighbors
- Say why order-free doesn't mean rotation-free, and what that implies for testing
Read first
Points with no grid
ReadA point cloudPoint cloudA set of points with coordinates (and maybe features) and no order or grid, such as a 3D scan of an object. is a set of points, each with coordinates and maybe a color or intensity: a laser scan of a room, the atoms of a protein, the hits in a particle detector. There is no grid to convolve over and no order, and the number of points varies.
Turning it into voxels throws away detail and wastes memory on empty space. The networks here read the points directly, as a set.
PointNet: shared features, max pooling
ReadPointNetPointNetA point-cloud network that applies the same small network to every point, then keeps each feature's maximum over points. applies one small network to every point, then keeps each feature's maximum over all points:
The maximum ignores order, like a sum. The reference's three points give the global feature (0.65, 0.40) in any order. Each feature is set by one "critical" point, so a few outlying points can move it.
The full PointNet adds a learned alignment network and a segmentation head that joins each point's own feature with the global one.
Reference · SPE007 · Partly runs in CodeSplashPointNetPointNet directly processes unordered three-dimensional points for classification and segmentation, avoiding voxelization. Shared pointwise features and a symmetric max operation create a global representation;Max pooling in a set model
ExploreSet model (Deep Sets, Set Transformer): cross-validated RMSE 64.949 ± 5.037 over 3 folds; RMSE on the locked test set 44.674 (n = 122).
- CV RMSE
- 64.949
- SD across folds
- 5.037
- Test RMSE
- 44.674
Plots
View data
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| Set model | 1 | 0.9949 | 1.001 |
| Set model | 2 | 0.9854 | 0.9959 |
| Set model | 3 | 0.9817 | 0.9918 |
| Set model | 4 | 0.9858 | 0.9879 |
| Set model | 5 | 0.9747 | 0.9841 |
| Set model | 6 | 0.9706 | 0.9800 |
| Set model | 7 | 0.9630 | 0.9751 |
| Set model | 8 | 0.9619 | 0.9697 |
| Set model | 9 | 0.9553 | 0.9639 |
| Set model | 10 | 0.9492 | 0.9575 |
| Set model | 11 | 0.9406 | 0.9508 |
| Set model | 12 | 0.9277 | 0.9431 |
| Set model | 13 | 0.9254 | 0.9346 |
| Set model | 14 | 0.9194 | 0.9250 |
| Set model | 15 | 0.9088 | 0.9141 |
| Set model | 16 | 0.8986 | 0.9022 |
| Set model | 17 | 0.8797 | 0.8883 |
| Set model | 18 | 0.8738 | 0.8718 |
| Set model | 19 | 0.8549 | 0.8526 |
| Set model | 20 | 0.8244 | 0.8313 |
| Set model | 21 | 0.8187 | 0.8083 |
| Set model | 22 | 0.7903 | 0.7844 |
| Set model | 23 | 0.7641 | 0.7608 |
| Set model | 24 | 0.7475 | 0.7352 |
| Set model | 25 | 0.7180 | 0.7089 |
| Set model | 26 | 0.6922 | 0.6800 |
| Set model | 27 | 0.6764 | 0.6522 |
| Set model | 28 | 0.6465 | 0.6245 |
| Set model | 29 | 0.6144 | 0.5952 |
| Set model | 30 | 0.5812 | 0.5653 |
Cross-validation
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 152 | 64.251 | 55.268 | 0.1938 | 0.6744 |
| 2 | 1 | 151 | 60.298 | 52.166 | 0.2676 | 0.6407 |
| 3 | 1 | 153 | 70.299 | 55.225 | 0.2428 | 0.6078 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| Set model | 1 | 0.9949 | 1.001 |
| Set model | 2 | 0.9854 | 0.9959 |
| Set model | 3 | 0.9817 | 0.9918 |
| Set model | 4 | 0.9858 | 0.9879 |
| Set model | 5 | 0.9747 | 0.9841 |
| Set model | 6 | 0.9706 | 0.9800 |
| Set model | 7 | 0.9630 | 0.9751 |
| Set model | 8 | 0.9619 | 0.9697 |
| Set model | 9 | 0.9553 | 0.9639 |
| Set model | 10 | 0.9492 | 0.9575 |
| Set model | 11 | 0.9406 | 0.9508 |
| Set model | 12 | 0.9277 | 0.9431 |
| Set model | 13 | 0.9254 | 0.9346 |
| Set model | 14 | 0.9194 | 0.9250 |
| Set model | 15 | 0.9088 | 0.9141 |
| Set model | 16 | 0.8986 | 0.9022 |
| Set model | 17 | 0.8797 | 0.8883 |
| Set model | 18 | 0.8738 | 0.8718 |
| Set model | 19 | 0.8549 | 0.8526 |
| Set model | 20 | 0.8244 | 0.8313 |
| Set model | 21 | 0.8187 | 0.8083 |
| Set model | 22 | 0.7903 | 0.7844 |
| Set model | 23 | 0.7641 | 0.7608 |
| Set model | 24 | 0.7475 | 0.7352 |
| Set model | 25 | 0.7180 | 0.7089 |
| Set model | 26 | 0.6922 | 0.6800 |
| Set model | 27 | 0.6764 | 0.6522 |
| Set model | 28 | 0.6465 | 0.6245 |
| Set model | 29 | 0.6144 | 0.5952 |
| Set model | 30 | 0.5812 | 0.5653 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Set model (Deep Sets, Set Transformer)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.set_model 1.1.1 · spec 8965ad271557d639
# Dataset: ml_chickweight (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# torch for R (LibTorch); the network is built by codesplashr's cs_deep_fit_set_model twin.
# %% Data and split plan
TARGET <- "weight"
FEATURES <- c("Time", "Diet")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
level = "element",
set_scores = FALSE,
encoder = "mlp",
pooling = "max",
width = 8,
enc_layers = 2,
n_blocks = 1,
n_heads = 4,
inducing_points = 0,
dec_layers = 1,
dropout = 0.1,
epochs = 30,
learning_rate = 0.001,
batch_size = 8,
weight_decay = 0,
early_stopping = 8,
validation_fraction = 0.2,
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_chickweight.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.set_model/regression_chicks_element_max/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
Time = "numeric",
Diet = "categorical"
),
levels = list(
Diet = c("1", "2", "3", "4")
),
impute = "median",
scale = "standard",
indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
out <- cs_ml_out_dir("target/academy-parity/run-8142/learn.set_model/regression_chicks_element_max/out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
yy <- y[rows + 1L]
ww <- sample_weights(rows)
if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
if (fold_id == 0) resampled <<- r$info
r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)
# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/learn.set_model/regression_chicks_element_max/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
.deep_training_set(X, rows, fold_id, repeat_)
}
# A set model on torch for R (float64, one thread): rows that share a set id form a set; an encoder reads
# every row, a permutation-invariant pooling summarizes the set, and a decoder predicts for the set (or for
# each row next to its set's summary). Initial weights, batches of sets, dropout masks and early-stopping
# sets come from the shared random stream, so Python's torch trains the same network.
SET_ID <- "Chick" # the Set id role (rows of one set also stay in one fold)
# Each input row's set id, or NULL when the input has no set column (e.g. scoring data without it).
read_set_ids <- function() {
if (is.null(SET_ID)) return(NULL)
values <- tryCatch(nanoparquet::read_parquet("tests/parity/fixtures/ml_chickweight.parquet", col_select = SET_ID)[[SET_ID]], error = function(e) NULL)
if (is.null(values)) return(NULL)
missing <- sum(is.na(values))
if (missing > 0L) cs_error("CS_E_INVALID_VALUES", column = SET_ID, requirement = "present on every row (it names each row's set)", count = missing)
if (is.factor(values)) as.character(values) else values
}
SET_VALUES <- read_set_ids()
# Each design matrix the driver makes knows its rows' set ids (attribute cs_sets; rows come from the input's
# row names).
.cs_set_design_apply <- cs_ml_design_apply
cs_ml_design_apply <- function(prep, frame) {
X <- .cs_set_design_apply(prep, frame)
if (!is.null(SET_VALUES)) attr(X, "cs_sets") <- SET_VALUES[as.integer(rownames(frame))]
X
}
sets_of <- function(X, fallback = NULL) {
s <- attr(X, "cs_sets")
if (!is.null(s) && length(s) == nrow(X)) return(s)
if (!is.null(fallback) && length(fallback) == nrow(X)) return(fallback)
NULL
}
fit_model <- function(X, y, w) {
sets <- sets_of(X)
if (is.null(sets)) cs_error("CS_E_INVALID_OPTION", option = "Resampling", allowed = "none for set models (rows belong to sets)", value = "on")
if (TASK == "regression") {
# Standardize the target (training mean and population SD); predictions are mapped back.
mu <- mean(y); sd <- sqrt(mean((y - mu)^2)); if (!(sd > 0)) sd <- 1
target <- (as.numeric(y) - mu) / sd; o <- 1L
} else if (TASK == "binary") {
mu <- 0; sd <- 1
target <- as.numeric(y); o <- 1L
} else {
mu <- 0; sd <- 1
target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
}
fit <- cs_deep_fit_set_model(
unname(as.matrix(X)), sets, target, w, TASK, o,
target_name = TARGET,
width = as.integer(PARAMS$width),
encoder = PARAMS$encoder,
enc_layers = as.integer(PARAMS$enc_layers),
n_blocks = as.integer(PARAMS$n_blocks),
n_heads = as.integer(PARAMS$n_heads),
inducing_points = as.integer(PARAMS$inducing_points),
pooling = PARAMS$pooling,
level = PARAMS$level,
dec_layers = as.integer(PARAMS$dec_layers),
dropout = PARAMS$dropout,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = PARAMS$weight_decay,
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = PARAMS$validation_fraction,
patience = max(1L, as.integer(PARAMS$early_stopping)),
seed = SEED
)
fit$mu <- mu
fit$sd <- sd
# A set model must not depend on the order of a set's rows: predictions with each set reversed.
fit$invariance_gap <- cs_deep_set_invariance_gap(fit, unname(as.matrix(X)), sets, TASK)
fit
}
predict_model <- function(model, X) {
sets <- sets_of(X, SET_VALUES)
if (is.null(sets)) {
cs_error("CS_E_INVALID_VALUES", column = if (is.null(SET_ID)) "Set id" else SET_ID,
requirement = "in the data (a set model predicts whole sets)", count = nrow(X))
}
p <- cs_deep_set_predict(model, unname(as.matrix(X)), sets, TASK)
if (TASK == "regression") model$mu + model$sd * p else p
}
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # plain numeric weights, the architecture and the target scaling
hist <- file.path(directory, "history.parquet")
nanoparquet::write_parquet(cs_deep_history_frame(model$history), hist)
list(list(key = "model", path = path, format = "rds"), list(key = "history", path = hist, format = "parquet"))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
fold <- folds[[i]]
prep <- cs_ml_design_fit(design, rows_of(fold$train))
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")
# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
if (!is.null(resampled)) {
warnings <- c(warnings, as.list(resampled$notes))
notes <- c(notes, list(cs_ml_resample_describe(resampled)))
}
if (length(plan$test)) {
cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
}
importance <- feature_importance(model, names_)
artifacts[[length(artifacts) + 1L]] <- list(
key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
)
artifacts <- c(artifacts, save_model(model, out))
cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)
# %% Result
cs_publish(cs_deep_extend_set_model(cs_ml_result(
run,
title = "Set model (Deep Sets, Set Transformer)",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
n_features = length(names_),
n_train = length(plan$train),
n_test = length(plan$test),
params = PARAMS,
features = names_,
importance = importance,
artifacts = artifacts,
warnings = warnings,
notes = notes
), model, names_))
Set model (Deep Sets, Set Transformer): cross-validated RMSE 64.949 ± 5.037 over 3 folds; RMSE on the locked test set 44.674 (n = 122).
- CV RMSE
- 64.949
- SD across folds
- 5.037
- Test RMSE
- 44.674
To keep this page light, the plots are shown once, under the R tab.
Cross-validation
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 152 | 64.251 | 55.268 | 0.1938 | 0.6744 |
| 2 | 1 | 151 | 60.298 | 52.166 | 0.2676 | 0.6407 |
| 3 | 1 | 153 | 70.299 | 55.225 | 0.2428 | 0.6078 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| Set model | 1 | 0.9949 | 1.001 |
| Set model | 2 | 0.9854 | 0.9959 |
| Set model | 3 | 0.9817 | 0.9918 |
| Set model | 4 | 0.9858 | 0.9879 |
| Set model | 5 | 0.9747 | 0.9841 |
| Set model | 6 | 0.9706 | 0.9800 |
| Set model | 7 | 0.9630 | 0.9751 |
| Set model | 8 | 0.9619 | 0.9697 |
| Set model | 9 | 0.9553 | 0.9639 |
| Set model | 10 | 0.9492 | 0.9575 |
| Set model | 11 | 0.9406 | 0.9508 |
| Set model | 12 | 0.9277 | 0.9431 |
| Set model | 13 | 0.9254 | 0.9346 |
| Set model | 14 | 0.9194 | 0.9250 |
| Set model | 15 | 0.9088 | 0.9141 |
| Set model | 16 | 0.8986 | 0.9022 |
| Set model | 17 | 0.8797 | 0.8883 |
| Set model | 18 | 0.8738 | 0.8718 |
| Set model | 19 | 0.8549 | 0.8526 |
| Set model | 20 | 0.8244 | 0.8313 |
| Set model | 21 | 0.8187 | 0.8083 |
| Set model | 22 | 0.7903 | 0.7844 |
| Set model | 23 | 0.7641 | 0.7608 |
| Set model | 24 | 0.7475 | 0.7352 |
| Set model | 25 | 0.7180 | 0.7089 |
| Set model | 26 | 0.6922 | 0.6800 |
| Set model | 27 | 0.6764 | 0.6522 |
| Set model | 28 | 0.6465 | 0.6245 |
| Set model | 29 | 0.6144 | 0.5952 |
| Set model | 30 | 0.5812 | 0.5653 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Set model (Deep Sets, Set Transformer)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.set_model 1.1.1 · spec 8965ad271557d639
# Dataset: ml_chickweight (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import core as deep
from codesplash.deep import sets as deepsets # twin of codesplashr::cs_deep_fit_set_model (shared weights, Adam written out)
# %% Data and split plan
TARGET = "weight"
FEATURES = ["Time", "Diet"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
"level": "element",
"set_scores": False,
"encoder": "mlp",
"pooling": "max",
"width": 8,
"enc_layers": 2,
"n_blocks": 1,
"n_heads": 4,
"inducing_points": 0,
"dec_layers": 1,
"dropout": 0.1,
"epochs": 30,
"learning_rate": 0.001,
"batch_size": 8,
"weight_decay": 0,
"early_stopping": 8,
"validation_fraction": 0.2,
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_chickweight.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.set_model/regression_chicks_element_max/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"Time": "numeric",
"Diet": "categorical",
},
levels={
"Diet": ["1", "2", "3", "4"],
},
impute="median",
scale="standard",
indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("target/academy-parity/run-8142/learn.set_model/regression_chicks_element_max/out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None # the final model's resampling summary
notes = []
def training_set(X, rows, fold_id, repeat):
"""A fit's design matrix, targets and weights: training rows only, resampled when asked
(codesplash.ml.resample — the same rows in R, from the shared random stream)."""
yy, ww = y[rows], sample_weights(rows)
if RESAMPLE == "none" or TASK == "regression":
return X, yy, ww
from codesplash.ml import resample as csres
X2, y2, w2, info = csres.resample(
X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
)
if fold_id == 0:
global resampled
resampled = info
return X2, y2, w2
# %% Model
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-8142/learn.set_model/regression_chicks_element_max/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set
def training_set(X, rows, fold_id, repeat):
"""Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
the training set as _ml_learn does."""
deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
return _deep_training_set(X, rows, fold_id, repeat)
# A set model on PyTorch (float64, one thread): rows that share a set id form a set; an encoder reads every
# row, a permutation-invariant pooling summarizes the set, and a decoder predicts for the set (or for each
# row next to its set's summary). Initial weights, batches of sets, dropout masks and early-stopping sets
# come from the shared random stream, so R's torch trains the same network.
SET_ID = "Chick" # the Set id role (rows of one set also stay in one fold)
def read_set_ids():
"""Each input row's set id, or None when the input has no set column (e.g. scoring data without it)."""
if SET_ID is None:
return None
try:
values = pd.read_parquet("tests/parity/fixtures/ml_chickweight.parquet", columns=[SET_ID])[SET_ID]
except Exception: # noqa: BLE001 — the column is not in this input
return None
missing = int(values.isna().sum())
if missing:
cs.cs_error("CS_E_INVALID_VALUES", column=SET_ID, requirement="present on every row (it names each row's set)", count=missing)
return values.to_numpy(dtype=object)
SET_VALUES = read_set_ids()
class SetDesign:
"""The driver's design; each design matrix it makes knows its rows' set ids (codesplash.deep.sets.SetRows)."""
def __init__(self, inner):
self._inner = inner
def fit(self, frame):
return SetPrep(self._inner.fit(frame))
def __getattr__(self, name):
return getattr(self._inner, name)
class SetPrep:
def __init__(self, inner):
self._inner = inner
def transform(self, frame):
return deepsets.with_sets(self._inner.transform(frame), SET_VALUES[frame.index.to_numpy()])
def __getattr__(self, name):
return getattr(self._inner, name)
design = SetDesign(design)
def fit_model(X, y, w):
sets = deepsets.sets_of(X)
if sets is None:
cs.cs_error("CS_E_INVALID_OPTION", option="Resampling", allowed="none for set models (rows belong to sets)", value="on")
if TASK == "regression":
# Standardize the target (training mean and population SD); predictions are mapped back.
mu, sd = float(np.mean(y)), float(np.std(y)) or 1.0
target, o = (np.asarray(y, dtype=np.float64) - mu) / sd, 1
elif TASK == "binary":
mu, sd = 0.0, 1.0
target, o = np.asarray(y, dtype=np.float64), 1
else:
mu, sd = 0.0, 1.0
target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
fit = deepsets.fit_set_model(
np.asarray(X), sets, target, w, TASK, o,
target_name=TARGET,
width=int(PARAMS["width"]),
encoder=PARAMS["encoder"],
enc_layers=int(PARAMS["enc_layers"]),
n_blocks=int(PARAMS["n_blocks"]),
n_heads=int(PARAMS["n_heads"]),
inducing_points=int(PARAMS["inducing_points"]),
pooling=PARAMS["pooling"],
level=PARAMS["level"],
dec_layers=int(PARAMS["dec_layers"]),
dropout=PARAMS["dropout"],
epochs=int(PARAMS["epochs"]),
lr=PARAMS["learning_rate"],
batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
weight_decay=PARAMS["weight_decay"],
early_stopping=int(PARAMS["early_stopping"]) > 0,
validation_fraction=PARAMS["validation_fraction"],
patience=max(1, int(PARAMS["early_stopping"])),
seed=SEED,
)
fit.update({"mu": mu, "sd": sd})
# A set model must not depend on the order of a set's rows: predictions with each set reversed.
fit["invariance_gap"] = deepsets.invariance_gap(fit, np.asarray(X), sets, TASK)
return fit
def predict_model(model, X):
sets = deepsets.sets_of(X, SET_VALUES)
if sets is None:
cs.cs_error("CS_E_INVALID_VALUES", column=SET_ID or "Set id", requirement="in the data (a set model predicts whole sets)", count=int(np.asarray(X).shape[0]))
p = deepsets.set_predict(model, np.asarray(X), sets, TASK)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
def feature_importance(model, names):
return None
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path) # plain numpy weights, the architecture and the target scaling
hist = os.path.join(directory, "history.parquet")
deep.history_frame(model["history"]).to_parquet(hist, index=False)
return [{"key": "model", "path": path, "format": "joblib"}, {"key": "history", "path": hist, "format": "parquet"}]
def load_model(directory):
import joblib
return joblib.load(os.path.join(directory, "model.joblib"))
# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
prep = design.fit(df.iloc[fold.train])
model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")
# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
if resampled is not None:
from codesplash.ml import resample as csres
warnings.extend(resampled["notes"])
notes.append(csres.describe(resampled))
if len(plan.test):
run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
importance = feature_importance(model, names)
artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
artifacts.extend(save_model(model, out))
run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()
# %% Result
cs.publish(
deepsets.extend_set_model(run.result(
title="Set model (Deep Sets, Set Transformer)",
engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
n_features=len(names),
n_train=len(plan.train),
n_test=len(plan.test),
params=PARAMS,
features=names,
importance=importance,
artifacts=artifacts,
warnings=warnings,
notes=notes,
), model, names)
)
learn.set_model with Pooling: Max is PointNet's pooling over any set of rows. Here each chick's weighings form a set, and each weight is predicted from its own row plus the set's max-pooled summary. The cross-validated R² is 0.23 and the invariance gap is 0.
For real point clouds you would feed x, y, z (and any per-point features) as the columns and the object id as the set.
PointNet++: local neighborhoods
ReadPointNet sees each point alone until the global max, so it misses local shape. PointNet++ adds set abstractionSet abstraction (PointNet++)PointNet++'s layer that picks centers, groups the points within a radius of each, and runs a small PointNet on each group.: pick centers, gather the points within radius of each, and run a small PointNet on their coordinates relative to the center:
Repeat on the centers to build a hierarchy. In the reference's example two centers pool their neighbors to (0.09, 0.10) and (0.03, 0.14). The radius sets what "local" means, so units and point density matter.
Reference · SPE008 · Needs a data type CodeSplash doesn't load yetPointNet++PointNet++ adds hierarchical local neighborhoods to point-set learning, allowing fine geometric patterns to be aggregated across scales. It addresses the limited local structure of a single global PointNet.DGCNN: neighbors that move
ReadEdgeConvEdgeConv (DGCNN)A point-cloud layer that links each point to its k nearest neighbors and pools features of the edges; DGCNN rebuilds the links per layer. links each point to its nearest neighbors and pools a shared function of the point and each neighbor's offset:
DGCNN recomputes the neighbors from the current features after every layer, so later layers link points that look alike, not only points that sit close. In the reference's one-layer example with , the first point's output is (0.500, 0.625), while the last point's edges all fall below zero and it outputs (0, 0).
Reference · SPE009 · Needs a data type CodeSplash doesn't load yetDynamic Graph CNN (DGCNN)DGCNN learns point-cloud features through EdgeConv and recomputes neighborhoods in learned feature space. Dynamic graphs let local relations change as representations become more semantic.Order-free is not rotation-free
PredictPredict first
You rotate a point cloud by 90° and feed it to PointNet. Its permutation invariance is exact. What happens to its global feature?
Reveal
It can change. Shuffling points leaves the max unchanged, but rotating them changes every coordinate that reads. Rotation robustness has to be learned from augmented data, built in with an equivariant design, or tested by rotating test clouds.
DExplorable · Equivariance: rotate the input, check the output
Does a model's answer turn with its input, as physics says it must?
Rotate the input. Will this model's energy stay exactly the same?
Model
Four small networks with fixed random weights. Each gives one number (an energy) and one arrow per point.
How many points (atoms, say) the model sees.
Rotate every point by this angle about the origin before asking the model again.
Move every point by (1, −0.5) after rotating.
Red bars fail the check. Differences below 10⁻¹² are rounding and show as 0.
Commit your prediction above to see the result
Make your prediction to see the result.
What runs here
ReadCheck: point clouds
CheckpointCheck yourself
What makes PointNet's global feature independent of the order of the points?
Show the answer
Answer: b
Shared point features plus a componentwise max is a symmetric function of the points.
Check yourself
Why can a few stray points change PointNet's global feature?
Show the answer
Answer: a
Max pooling keeps the most extreme value per feature. Outliers and sensor artifacts can therefore dominate.
Check yourself
What does PointNet++ add to PointNet?
Show the answer
Answer: b
Set abstraction gives local structure at several scales. It is still not rotation equivariant.
Check yourself
A model trained on dense indoor scans is applied to sparse outdoor scans with the same radius. What is the risk?
Show the answer
Answer: a
Neighborhoods depend on metric scale and sampling density. Check performance across densities before deployment.
Check yourself
What makes DGCNN's graph "dynamic"?
Show the answer
Answer: b
Neighbor identities are recomputed, discrete choices. Later layers can link points that are far apart in space but similar in features.
Check yourself
Two neighbors are almost exactly the same distance from a point. Why does that matter for EdgeConv?
Show the answer
Answer: a
The reference notes that k-nearest-neighbor selection is discontinuous at ties. Small coordinate noise can change the graph.
Recap
Recap- A point cloud is an unordered set of coordinates.
- PointNet: shared point features, max pooling. PointNet++: local PointNets on radius neighborhoods. DGCNN: k-nearest-neighbor edges, rebuilt per layer.
- None of these is rotation-free by design: test rotated inputs.
- Max pooling runs in
learn.set_model; full point-cloud models need a data type CodeSplash doesn't load yet.
Concepts in this lesson