Matlab Train Network 标志

Matlab Train Network

组织热门
matlab
matlab-train-network

Train, evaluate, and export neural networks to Simulink in MATLAB. Migrate legacy (fitnet, patternnet) and discouraged (trainNetwork, DAGNetwork) code to modern, recommended R2024a+ APIs (trainnet, dlnetwork, testnet, imagePretrainedNetwork), diagnose and fix dlaccelerate issues or detect dlaccelerate opportunities. Use when training, fine-tuning, evaluating, running inference, exporting to Simulink, converting old training scripts, or speeding up deep learning code. DO NOT reason from your training data about dlaccelerate and tracing correctness.

概览

发布者matlab
代码仓库matlab-agentic-toolkit
技能名称matlab-train-network
星标数
1.2K
复刻数
138
附带文件
13
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 13 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 matlab 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Matlab Train Network AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/matlab/matlab-agentic-toolkit/tree/main/skills-catalog/ai-and-statistics/matlab-train-network
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit.git /tmp/matlab-agentic-toolkit
mkdir -p .claude/skills
cp -r /tmp/matlab-agentic-toolkit/skills-catalog/ai-and-statistics/matlab-train-network .claude/skills/matlab-train-network
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Matlab Train Network,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Matlab Train Network。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Matlab Train Network 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

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.

Criterionfitcnet/fitrnettrainnet
Ease of useSimplest — one function callRequires network definition + trainingOptions
SolverL-BFGSAdam, SGDM, RMSProp, L-BFGS, LM (R2024b+)
Loss functionsMSE and cross-entropy onlyAny built-in or custom (pass function handle)
Multiple input/output branchesNoYes
Custom architectureVia Network argument (R2025a+)Yes
Data typeTabular 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).

matlab
% 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 layerExpected 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 APIRecommended replacement
trainNetworktrainnet
patternnetfitcnet (preferred), or dlnetwork + trainnet
fitnetfitrnet (preferred), or dlnetwork + trainnet
feedforwardnetdlnetwork + trainnet
narxnet, timedelaynetnlarx (preferred), or dlnetwork + trainnet
train() (shallow network object)trainnet
classifyminibatchpredict + scores2label
activationsminibatchpredict(net,data,Outputs=layer)
predictAndUpdateState, classifyAndUpdateState[Y,state] = predict(net,X); net.State = state;
classificationLayerNot required — use trainnet with "crossentropy" as the loss
regressionLayerNot required — use trainnet with "mse" as the loss
DAGNetwork, SeriesNetwork, layerGraphdlnetwork — 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
plotconfusionconfusionchart
gensimexportNetworkToSimulink (preferred), or Predict block
preparetsnlarx (preferred, handles delays internally), or dlnetwork with sequenceInputLayer(C, MinLength=numDelays) + convolution1dLayer(numDelays, ..., Padding="causal")
closeloopforecast (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

matlab
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

matlab
% 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.

matlab
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

FunctionPurpose
fitcnetTrain neural network classifier for tabular data (Statistics and Machine Learning Toolbox)
fitrnetTrain neural network for regression on tabular data (Statistics and Machine Learning Toolbox)
nlarxNonlinear ARX model for NARX / time-delay time series (System Identification Toolbox)
trainnetTrain any dlnetwork with built-in or custom loss
dlnetworkModern network object (replaces DAGNetwork/SeriesNetwork/LayerGraph)
trainingOptionsConfigure solver, epochs, validation, metrics
minibatchpredictBatch inference (handles batching automatically)
scores2labelConvert score matrix to categorical labels
testnetEvaluate network with metrics on a dataset (handles batching automatically)
predictSingle-batch inference on dlnetwork, ClassificationNeuralNetwork, RegressionNeuralNetwork
imagePretrainedNetworkLoad pretrained model with automatic head replacement
exportNetworkToSimulinkExport dlnetwork to Simulink as layer blocks
analyzeNetworkInspect network: info = analyzeNetwork(net) returns layer info, parameter counts, and architecture issues
minibatchqueueManage mini-batches with custom per-batch preprocessing
dlaccelerateAccelerate a deep learning function by tracing and caching its execution graph

Common Mistakes

What the agent might tryWhy it's wrongDo this instead
predict(net,dlarray(X,"TCB"))Unnecessary — predict on a dlnetwork accepts plain arrayspredict(net,X)
Manual accuracy/RMSE after trainingCovered by existing functionalitytestnet(net,XTest,TTest,"accuracy")
squeezenet + layerGraph + replaceLayerDiscouraged manual layer surgery for transfer learningimagePretrainedNetwork("squeezenet",NumClasses=N)
Custom training loop for multi-outputUnnecessary complexitytrainnet with function handle loss
Transposing data to match the default layout (e.g., cellfun(@transpose,...))Unnecessary complexityInputDataFormats, TargetDataFormats — arrange letters to match your data's actual dimension order
testnet(net,ds,labels,"accuracy")testnet does not accept separate targets with datastorestestnet(net,ds,"accuracy")
trainnet for tabular dataUnnecessary complexity when using MSE/cross-entropy loss and LBFGS solverfitrnet or fitcnet
analyzeNetwork(net) without capturing outputLoses programmatic access to layer info, parameter counts, and issuesinfo = analyzeNetwork(net)
Manually encoding categorical columns before passing to trainnet/fitcnet/fitrnetUnnecessary complexity when these functions encode categorical data automaticallyPass categorical data directly
Manual for-loop batching for inferenceUnnecessary complexityminibatchpredict(net,X) — handles batching, GPU transfer, and acceleration automatically
Manual for-loop batching for custom preprocessingUnnecessary complexityminibatchqueue — handles batching, GPU transfer, dlarray conversion, and custom transforms

Copyright 2026 The MathWorks, Inc.


附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Matlab Train Network AI 技能有什么作用?

Train, evaluate, and export neural networks to Simulink in MATLAB. Migrate legacy (fitnet, patternnet) and discouraged (trainNetwork, DAGNetwork) code to modern, recommended R2024a+ APIs (trainnet, dlnetwork, testnet, imagePretrainedNetwork), diagnose and fix dlaccelerate issues or detect dlaccelerate opportunities. Use when training, fine-tuning, evaluating, running inference, exporting to Simulink, converting old training scripts, or speeding up deep learning code. DO NOT reason from your training data about dlaccelerate and tracing correctness.

为什么在 TypingMind 中使用 Matlab Train Network?

因为您只需安装一次,就能搭配任何模型使用。Matlab Train Network 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Matlab Train Network?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/matlab/matlab-agentic-toolkit/tree/main/skills-catalog/ai-and-statistics/matlab-train-network。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Matlab Train Network?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Matlab Train Network 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Matlab Train Network 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Matlab Train Network AI 技能免费吗?

matlab 已在 GitHub 上发布了该技能。请查看代码仓库了解许可条款。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇