matlab-train-network
Train, evaluate, and export neural networks to Simulink in MATLAB using the
recommended dlnetwork-based API (trainnet, dlnetwork, minibatchpredict,
scores2label, testnet, imagePretrainedNetwork) or, for tabular data, the
Statistics and Machine Learning Toolbox functions fitcnet and fitrnet.
When to Use
Activate this skill when a user asks to:
- Train any neural network (classifier, regression, multi-output, LSTM, CNN, etc.)
- Fine-tune or use a pretrained model for transfer learning
- Evaluate a trained network on test data
- Run inference / predict with a trained network
- Export a trained network to Simulink
- Migrate existing legacy (patternnet, fitnet, narxnet, gensim) or discouraged
(trainNetwork, DAGNetwork, classify) code to recommended APIs
- Create a "pattern recognition network", "function fitting network", "NARX
network", or any task historically associated with the Neural Network Toolbox
shallow nets API
- Speed up or optimize any deep learning code (even without mentioning dlaccelerate by name)
- Make existing deep learning code faster using dlaccelerate
- Diagnose and fix dlaccelerate issues (low HitRate, retracing, code is slower after using dlaccelerate)
- Accelerate custom training (code that uses dlfeval/dlgradient)
- Accelerate a function that supports dlarray input and is long running
- Accelerate a custom loss function passed to trainnet (R2026a+)
When NOT to Use
- Importing/exporting models (importNetworkFromPyTorch, exportONNXNetwork)
- Data loading and preprocessing (imageDatastore, transforms, augmentation)
- Network architecture design decisions (choosing CNN vs LSTM vs transformer)
- Reinforcement learning workflows (use Reinforcement Learning Toolbox)
- Object detection (use specialized detector training functions in Computer Vision Toolbox)
Decision: fitrnet/fitcnet or trainnet
Apply this check before starting any training workflow below.
| Criterion |
fitcnet/fitrnet |
trainnet |
| Ease of use |
Simplest — one function call |
Requires network definition + trainingOptions |
| Solver |
L-BFGS |
Adam, SGDM, RMSProp, L-BFGS, LM (R2024b+) |
| Loss functions |
MSE and cross-entropy only |
Any built-in or custom (pass function handle) |
| Multiple input/output branches |
No |
Yes |
| Custom architecture |
Via Network argument (R2025a+) |
Yes |
| Data type |
Tabular data only (a table or a numeric matrix) |
Tabular data plus everything else (sequences, images, multi-input) |
Pass tables directly to trainnet, fitcnet, and fitrnet. If inputs have
categorical columns, pass them directly — they are encoded automatically
(fitcnet/fitrnet always; trainnet/minibatchpredict/testnet from R2025a).
% Classification
mdl = fitcnet(tbl,responseName,LayerSizes=20);
[labels,score] = predict(mdl,tblTest);
L = loss(mdl,tblTest);
% Regression
mdl = fitrnet(tbl,responseName,LayerSizes=[20 20]);
Y = predict(mdl,tblTest);
L = loss(mdl,tblTest);
% Tabular data with trainnet (when fitcnet/fitrnet can't be used)
net = trainnet(tbl,net,"crossentropy",options);
accuracy = testnet(net,tblTest,"accuracy");
scores = minibatchpredict(net,tblPredictors);
- From R2024b,
fitrnet supports multi-response variables.
- From R2025a, for custom architectures beyond
LayerSizes, Activations, LayerWeightsInitializer, and LayerBiasesInitializer, pass a dlnetwork via the Network name-value argument.
Conventions
Training with trainnet + dlnetwork
Data formats
trainnet expects data in specific orientations by default:
| Input layer |
Expected data shape |
featureInputLayer(C) |
observations×channels (e.g., 150×4) |
imageInputLayer([H W C]) |
height×width×channels×observations (e.g., 28×28×1×5000) |
sequenceInputLayer(C) |
timesteps×channels×observations, or an observations×1 cell array where each element is a timesteps×channels time series |
If your data has a different layout, use InputDataFormats and/or
TargetDataFormats in trainingOptions instead of transposing the data manually.
The format string describes your data's current layout — one letter per
dimension, not the desired layout. MATLAB handles the remapping internally.
For cell arrays, add "B" (batch) to the format string — e.g.,
InputDataFormats="CTB" for cells of C×T matrices. Do not specify these
options when data already matches the input layer's default.
What trainnet supports
Use trainnet and dlnetwork for all Deep Learning Toolbox training. This includes:
- Standard classification and regression
- Transfer learning
- Multi-input or multi-output networks
- Custom loss functions (pass a function handle to
trainnet)
- Custom loss function backward passes via
DifferentiableFunction
- Custom metrics (string, function handle, or
deep.Metric subclass)
- Custom stopping criteria via
OutputFcn in trainingOptions
- Custom layers
Custom training loops (dlfeval/dlgradient/update functions) are appropriate
when the workflow requires customizations impossible via trainingOptions or
the specific workflow — multi-model adversarial training, alternating updates,
or custom weight update rules. Note that trainingOptions supports L-BFGS (R2023b+)
and Levenberg-Marquardt "lm" (R2024b+).
When a user has a working custom training loop and asks to speed it up, apply
dlaccelerate directly. Mention that their workflow may also be expressible
with trainnet (which handles acceleration internally), but do not push the
conversion — focus on accelerating the code they have.
NEVER use these legacy or discouraged APIs
If the user has existing code using these APIs, migrate it to the recommended
replacement and briefly explain which APIs were replaced and what the modern
equivalents are. If the user asks for a legacy or discouraged API by name,
acknowledge their request and explain that the function has been replaced with a
recommended alternative before providing the solution.
| Legacy or discouraged API |
Recommended replacement |
trainNetwork |
trainnet |
patternnet |
fitcnet (preferred), or dlnetwork + trainnet |
fitnet |
fitrnet (preferred), or dlnetwork + trainnet |
feedforwardnet |
dlnetwork + trainnet |
narxnet, timedelaynet |
nlarx (preferred), or dlnetwork + trainnet |
train() (shallow network object) |
trainnet |
classify |
minibatchpredict + scores2label |
activations |
minibatchpredict(net,data,Outputs=layer) |
predictAndUpdateState, classifyAndUpdateState |
[Y,state] = predict(net,X); net.State = state; |
classificationLayer |
Not required — use trainnet with "crossentropy" as the loss |
regressionLayer |
Not required — use trainnet with "mse" as the loss |
DAGNetwork, SeriesNetwork, layerGraph |
dlnetwork — supports addLayers, connectLayers, and replaceLayer for multi-branch architectures, anything layerGraph can do, dlnetwork can do directly |
resnet18, googlenet, squeezenet, etc. (pretrained network functions that return DAGNetwork) |
imagePretrainedNetwork("resnet18", ...) — returns a dlnetwork and handles head replacement automatically |
Manually converting network scores to labels (e.g., [~,idx] = max(scores)) |
scores2label |
plotconfusion |
confusionchart |
gensim |
exportNetworkToSimulink (preferred), or Predict block |
preparets |
nlarx (preferred, handles delays internally), or dlnetwork with sequenceInputLayer(C, MinLength=numDelays) + convolution1dLayer(numDelays, ..., Padding="causal") |
closeloop |
forecast (preferred, with nlarx), or iterative predict loop feeding previous predictions back as input |
See references/legacy-api-redirects.md for before/after code examples.
Inference — use minibatchpredict (or predict)
If you see a for-loop calling predict or forward on batches for inference,
replace the entire loop with minibatchpredict. It handles batching, GPU
transfer, dlarray conversion, and acceleration automatically. Output format
(numeric array, table, or cell array) depends on the input type and network.
Exception: If the loop includes custom pre- or postprocessing around the
predict call that cannot be separated from it, minibatchpredict cannot
replicate the full pipeline. In that case, wrap the entire custom function
with dlaccelerate instead (see references/dlaccelerate-workflow.md).
Do not split the function into a minibatchpredict call plus separate
accelerated pre/postprocessing — a single dlaccelerate boundary around the
full function produces one unified trace.
- For classification: use
minibatchpredict (or predict) + scores2label.
- For regression or when you need raw scores: use
minibatchpredict or predict.
predict is for single-batch/small-batch use and accepts plain numeric
arrays directly — do not wrap inputs in dlarray or call extractdata on outputs.
Evaluation — use testnet
- Use
testnet to calculate post-training metrics on a test dataset instead
of doing it manually.
- For single-output networks, use string metrics:
"accuracy", "rmse".
trainnet and testnet accept targets as a separate argument only for
in-memory data (testnet(net,XTest,TTest,"accuracy")). When passing a
datastore, targets must already be embedded in it (e.g., labeled
imageDatastore or combined datastore with targets in a second column).
- For multi-output networks or advanced metric customization, see
references/metrics-guidance.md.
Transfer learning — use imagePretrainedNetwork
net = imagePretrainedNetwork("squeezenet",NumClasses=5);
options = trainingOptions("adam", ...
MaxEpochs=10, ...
MiniBatchSize=16, ...
InitialLearnRate=1e-4, ...
ValidationData=imdsVal, ...
Metrics="accuracy", ...
Plots="training-progress");
net = trainnet(augimdsTrain,net,"crossentropy",options);
% Inference — class names come from training data, not the pretrained net
classNames = categories(imdsTrain.Labels);
scores = minibatchpredict(net,imdsTest);
labels = scores2label(scores,classNames);
imagePretrainedNetwork returns class names only when both NumClasses and
NumResponses are unset (pretrained mode, no transfer learning).
Workflow: Training
Check the Decision section above first — tabular data goes to fitrnet/fitcnet unless you need a non-LBFGS solver or a non-MSE/cross-entropy loss.
Standard training
% Define network
numChannels = 3;
numClasses = 5;
layers = [
sequenceInputLayer(numChannels,Normalization="zscore")
lstmLayer(100,OutputMode="last")
fullyConnectedLayer(numClasses)
softmaxLayer];
% Training options
options = trainingOptions("adam", ...
MaxEpochs=30, ...
MiniBatchSize=128, ...
ValidationData={XVal,TVal}, ...
Metrics="accuracy", ...
Plots="training-progress");
% Train
net = trainnet(XTrain,TTrain,layers,"crossentropy",options);
Always normalize inputs. Set Normalization on the input layer (see example
above). For regression, also normalize targets:
- R2026a+: append
inverseNormalizationLayer to the last layer and set
NormalizeTargets=true in trainingOptions
- Pre-R2026a: manually z-score targets before training and denormalize
predictions at inference
See references/normalization.md for both workflows.
Custom loss function for multi-output
The function handle receives network outputs then targets, in order.
Pass categorical targets directly — trainnet encodes them automatically.
lossFcn = @(Y1,Y2,T1,T2) crossentropy(Y1,T1) + mse(Y2,T2);
net = trainnet(ds,net,lossFcn,options);
For the full multi-output recipe (OutputNames alignment, combined datastores,
testnet evaluation), see references/multi-output-training.md.
Since the multi-output loss is a function handle, it can be accelerated using
dlaccelerate. Always inform the user that their custom loss function handle
can be accelerated with dlaccelerate for faster training — even if they did not
ask to speed up training. See references/dlaccelerate-trainnet-custom-loss.md
for the verification and production workflow.
Workflow: Simulink Export
dlnetwork (small, all layers supported): use exportNetworkToSimulink
dlnetwork (large, or has layers unsupported by exportNetworkToSimulink): use the Predict block at library path deeplib/Predict
fitcnet/fitrnet models: use the ClassificationNeuralNetwork Predict or RegressionNeuralNetwork Predict blocks from statsLibrary/
See references/simulink-export.md for details.
Workflow: Deep Learning Code Acceleration with dlaccelerate — Diagnose, Fix, or Apply
Does NOT apply to:
- Simulink export
- MEX/Coder compilation
fitcnet/fitrnet/nlarx workflows
Applies when:
- User has a custom training loop (
dlfeval/dlgradient)
- User has a function that supports dlarray input and is long running
- User calls
trainnet with a custom loss function handle (R2026a+)
Always attempt to dlaccelerate functions that:
- Are long-running.
- Have dlarray objects, structures of dlarray objects, or dlnetwork objects as inputs.
- Only perform operations that affect the output variables. Operations that do not affect the output variables include plotting, displaying output, and writing to files.
Check references/dlaccelerate-workflow.md Step 0 to determine whether the
function is acceleratable before recommending.
Follow references/dlaccelerate-workflow.md for the full diagnostic/fix/improve
process. Entry points:
- User says "make faster" or "speed up" and the code has a custom training loop: start at Step 0.
- Code already uses
dlaccelerate with problems: start at Step 1 (identify
antipatterns, apply fixes, verify).
- Custom training loop without
dlaccelerate: start at Step 0 (requirements check,
wrap, verify).
- Any function with dlarray input that is called repeatedly: start at Step 0.
This includes custom model functions used for prediction.
- Custom inference function called repeatedly: same Step 0 applies.
dlaccelerate is not training-specific — any repeatedly-called dlarray
function benefits. Use minibatchpredict when the loop only calls predict
with no custom pre- or postprocessing; use dlaccelerate when custom
operations surround the predict call.
trainnet + custom loss function handle (R2026a+): wrap the loss with
dlaccelerate and pass the AcceleratedFunction to trainnet. See
references/dlaccelerate-trainnet-custom-loss.md.
For antipatterns that break tracing and their fixes, see
references/dlaccelerate-antipatterns.md.
dlaccelerate References
references/dlaccelerate-workflow.md — full diagnostic/fix/improve process
references/dlaccelerate-antipatterns.md — pattern catalog with BAD/GOOD examples
references/dlaccelerate-custom-training-loop.md — acceleration levels, L2, clipping
references/dlaccelerate-trainnet-custom-loss.md — trainnet + custom loss (R2026a+)
references/dlaccelerate-variable-length-sequences.md — padding/bucketing strategies
references/dlaccelerate-custom-layers.md — Acceleratable custom layers (nnet.layer.Acceleratable)
references/dlaccelerate-measure-speedup.md — benchmarking methodology
Key Functions
| Function |
Purpose |
fitcnet |
Train neural network classifier for tabular data (Statistics and Machine Learning Toolbox) |
fitrnet |
Train neural network for regression on tabular data (Statistics and Machine Learning Toolbox) |
nlarx |
Nonlinear ARX model for NARX / time-delay time series (System Identification Toolbox) |
trainnet |
Train any dlnetwork with built-in or custom loss |
dlnetwork |
Modern network object (replaces DAGNetwork/SeriesNetwork/LayerGraph) |
trainingOptions |
Configure solver, epochs, validation, metrics |
minibatchpredict |
Batch inference (handles batching automatically) |
scores2label |
Convert score matrix to categorical labels |
testnet |
Evaluate network with metrics on a dataset (handles batching automatically) |
predict |
Single-batch inference on dlnetwork, ClassificationNeuralNetwork, RegressionNeuralNetwork |
imagePretrainedNetwork |
Load pretrained model with automatic head replacement |
exportNetworkToSimulink |
Export dlnetwork to Simulink as layer blocks |
analyzeNetwork |
Inspect network: info = analyzeNetwork(net) returns layer info, parameter counts, and architecture issues |
minibatchqueue |
Manage mini-batches with custom per-batch preprocessing |
dlaccelerate |
Accelerate a deep learning function by tracing and caching its execution graph |
Common Mistakes
| What the agent might try |
Why it's wrong |
Do this instead |
predict(net,dlarray(X,"TCB")) |
Unnecessary — predict on a dlnetwork accepts plain arrays |
predict(net,X) |
| Manual accuracy/RMSE after training |
Covered by existing functionality |
testnet(net,XTest,TTest,"accuracy") |
squeezenet + layerGraph + replaceLayer |
Discouraged manual layer surgery for transfer learning |
imagePretrainedNetwork("squeezenet",NumClasses=N) |
| Custom training loop for multi-output |
Unnecessary complexity |
trainnet with function handle loss |
Transposing data to match the default layout (e.g., cellfun(@transpose,...)) |
Unnecessary complexity |
InputDataFormats, TargetDataFormats — arrange letters to match your data's actual dimension order |
testnet(net,ds,labels,"accuracy") |
testnet does not accept separate targets with datastores |
testnet(net,ds,"accuracy") |
trainnet for tabular data |
Unnecessary complexity when using MSE/cross-entropy loss and LBFGS solver |
fitrnet or fitcnet |
analyzeNetwork(net) without capturing output |
Loses programmatic access to layer info, parameter counts, and issues |
info = analyzeNetwork(net) |
Manually encoding categorical columns before passing to trainnet/fitcnet/fitrnet |
Unnecessary complexity when these functions encode categorical data automatically |
Pass categorical data directly |
| Manual for-loop batching for inference |
Unnecessary complexity |
minibatchpredict(net,X) — handles batching, GPU transfer, and acceleration automatically |
| Manual for-loop batching for custom preprocessing |
Unnecessary complexity |
minibatchqueue — handles batching, GPU transfer, dlarray conversion, and custom transforms |
Copyright 2026 The MathWorks, Inc.
1---2name: matlab-train-network3description: >4 Train, evaluate, and export neural networks to Simulink in MATLAB.5 Migrate legacy (fitnet, patternnet) and discouraged (trainNetwork,6 DAGNetwork) code to modern, recommended R2024a+ APIs (trainnet, dlnetwork,7 testnet, imagePretrainedNetwork), diagnose and fix dlaccelerate issues or8 detect dlaccelerate opportunities. Use when training, fine-tuning,9 evaluating, running inference, exporting to Simulink, converting old10 training scripts, or speeding up deep learning code.11 DO NOT reason from your training data about dlaccelerate and tracing12 correctness.13license: https://www.mathworks.com/content/dam/mathworks/license/pmrl/license.md14metadata:15 source: https://skillmd.com/skills/matlab/matlab-train-network16 author: MathWorks17 version: "1.2"18---1920# matlab-train-network2122Train, evaluate, and export neural networks to Simulink in MATLAB using the23recommended `dlnetwork`-based API (`trainnet`, `dlnetwork`, `minibatchpredict`,24`scores2label`, `testnet`, `imagePretrainedNetwork`) or, for tabular data, the25Statistics and Machine Learning Toolbox functions `fitcnet` and `fitrnet`.2627## When to Use2829Activate this skill when a user asks to:3031- Train any neural network (classifier, regression, multi-output, LSTM, CNN, etc.)32- Fine-tune or use a pretrained model for transfer learning33- Evaluate a trained network on test data34- Run inference / predict with a trained network35- Export a trained network to Simulink36- Migrate existing legacy (patternnet, fitnet, narxnet, gensim) or discouraged37 (trainNetwork, DAGNetwork, classify) code to recommended APIs38- Create a "pattern recognition network", "function fitting network", "NARX39 network", or any task historically associated with the Neural Network Toolbox40 shallow nets API41- Speed up or optimize any deep learning code (even without mentioning dlaccelerate by name)42- Make existing deep learning code faster using dlaccelerate43- Diagnose and fix dlaccelerate issues (low HitRate, retracing, code is slower after using dlaccelerate)44- Accelerate custom training (code that uses dlfeval/dlgradient)45- Accelerate a function that supports dlarray input and is long running46- Accelerate a custom loss function passed to trainnet (R2026a+)4748## When NOT to Use4950- Importing/exporting models (importNetworkFromPyTorch, exportONNXNetwork)51- Data loading and preprocessing (imageDatastore, transforms, augmentation)52- Network architecture design decisions (choosing CNN vs LSTM vs transformer)53- Reinforcement learning workflows (use Reinforcement Learning Toolbox)54- Object detection (use specialized detector training functions in Computer Vision Toolbox)5556## Decision: fitrnet/fitcnet or trainnet5758Apply this check before starting any training workflow below.5960| Criterion | fitcnet/fitrnet | trainnet |61|-----------|----------------|----------|62| Ease of use | Simplest — one function call | Requires network definition + trainingOptions |63| Solver | L-BFGS | Adam, SGDM, RMSProp, L-BFGS, LM (R2024b+) |64| Loss functions | MSE and cross-entropy only | Any built-in or custom (pass function handle) |65| Multiple input/output branches | No | Yes |66| Custom architecture | Via `Network` argument (R2025a+) | Yes |67| Data type | Tabular data only (a table or a numeric matrix) | Tabular data plus everything else (sequences, images, multi-input) |6869Pass tables directly to `trainnet`, `fitcnet`, and `fitrnet`. If inputs have70categorical columns, pass them directly — they are encoded automatically71(`fitcnet`/`fitrnet` always; `trainnet`/`minibatchpredict`/`testnet` from R2025a).7273```matlab74% Classification75mdl = fitcnet(tbl,responseName,LayerSizes=20);76[labels,score] = predict(mdl,tblTest);77L = loss(mdl,tblTest);7879% Regression80mdl = fitrnet(tbl,responseName,LayerSizes=[20 20]);81Y = predict(mdl,tblTest);82L = loss(mdl,tblTest);8384% Tabular data with trainnet (when fitcnet/fitrnet can't be used)85net = trainnet(tbl,net,"crossentropy",options);86accuracy = testnet(net,tblTest,"accuracy");87scores = minibatchpredict(net,tblPredictors);88```8990- From R2024b, `fitrnet` supports multi-response variables.91- From R2025a, for custom architectures beyond `LayerSizes`, `Activations`, `LayerWeightsInitializer`, and `LayerBiasesInitializer`, pass a `dlnetwork` via the `Network` name-value argument.9293---9495## Conventions9697### Training with trainnet + dlnetwork9899#### Data formats100101`trainnet` expects data in specific orientations by default:102103| Input layer | Expected data shape |104|-------------|-------------------|105| `featureInputLayer(C)` | observations×channels (e.g., 150×4) |106| `imageInputLayer([H W C])` | height×width×channels×observations (e.g., 28×28×1×5000) |107| `sequenceInputLayer(C)` | timesteps×channels×observations, or an observations×1 cell array where each element is a timesteps×channels time series |108109If your data has a different layout, use `InputDataFormats` and/or110`TargetDataFormats` in `trainingOptions` instead of transposing the data manually.111The format string describes your data's current layout — one letter per112dimension, not the desired layout. MATLAB handles the remapping internally.113For cell arrays, add `"B"` (batch) to the format string — e.g.,114`InputDataFormats="CTB"` for cells of C×T matrices. Do not specify these115options when data already matches the input layer's default.116117#### What trainnet supports118119Use `trainnet` and `dlnetwork` for all Deep Learning Toolbox training. This includes:120121- Standard classification and regression122- Transfer learning123- Multi-input or multi-output networks124- Custom loss functions (pass a function handle to `trainnet`)125- Custom loss function backward passes via `DifferentiableFunction`126- Custom metrics (string, function handle, or `deep.Metric` subclass)127- Custom stopping criteria via `OutputFcn` in `trainingOptions`128- Custom layers129130Custom training loops (`dlfeval`/`dlgradient`/update functions) are appropriate131when the workflow requires customizations impossible via `trainingOptions` or132the specific workflow — multi-model adversarial training, alternating updates,133or custom weight update rules. Note that `trainingOptions` supports L-BFGS (R2023b+)134and Levenberg-Marquardt `"lm"` (R2024b+).135136When a user has a working custom training loop and asks to speed it up, apply137`dlaccelerate` directly. Mention that their workflow may also be expressible138with `trainnet` (which handles acceleration internally), but do not push the139conversion — focus on accelerating the code they have.140141### NEVER use these legacy or discouraged APIs142143If the user has existing code using these APIs, migrate it to the recommended144replacement and briefly explain which APIs were replaced and what the modern145equivalents are. If the user asks for a legacy or discouraged API by name,146acknowledge their request and explain that the function has been replaced with a147recommended alternative before providing the solution.148149| Legacy or discouraged API | Recommended replacement |150|-----------|-------------------|151| `trainNetwork` | `trainnet` |152| `patternnet` | `fitcnet` (preferred), or `dlnetwork` + `trainnet` |153| `fitnet` | `fitrnet` (preferred), or `dlnetwork` + `trainnet` |154| `feedforwardnet` | `dlnetwork` + `trainnet` |155| `narxnet`, `timedelaynet` | `nlarx` (preferred), or `dlnetwork` + `trainnet` |156| `train()` (shallow `network` object) | `trainnet` |157| `classify` | `minibatchpredict` + `scores2label` |158| `activations` | `minibatchpredict(net,data,Outputs=layer)` |159| `predictAndUpdateState`, `classifyAndUpdateState` | `[Y,state] = predict(net,X); net.State = state;` |160| `classificationLayer` | Not required — use `trainnet` with `"crossentropy"` as the loss |161| `regressionLayer` | Not required — use `trainnet` with `"mse"` as the loss |162| `DAGNetwork`, `SeriesNetwork`, `layerGraph` | `dlnetwork` — supports `addLayers`, `connectLayers`, and `replaceLayer` for multi-branch architectures, anything `layerGraph` can do, `dlnetwork` can do directly |163| `resnet18`, `googlenet`, `squeezenet`, etc. (pretrained network functions that return `DAGNetwork`) | `imagePretrainedNetwork("resnet18", ...)` — returns a `dlnetwork` and handles head replacement automatically |164| Manually converting network scores to labels (e.g., `[~,idx] = max(scores)`) | `scores2label` |165| `plotconfusion` | `confusionchart` |166| `gensim` | `exportNetworkToSimulink` (preferred), or Predict block |167| `preparets` | `nlarx` (preferred, handles delays internally), or `dlnetwork` with `sequenceInputLayer(C, MinLength=numDelays)` + `convolution1dLayer(numDelays, ..., Padding="causal")` |168| `closeloop` | `forecast` (preferred, with `nlarx`), or iterative `predict` loop feeding previous predictions back as input |169170See `references/legacy-api-redirects.md` for before/after code examples.171172### Inference — use minibatchpredict (or predict)173174If you see a for-loop calling `predict` or `forward` on batches for inference,175replace the entire loop with `minibatchpredict`. It handles batching, GPU176transfer, dlarray conversion, and acceleration automatically. Output format177(numeric array, table, or cell array) depends on the input type and network.178179**Exception:** If the loop includes custom pre- or postprocessing around the180`predict` call that cannot be separated from it, `minibatchpredict` cannot181replicate the full pipeline. In that case, wrap the entire custom function182with `dlaccelerate` instead (see `references/dlaccelerate-workflow.md`).183Do not split the function into a `minibatchpredict` call plus separate184accelerated pre/postprocessing — a single `dlaccelerate` boundary around the185full function produces one unified trace.186187- For classification: use `minibatchpredict` (or `predict`) + `scores2label`.188- For regression or when you need raw scores: use `minibatchpredict` or `predict`.189- `predict` is for single-batch/small-batch use and accepts plain numeric190 arrays directly — do not wrap inputs in `dlarray` or call `extractdata` on outputs.191192### Evaluation — use testnet193194- Use `testnet` to calculate post-training metrics on a test dataset instead195 of doing it manually.196- For single-output networks, use string metrics: `"accuracy"`, `"rmse"`.197- `trainnet` and `testnet` accept targets as a separate argument only for198 in-memory data (`testnet(net,XTest,TTest,"accuracy")`). When passing a199 datastore, targets must already be embedded in it (e.g., labeled200 imageDatastore or combined datastore with targets in a second column).201- For multi-output networks or advanced metric customization, see202 `references/metrics-guidance.md`.203204### Transfer learning — use imagePretrainedNetwork205206```matlab207net = imagePretrainedNetwork("squeezenet",NumClasses=5);208209options = trainingOptions("adam", ...210 MaxEpochs=10, ...211 MiniBatchSize=16, ...212 InitialLearnRate=1e-4, ...213 ValidationData=imdsVal, ...214 Metrics="accuracy", ...215 Plots="training-progress");216217net = trainnet(augimdsTrain,net,"crossentropy",options);218219% Inference — class names come from training data, not the pretrained net220classNames = categories(imdsTrain.Labels);221scores = minibatchpredict(net,imdsTest);222labels = scores2label(scores,classNames);223```224225`imagePretrainedNetwork` returns class names only when both `NumClasses` and226`NumResponses` are unset (pretrained mode, no transfer learning).227228---229230## Workflow: Training231232Check the Decision section above first — tabular data goes to `fitrnet`/`fitcnet` unless you need a non-LBFGS solver or a non-MSE/cross-entropy loss.233234### Standard training235236```matlab237% Define network238numChannels = 3;239numClasses = 5;240layers = [241 sequenceInputLayer(numChannels,Normalization="zscore")242 lstmLayer(100,OutputMode="last")243 fullyConnectedLayer(numClasses)244 softmaxLayer];245246% Training options247options = trainingOptions("adam", ...248 MaxEpochs=30, ...249 MiniBatchSize=128, ...250 ValidationData={XVal,TVal}, ...251 Metrics="accuracy", ...252 Plots="training-progress");253254% Train255net = trainnet(XTrain,TTrain,layers,"crossentropy",options);256```257258Always normalize inputs. Set `Normalization` on the input layer (see example259above). For regression, also normalize targets:260261- **R2026a+**: append `inverseNormalizationLayer` to the last layer and set262 `NormalizeTargets=true` in `trainingOptions`263- **Pre-R2026a**: manually z-score targets before training and denormalize264 predictions at inference265266See `references/normalization.md` for both workflows.267268### Custom loss function for multi-output269270The function handle receives network outputs then targets, in order.271Pass categorical targets directly — `trainnet` encodes them automatically.272273```matlab274lossFcn = @(Y1,Y2,T1,T2) crossentropy(Y1,T1) + mse(Y2,T2);275276net = trainnet(ds,net,lossFcn,options);277```278279For the full multi-output recipe (OutputNames alignment, combined datastores,280testnet evaluation), see `references/multi-output-training.md`.281282Since the multi-output loss is a function handle, it can be accelerated using283`dlaccelerate`. **Always inform the user** that their custom loss function handle284can be accelerated with `dlaccelerate` for faster training — even if they did not285ask to speed up training. See `references/dlaccelerate-trainnet-custom-loss.md`286for the verification and production workflow.287288---289290## Workflow: Simulink Export291292- **`dlnetwork` (small, all layers supported)**: use `exportNetworkToSimulink`293- **`dlnetwork` (large, or has layers unsupported by `exportNetworkToSimulink`)**: use the Predict block at library path `deeplib/Predict`294- **`fitcnet`/`fitrnet` models**: use the `ClassificationNeuralNetwork Predict` or `RegressionNeuralNetwork Predict` blocks from `statsLibrary/`295296See `references/simulink-export.md` for details.297298---299300## Workflow: Deep Learning Code Acceleration with dlaccelerate — Diagnose, Fix, or Apply301302**Does NOT apply to:**303- Simulink export304- MEX/Coder compilation305- `fitcnet`/`fitrnet`/`nlarx` workflows306307**Applies when:**308- User has a custom training loop (`dlfeval`/`dlgradient`)309- User has a function that supports dlarray input and is long running310- User calls `trainnet` with a custom loss function handle (R2026a+)311312Always attempt to dlaccelerate functions that:313- Are long-running.314- Have dlarray objects, structures of dlarray objects, or dlnetwork objects as inputs.315- Only perform operations that affect the output variables. Operations that do not affect the output variables include plotting, displaying output, and writing to files.316317Check `references/dlaccelerate-workflow.md` Step 0 to determine whether the318function is acceleratable before recommending.319320Follow `references/dlaccelerate-workflow.md` for the full diagnostic/fix/improve321process. Entry points:322323- **User says "make faster" or "speed up" and the code has a custom training loop:** start at Step 0.324- **Code already uses `dlaccelerate` with problems:** start at Step 1 (identify325 antipatterns, apply fixes, verify).326- **Custom training loop without `dlaccelerate`:** start at Step 0 (requirements check,327 wrap, verify).328- **Any function with dlarray input that is called repeatedly:** start at Step 0.329 This includes custom model functions used for prediction.330- **Custom inference function called repeatedly:** same Step 0 applies.331 `dlaccelerate` is not training-specific — any repeatedly-called dlarray332 function benefits. Use `minibatchpredict` when the loop only calls `predict`333 with no custom pre- or postprocessing; use `dlaccelerate` when custom334 operations surround the predict call.335- **`trainnet` + custom loss function handle (R2026a+):** wrap the loss with336 `dlaccelerate` and pass the AcceleratedFunction to trainnet. See337 `references/dlaccelerate-trainnet-custom-loss.md`.338339For antipatterns that break tracing and their fixes, see340`references/dlaccelerate-antipatterns.md`.341342### dlaccelerate References343344- `references/dlaccelerate-workflow.md` — full diagnostic/fix/improve process345- `references/dlaccelerate-antipatterns.md` — pattern catalog with BAD/GOOD examples346- `references/dlaccelerate-custom-training-loop.md` — acceleration levels, L2, clipping347- `references/dlaccelerate-trainnet-custom-loss.md` — trainnet + custom loss (R2026a+)348- `references/dlaccelerate-variable-length-sequences.md` — padding/bucketing strategies349- `references/dlaccelerate-custom-layers.md` — Acceleratable custom layers (`nnet.layer.Acceleratable`)350- `references/dlaccelerate-measure-speedup.md` — benchmarking methodology351352---353354## Key Functions355356| Function | Purpose |357|----------|---------|358| `fitcnet` | Train neural network classifier for tabular data (Statistics and Machine Learning Toolbox) |359| `fitrnet` | Train neural network for regression on tabular data (Statistics and Machine Learning Toolbox) |360| `nlarx` | Nonlinear ARX model for NARX / time-delay time series (System Identification Toolbox) |361| `trainnet` | Train any `dlnetwork` with built-in or custom loss |362| `dlnetwork` | Modern network object (replaces DAGNetwork/SeriesNetwork/LayerGraph) |363| `trainingOptions` | Configure solver, epochs, validation, metrics |364| `minibatchpredict` | Batch inference (handles batching automatically) |365| `scores2label` | Convert score matrix to categorical labels |366| `testnet` | Evaluate network with metrics on a dataset (handles batching automatically)|367| `predict` | Single-batch inference on `dlnetwork`, `ClassificationNeuralNetwork`, `RegressionNeuralNetwork` |368| `imagePretrainedNetwork` | Load pretrained model with automatic head replacement |369| `exportNetworkToSimulink` | Export `dlnetwork` to Simulink as layer blocks |370| `analyzeNetwork` | Inspect network: `info = analyzeNetwork(net)` returns layer info, parameter counts, and architecture issues |371| `minibatchqueue` | Manage mini-batches with custom per-batch preprocessing |372| `dlaccelerate` | Accelerate a deep learning function by tracing and caching its execution graph |373374---375376## Common Mistakes377378| What the agent might try | Why it's wrong | Do this instead |379|--------------------------|---------------|-----------------|380| `predict(net,dlarray(X,"TCB"))` | Unnecessary — `predict` on a `dlnetwork` accepts plain arrays | `predict(net,X)` |381| Manual accuracy/RMSE after training | Covered by existing functionality | `testnet(net,XTest,TTest,"accuracy")` |382| `squeezenet` + `layerGraph` + `replaceLayer` | Discouraged manual layer surgery for transfer learning | `imagePretrainedNetwork("squeezenet",NumClasses=N)` |383| Custom training loop for multi-output | Unnecessary complexity | `trainnet` with function handle loss |384| Transposing data to match the default layout (e.g., `cellfun(@transpose,...)`) | Unnecessary complexity | `InputDataFormats`, `TargetDataFormats` — arrange letters to match your data's actual dimension order |385| `testnet(net,ds,labels,"accuracy")` | `testnet` does not accept separate targets with datastores | `testnet(net,ds,"accuracy")` |386| `trainnet` for tabular data | Unnecessary complexity when using MSE/cross-entropy loss and LBFGS solver | `fitrnet` or `fitcnet` |387| `analyzeNetwork(net)` without capturing output | Loses programmatic access to layer info, parameter counts, and issues | `info = analyzeNetwork(net)` |388| Manually encoding categorical columns before passing to `trainnet`/`fitcnet`/`fitrnet` | Unnecessary complexity when these functions encode categorical data automatically | Pass categorical data directly |389| Manual for-loop batching for inference | Unnecessary complexity | `minibatchpredict(net,X)` — handles batching, GPU transfer, and acceleration automatically |390| Manual for-loop batching for custom preprocessing | Unnecessary complexity | `minibatchqueue` — handles batching, GPU transfer, dlarray conversion, and custom transforms |391392----393394Copyright 2026 The MathWorks, Inc.395396----