Examples
50 small scripts you can copy and run. Each page shows the source and what it prints.
50 of 50 examples
- 00Quick StartA short tour of tensors, DataFrames and a first machine learning model. The script is about 50 lines.beginnerTensorsDataFrameMLPreprocessingbeginner
- 01Tensor BasicsHow to create and inspect tensors, the N-dimensional arrays that every other module is built on.beginnerTensorsbeginner
- 02Tensor OperationsArithmetic, math functions and reductions on tensors, including broadcasting.beginnerTensorsbeginner
- 03Data Analysis & VisualizationAn exploratory workflow on a 20-row employee table: summarize it, compute statistics, group and filter rows, and draw four charts.beginnerDataFrameTensorsStatisticsVisualizationbeginner
- 04DataFrame BasicsThe basic DataFrame operations: creation, column access, selection, filtering, sorting,
headandtail.beginnerDataFramebeginner - 05DataFrame GroupBy & AggregationGroup rows by one or more columns and aggregate each group, like SQL
GROUP BY.beginnerDataFramebeginner - 06Machine Learning PipelineTwo end-to-end workflows. Part 1 classifies Iris (setosa vs the rest). Part 2 compares four linear regression models on the Housing-Mini dataset, cross-validates one and plots its predictions.intermediateDatasetsMLMetricsPreprocessingintermediate
- 07Linear RegressionFit a linear regression to noisy synthetic data (
y = 2x + 3) and measure it on a held-out test set.intermediateMLTensorsRandomMetricsintermediate - 08Logistic RegressionBinary classification with logistic regression on the Iris dataset: setosa vs the other two species.intermediateDatasetsMLMetricsPreprocessingintermediate
- 09Ridge & Lasso RegressionCompare L2 (Ridge) and L1 (Lasso) regularization against plain linear regression on the diabetes dataset.intermediateDatasetsMLMetricsPreprocessingintermediate
- 10Advanced ML ModelsFive models on tiny datasets: KMeans clustering, K-Nearest Neighbors for classification and regression, PCA, and Gaussian Naive Bayes.intermediateMLTensorsMetricsPreprocessingintermediate
- 11Tree-Based & Ensemble ModelsDecision trees, random forests, gradient boosting and linear SVMs, for classification and regression.intermediateDatasetsMLTensorsMetricsintermediate
- 12Complete ML PipelineA regression workflow from start to finish on the Housing-Mini dataset: load, explore, split, scale, fit a Ridge model, evaluate and plot.advancedDatasetsMLMetricsPreprocessingadvanced
- 13Neural Network TrainingTrain small networks with plain tensors. Covers
Sequentialmodels, a customModule, themseLossfunction,AdamandSGDwith momentum.intermediateTensorsNeural NetworksOptimizationintermediate - 14Automatic Differentiation (Autograd)Deepbox records the operations done on tracked tensors (
GradTensor) as a computation graph.backward()walks the graph in reverse and fills in the gradient of each tracked input.intermediateTensorsNeural Networksintermediate - 15Activation FunctionsApply common activation functions to a range of inputs, compare their values at a few points and plot them.intermediateTensorsVisualizationintermediate
- 16Learning Rate SchedulersA scheduler changes the optimizer's learning rate as training goes on. This example steps eight schedulers for a few epochs and prints the learning rate at each one.intermediateNeural NetworksOptimizationintermediate
- 17Preprocessing: EncodersTurn categorical and label data into numbers and back again with five encoders.intermediateTensorsPreprocessingintermediate
- 18Preprocessing: ScalersSeven scalers applied to the same small table. The table has a large outlier in the first and last columns, so you can see how each scaler reacts to it.intermediateTensorsPreprocessingintermediate
- 19StatisticsDescriptive statistics, percentiles and correlation on small samples. For hypothesis tests see example 43.intermediateTensorsStatisticsintermediate
- 20Linear Algebra OperationsDeterminant, inverse, norms, matrix power, SVD, QR, LU, symmetric eigendecomposition and linear systems. Each decomposition is checked by multiplying the factors back together.intermediateLinear AlgebraTensorsintermediate
- 21Random Sampling & DistributionsDraw random numbers from common distributions.
setSeedmakes every later draw reproducible, which helps with simulations, tests and repeatable experiments.intermediateRandomTensorsintermediate - 22Built-in DatasetsLoad the 24 built-in datasets and the 6 synthetic generators, and print their shapes and metadata. The datasets ship with the package, so nothing is downloaded.intermediateDatasetsintermediate
- 23Cross-ValidationCross-validation scores a model on several different train/test splits, so one lucky or unlucky split does not decide the result. The example covers the splitters and
crossValScore, which runs the whole loop.intermediatePreprocessingMLTensorsRandomintermediate - 24Model Evaluation MetricsMetrics for classification, regression and clustering, including the multiclass and probability-based metrics.intermediateTensorsMetricsintermediate
- 25Data VisualizationCreate line, scatter, bar, histogram and heatmap plots and save each one as an SVG file.
Figure.renderSVG()returns the SVG text.Figure.renderPNG()renders PNG in Node.js.intermediateTensorsVisualizationintermediate - 26Sparse Matrix Operations
CSRMatrix(Compressed Sparse Row) stores only the non-zero entries of a matrix. This example builds one from COO triplets and runs addition, scaling, element-wise and matrix products, transpose and conversion back to a dense tensor.intermediateTensorsintermediate - 27CNN LayersRuns the convolution and pooling layers
Conv1d,Conv2d,MaxPool2dandAvgPool2don small inputs and prints the output shapes. It also showspadding: "same"andpadding: "valid", and chains layers withSequential.intermediateTensorsNeural Networksintermediate - 28Recurrent Neural Network LayersRuns the
RNN,LSTMandGRUlayers on a small batch of sequences and prints the output shapes. It also shows stacked layers, unbatched input and the weight count of each layer type.intermediateTensorsNeural Networksintermediate - 29Attention & Transformer LayersRuns
MultiheadAttentionandTransformerEncoderLayeron a short sequence. It shows self-attention, the attention weights (needWeights), a key padding mask, a causal mask, and theactivationandnormFirstoptions of the encoder layer.advancedTensorsNeural Networksadvanced - 30Normalization & Dropout LayersRuns
BatchNorm1d,LayerNormandDropouton small inputs.BatchNorm1dandDropoutbehave differently in train and eval mode, and the example shows both.intermediateTensorsNeural Networksintermediate - 31DataLoader: Batching & Shuffling
DataLoadersplits a dataset into batches, with optional shuffling, and is the usual way to feed a training loop. The example covers batching, a seeded shuffle,reshuffleEachIteration,dropLastand loading without labels.intermediateDatasetsTensorsintermediate - 32Neural Network Module SystemCovers the
Modulebase class: writing a custom module, listing parameters, saving and loading a state dict, train and eval modes, freezing parameters, forward hooks and theSequentialcontainer. It also shows whenforwardreturns aGradTensorand when it returns a plainTensor.intermediateTensorsNeural Networksintermediate - 33DataFrame Advanced FeaturesTwelve short parts on
SeriesandDataFramefeatures: string and datetime accessors, rolling, expanding and EWM windows,queryandevalexpressions,assign, pivot tables, crosstabs,nlargest, interpolation and gap filling.intermediateDataFrameintermediate - 34Ensemble & Advanced ML ModelsTrains AdaBoost, Bagging, Voting, Stacking and ExtraTrees classifiers, a Gaussian process regressor and Linear Discriminant Analysis on synthetic data, then prints a comparison table. It also shows
classWeightandclone().advancedMLMetricsDatasetsPreprocessingadvanced - 35Advanced ClusteringRuns eight clustering algorithms on synthetic data and scores them with the silhouette score and the adjusted Rand index. Seven run on well-separated blobs. Spectral clustering runs on two interleaved moons, a non-convex shape.advancedMLMetricsDatasetsadvanced
- 36Kernel SVM & Anomaly DetectionKernel support vector machines (
SVC,NuSVC,SVR) and anomaly detectors (IsolationForest,LocalOutlierFactor,OneClassSVM). The SVMs compare kernels and values ofCon synthetic data. The detectors look for three planted outliers in a small 2-D dataset.advancedMLMetricsDatasetsPreprocessingadvanced - 37Model Selection & PipelineChains a scaler and a model with
Pipeline, scores models withcrossValidate, and tunes hyperparameters withGridSearchCVandRandomizedSearchCV. A pipeline step's parameters are tuned asstepName__parameterName, for exampleclassifier__nNeighbors.advancedMLPreprocessingDatasetsadvanced - 38Feature Engineering & PreprocessingNine short parts on preprocessing: imputation, feature selection, text vectorizers, polynomial and spline features, median-based and power scalers, and cross-validation splitters.
PowerTransformerhasstandardizeset tofalseby default, while scikit-learn usestrue. The example shows both settings.intermediatePreprocessingTensorsintermediate - 39Advanced Neural NetworksEight parts on neural network building blocks: weight initialization, GELU and PReLU,
LayerNormandGroupNorm,Embedding,ModuleListandModuleDict, aSequentialmodel with dropout, and theTrainerwith early stopping, gradient accumulation and best-weight restore.GELUuses the tanh approximation by default, while PyTorch uses the exact form. Pass{ approximate: "none" }for the exact form.advancedNeural NetworksOptimizationTensorsRandomadvanced - 40Transformer ArchitectureBuilds the parts of a Transformer one at a time and prints the tensor shapes:
MultiheadAttention, encoder and decoder layers and stacks,PositionalEncoding, and a small encoder-decoder pipeline from token ids to vocabulary logits withEmbedding,causalMaskand aLinearoutput projection.advancedNeural NetworksTensorsadvanced - 41Advanced Optimizers & SchedulersTrains a small network with the
RAdam,LAMBandLARSoptimizers, then prints the learning rate curves of theCyclicLR,CosineAnnealingWarmRestarts,PolynomialLR,LambdaLRandSequentialLRschedulers.advancedOptimizationNeural NetworksTensorsRandomadvanced - 42FFT & Signal ProcessingUses
fft,ifft,rfft,irfft,fft2,ifft2andrfftfreqto find the frequencies in a signal, rebuild it, and remove high-frequency noise with a low-pass filter. It also checks Parseval's theorem. Each transform returns an object with arealand animagtensor.intermediateTensorsintermediate - 43Statistical Distributions & Hypothesis TestsEvaluates probability distributions (
norm,t,chi2,expon,beta,uniform,binom,poisson) and runs hypothesis tests (t-tests, chi-square, Shapiro-Wilk, Kolmogorov-Smirnov, one-way ANOVA) and correlation tests (Pearson, Spearman, Kendall). The correlation tests take analternativeoption, andkendalltaualso takesvariantandmethod.intermediateStatisticsTensorsintermediate - 44Advanced VisualizationTen plots through the function-style plotting API: line, scatter, bar, histogram, heatmap, confusion matrix, ROC curve, feature importance, elbow curve and residual plot. Each plot is rendered with
show({ format: "svg" }), and the example reports the size of the SVG text. Example 25 writes SVG files with theFigureclass.advancedVisualizationTensorsadvanced - 45Core Runtime ToolingWalks through the runtime tools in
deepbox/core: the logger, warning filters, JSON and file serialization, and the backend registry with the WASM SIMD backend. The WebGPU and WASM backends accelerate a subset of operations. An operation that a device cannot run throws aDeviceErrorthat says to move the tensor withawait t.cpu().advancedCoreadvanced - 46Dataset Transforms & SamplersDataset helpers around a training loop, applied to the iris dataset:
randomSplit,Subset,filterDataset,mapDataset,WeightedRandomSamplerandSubsetRandomSampler. The sampler part builds a skewed two-class dataset, weights each row by the inverse of its class size, and draws batches with aDataLoader.intermediateDatasetsintermediate - 47DataFrame IO & StylingReads and writes a small sales table as CSV, JSON, XLSX and Parquet, parses dates with
toDatetime, formats the table withdf.styleas HTML and ANSI text, and draws a line chart withdf.plot.line().advancedDataFrameadvanced - 48Statistical Inference PlaybookApplies the inference functions in
deepbox/statsto a small A/B experiment: confidence intervals, a bootstrap of the mean uplift, a Gaussian kernel density estimate, p-value correction for four metrics, and a power analysis.intermediateStatisticsVisualizationTensorsintermediate - 49Advanced Linear Algebra ToolkitLinear algebra routines beyond SVD, QR and LU: Hessenberg and Schur decompositions, polar decomposition, matrix functions (
expm,logm,sqrtm,matrixPower), banded and sparse solvers, Sylvester and Lyapunov equations, and special matrix builders. Reconstruction errors are computed with the fluentTensormethodsmatmul,T,sub,square,sumandsqrt.intermediateLinear AlgebraTensorsintermediate