classify
Classify data using trained deep learning neural network
Syntax
Description
You can make predictions using a trained neural network for deep learning on
either a CPU or GPU. Using a GPU requires
a Parallel Computing Toolbox™ license and a supported GPU device. For information about supported devices, see
GPU Computing Requirements (Parallel Computing Toolbox). Specify the hardware requirements using the
ExecutionEnvironment
name-value argument.
For networks with multiple outputs, use the predict
function instead and set the ReturnCategorical
option to true
.
___ = classify(___,
predicts class labels with additional options specified by one or more
name-value arguments.Name=Value
)
Tip
When you make predictions with sequences of different lengths,
the mini-batch size can impact the amount of padding added to the input data, which can result
in different predicted values. Try using different values to see which works best with your
network. To specify mini-batch size and padding options, use the MiniBatchSize
and SequenceLength
options, respectively.
Examples
Classify Images Using Trained Convolutional Neural Network
Load the pretrained network digitsNet
. This network is a classification convolutional neural network that classifies handwritten digits.
load digitsNet
View the network layers. The output layer of the network is a classification layer.
layers = net.Layers
layers = 15x1 Layer array with layers: 1 'imageinput' Image Input 28x28x1 images with 'zerocenter' normalization 2 'conv_1' 2-D Convolution 8 3x3x1 convolutions with stride [1 1] and padding 'same' 3 'batchnorm_1' Batch Normalization Batch normalization with 8 channels 4 'relu_1' ReLU ReLU 5 'maxpool_1' 2-D Max Pooling 2x2 max pooling with stride [2 2] and padding [0 0 0 0] 6 'conv_2' 2-D Convolution 16 3x3x8 convolutions with stride [1 1] and padding 'same' 7 'batchnorm_2' Batch Normalization Batch normalization with 16 channels 8 'relu_2' ReLU ReLU 9 'maxpool_2' 2-D Max Pooling 2x2 max pooling with stride [2 2] and padding [0 0 0 0] 10 'conv_3' 2-D Convolution 32 3x3x16 convolutions with stride [1 1] and padding 'same' 11 'batchnorm_3' Batch Normalization Batch normalization with 32 channels 12 'relu_3' ReLU ReLU 13 'fc' Fully Connected 10 fully connected layer 14 'softmax' Softmax softmax 15 'classoutput' Classification Output crossentropyex with '0' and 9 other classes
Load the test images.
digitDatasetPath = fullfile(toolboxdir("nnet"),"nndemos","nndatasets","DigitDataset"); imdsTest = imageDatastore(digitDatasetPath,IncludeSubfolders=true);
Classify the images using the classify
function.
YTest = classify(net,imdsTest);
View some of the test images at random with their predictions.
numImages = 9; idx = randperm(numel(imdsTest.Files),numImages); figure tiledlayout("flow") for i = 1:numImages nexttile imshow(imdsTest.Files{idx(i)}); title("Predicted Label: " + string(YTest(idx(i)))) end
Classify Sequences Using Trained LSTM Network
Load the pretrained network WaveformNet
.
load WaveformDataNet
View the network architecture.
net.Layers
ans = 5x1 Layer array with layers: 1 'sequenceinput' Sequence Input Sequence input with 3 dimensions 2 'lstm' LSTM LSTM with 120 hidden units 3 'fc' Fully Connected 4 fully connected layer 4 'softmax' Softmax softmax 5 'classoutput' Classification Output crossentropyex with 'Sawtooth' and 3 other classes
Load the test data.
load WaveformTestData
Classify the test data.
YTest = classify(net,XTest);
View the predictions in a confusion chart.
figure confusionchart(TTest,YTest)
Calculate the classification accuracy of the predictions.
accuracy = mean(YTest == TTest)
accuracy = 0.9000
Classify Feature Data Using Trained Network
Load the pretrained network TransmissionCasingNet
. This network classifies the gear tooth condition of a transmission system given a mixture of numeric sensor readings, statistics, and categorical inputs.
load TransmissionCasingNet
View the network architecture.
net.Layers
ans = 7x1 Layer array with layers: 1 'input' Feature Input 22 features with 'zscore' normalization 2 'fc_1' Fully Connected 50 fully connected layer 3 'batchnorm' Batch Normalization Batch normalization with 50 channels 4 'relu' ReLU ReLU 5 'fc_2' Fully Connected 2 fully connected layer 6 'softmax' Softmax softmax 7 'classoutput' Classification Output crossentropyex with classes 'No Tooth Fault' and 'Tooth Fault'
Read the transmission casing data from the CSV file "transmissionCasingData.csv"
.
filename = "transmissionCasingData.csv"; tbl = readtable(filename,TextType="string");
Convert the labels for prediction to categorical using the convertvars
function.
labelName = "GearToothCondition"; tbl = convertvars(tbl,labelName,"categorical");
To make predictions using categorical features, you must first convert the categorical features to numeric. First, convert the categorical predictors to categorical using the convertvars
function by specifying a string array containing the names of all the categorical input variables. This data set has two categorical features named "SensorCondition"
and "ShaftCondition"
.
categoricalInputNames = ["SensorCondition" "ShaftCondition"]; tbl = convertvars(tbl,categoricalInputNames,"categorical");
Loop over the categorical input variables. For each variable:
Convert the categorical values to one-hot encoded vectors using the
onehotencode
function.Add the one-hot vectors to the table using the
addvars
function. Specify insertion of the vectors after the column containing the corresponding categorical data.Remove the corresponding column containing the categorical data.
for i = 1:numel(categoricalInputNames) name = categoricalInputNames(i); oh = onehotencode(tbl(:,name)); tbl = addvars(tbl,oh,After=name); tbl(:,name) = []; end
Split the vectors into separate columns using the splitvars
function.
tbl = splitvars(tbl);
View the first few rows of the table.
head(tbl)
SigMean SigMedian SigRMS SigVar SigPeak SigPeak2Peak SigSkewness SigKurtosis SigCrestFactor SigMAD SigRangeCumSum SigCorrDimension SigApproxEntropy SigLyapExponent PeakFreq HighFreqPower EnvPower PeakSpecKurtosis No Sensor Drift Sensor Drift No Shaft Wear Shaft Wear GearToothCondition ________ _________ ______ _______ _______ ____________ ___________ ___________ ______________ _______ ______________ ________________ ________________ _______________ ________ _____________ ________ ________________ _______________ ____________ _____________ __________ __________________ -0.94876 -0.9722 1.3726 0.98387 0.81571 3.6314 -0.041525 2.2666 2.0514 0.8081 28562 1.1429 0.031581 79.931 0 6.75e-06 3.23e-07 162.13 0 1 1 0 No Tooth Fault -0.97537 -0.98958 1.3937 0.99105 0.81571 3.6314 -0.023777 2.2598 2.0203 0.81017 29418 1.1362 0.037835 70.325 0 5.08e-08 9.16e-08 226.12 0 1 1 0 No Tooth Fault 1.0502 1.0267 1.4449 0.98491 2.8157 3.6314 -0.04162 2.2658 1.9487 0.80853 31710 1.1479 0.031565 125.19 0 6.74e-06 2.85e-07 162.13 0 1 0 1 No Tooth Fault 1.0227 1.0045 1.4288 0.99553 2.8157 3.6314 -0.016356 2.2483 1.9707 0.81324 30984 1.1472 0.032088 112.5 0 4.99e-06 2.4e-07 162.13 0 1 0 1 No Tooth Fault 1.0123 1.0024 1.4202 0.99233 2.8157 3.6314 -0.014701 2.2542 1.9826 0.81156 30661 1.1469 0.03287 108.86 0 3.62e-06 2.28e-07 230.39 0 1 0 1 No Tooth Fault 1.0275 1.0102 1.4338 1.0001 2.8157 3.6314 -0.02659 2.2439 1.9638 0.81589 31102 1.0985 0.033427 64.576 0 2.55e-06 1.65e-07 230.39 0 1 0 1 No Tooth Fault 1.0464 1.0275 1.4477 1.0011 2.8157 3.6314 -0.042849 2.2455 1.9449 0.81595 31665 1.1417 0.034159 98.838 0 1.73e-06 1.55e-07 230.39 0 1 0 1 No Tooth Fault 1.0459 1.0257 1.4402 0.98047 2.8157 3.6314 -0.035405 2.2757 1.955 0.80583 31554 1.1345 0.0353 44.223 0 1.11e-06 1.39e-07 230.39 0 1 0 1 No Tooth Fault
Extract the test labels from the table.
TTest = tbl{:,labelName};
Predict the labels of the test data using the trained network and calculate the accuracy. Specify the same mini-batch size used for training.
YTest = classify(net,tbl(:,1:end-1));
Visualize the predictions in a confusion matrix.
figure confusionchart(TTest,YTest)
Calculate the classification accuracy. The accuracy is the proportion of the labels that the network predicts correctly.
accuracy = mean(YTest == TTest)
accuracy = 0.9952
Input Arguments
net
— Trained network
SeriesNetwork
object | DAGNetwork
object
Trained network, specified as a SeriesNetwork
or a DAGNetwork
object. You can get a trained network by importing a pretrained network (for example, by
using the googlenet
function) or by training your own network using
trainNetwork
.
images
— Image data
datastore | numeric array | table
Image data, specified as one of the following.
Data Type | Description | Example Usage | |
---|---|---|---|
Datastore | ImageDatastore | Datastore of images saved on disk | Make predictions with images saved on disk, where the images are the same size. When the images are different sizes, use an
|
AugmentedImageDatastore | Datastore that applies random affine geometric transformations, including resizing, rotation, reflection, shear, and translation | Make predictions with images saved on disk, where the images are different sizes. | |
TransformedDatastore | Datastore that transforms batches of data read from an underlying datastore using a custom transformation function |
| |
CombinedDatastore | Datastore that reads from two or more underlying datastores |
| |
Custom mini-batch datastore | Custom datastore that returns mini-batches of data | Make predictions using data in a format that other datastores do not support. For details, see Develop Custom Mini-Batch Datastore. | |
Numeric array | Images specified as a numeric array | Make predictions using data that fits in memory and does not require additional processing like resizing. | |
Table | Images specified as a table | Make predictions using data stored in a table. |
When you use a datastore with networks with multiple inputs, the datastore must be a
TransformedDatastore
or
CombinedDatastore
object.
Tip
For sequences of images, for example, video data, use the sequences
input argument.
Datastore
Datastores read mini-batches of images and responses. Use datastores when you have data that does not fit in memory or when you want to resize the input data.
These datastores are directly compatible with classify
for image data.:
Custom mini-batch datastore. For details, see Develop Custom Mini-Batch Datastore.
Tip
Use augmentedImageDatastore
for efficient preprocessing of images for deep
learning, including image resizing. Do not use the ReadFcn
option of
ImageDatastore
objects.
ImageDatastore
allows batch reading of JPG or PNG image files using
prefetching. If you set the ReadFcn
option to a custom function, then
ImageDatastore
does not prefetch and is usually significantly
slower.
You can use other built-in datastores for making predictions by using the transform
and
combine
functions. These functions can convert the data read from datastores to the format required
by classify
.
The required format of the datastore output depends on the network architecture.
Network Architecture | Datastore Output | Example Output |
---|---|---|
Single input | Table or cell array, where the first column specifies the predictors. Table elements must be scalars, row vectors, or 1-by-1 cell arrays containing a numeric array. Custom datastores must output tables. |
data = read(ds) data = 4×1 table Predictors __________________ {224×224×3 double} {224×224×3 double} {224×224×3 double} {224×224×3 double} |
data = read(ds) data = 4×1 cell array {224×224×3 double} {224×224×3 double} {224×224×3 double} {224×224×3 double} | ||
Multiple input | Cell array with at least The
first The order of inputs is given by the
|
data = read(ds) data = 4×2 cell array {224×224×3 double} {128×128×3 double} {224×224×3 double} {128×128×3 double} {224×224×3 double} {128×128×3 double} {224×224×3 double} {128×128×3 double} |
The format of the predictors depends on the type of data.
Data | Format |
---|---|
2-D images | h-by-w-by-c numeric array, where h, w, and c are the height, width, and number of channels of the images, respectively |
3-D images | h-by-w-by-d-by-c numeric array, where h, w, d, and c are the height, width, depth, and number of channels of the images, respectively |
For more information, see Datastores for Deep Learning.
Numeric Array
For data that fits in memory and does not require additional processing like augmentation, you can specify a data set of images as a numeric array.
The size and shape of the numeric array depends on the type of image data.
Data | Format |
---|---|
2-D images | h-by-w-by-c-by-N numeric array, where h, w, and c are the height, width, and number of channels of the images, respectively, and N is the number of images |
3-D images | h-by-w-by-d-by-c-by-N numeric array, where h, w, d, and c are the height, width, depth, and number of channels of the images, respectively, and N is the number of images |
Table
As an alternative to datastores or numeric arrays, you can also specify images in a table.
When you specify images in a table, each row in the table corresponds to an observation.
For image input, the predictors must be in the first column of the table, specified as one of the following:
Absolute or relative file path to an image, specified as a character vector
1-by-1 cell array containing a h-by-w-by-c numeric array representing a 2-D image, where h, w, and c correspond to the height, width, and number of channels of the image, respectively
Tip
To input complex-valued data into a neural network, the
SplitComplexInputs
option of the input layer must be
1
.
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| table
Complex Number Support: Yes
sequences
— Sequence or time series data
datastore | cell array of numeric arrays | numeric array
Sequence or time series data, specified as one of the following.
Data Type | Description | Example Usage | |
---|---|---|---|
Datastore | TransformedDatastore | Datastore that transforms batches of data read from an underlying datastore using a custom transformation function |
|
CombinedDatastore | Datastore that reads from two or more underlying datastores |
| |
Custom mini-batch datastore | Custom datastore that returns mini-batches of data | Make predictions using data in a format that other datastores do not support. For details, see Develop Custom Mini-Batch Datastore. | |
Numeric or cell array | A single sequence specified as a numeric array or a data set of sequences specified as cell array of numeric arrays | Make predictions using data that fits in memory and does not require additional processing like custom transformations. |
Datastore
Datastores read mini-batches of sequences and responses. Use datastores when you have data that does not fit in memory or when you want to apply transformations to the data.
These datastores are directly compatible with classify
for sequence data:
Custom mini-batch datastore. For details, see Develop Custom Mini-Batch Datastore.
You can use other built-in datastores for making predictions by using
the transform
and combine
functions. These functions can convert the data read from
datastores to the table or cell array format required by
classify
. For example, you can transform and combine
data read from in-memory arrays and CSV files using an
ArrayDatastore
and an TabularTextDatastore
object, respectively.
The datastore must return data in a table or cell array. Custom mini-batch datastores must output tables.
Datastore Output | Example Output |
---|---|
Table | data = read(ds) data = 4×2 table Predictors __________________ {12×50 double} {12×50 double} {12×50 double} {12×50 double} |
Cell array | data = read(ds) data = 4×2 cell array {12×50 double} {12×50 double} {12×50 double} {12×50 double} |
The format of the predictors depends on the type of data.
Data | Format of Predictors |
---|---|
Vector sequence | c-by-s matrix, where c is the number of features of the sequence and s is the sequence length |
1-D image sequence | h-by-c-by-s array, where h and c correspond to the height and number of channels of the image, respectively, and s is the sequence length. Each sequence in the mini-batch must have the same sequence length. |
2-D image sequence | h-by-w-by-c-by-s array, where h, w, and c correspond to the height, width, and number of channels of the image, respectively, and s is the sequence length. Each sequence in the mini-batch must have the same sequence length. |
3-D image sequence | h-by-w-by-d-by-c-by-s array, where h, w, d, and c correspond to the height, width, depth, and number of channels of the image, respectively, and s is the sequence length. Each sequence in the mini-batch must have the same sequence length. |
For predictors returned in tables, the elements must contain a numeric scalar, a numeric row vector, or a 1-by-1 cell array containing a numeric array.
For more information, see Datastores for Deep Learning.
Numeric or Cell Array
For data that fits in memory and does not require additional processing like custom transformations, you can specify a single sequence as a numeric array or a data set of sequences as a cell array of numeric arrays.
For cell array input, the cell array must be an N-by-1 cell array of numeric arrays, where N is the number of observations. The size and shape of the numeric array representing a sequence depends on the type of sequence data.
Input | Description |
---|---|
Vector sequences | c-by-s matrices, where c is the number of features of the sequences and s is the sequence length |
1-D image sequences | h-by-c-by-s arrays, where h and c correspond to the height and number of channels of the images, respectively, and s is the sequence length |
2-D image sequences | h-by-w-by-c-by-s arrays, where h, w, and c correspond to the height, width, and number of channels of the images, respectively, and s is the sequence length |
3-D image sequences | h-by-w-by-d-by-c-by-s, where h, w, d, and c correspond to the height, width, depth, and number of channels of the 3-D images, respectively, and s is the sequence length |
Tip
To input complex-valued data into a neural network, the
SplitComplexInputs
option of the input layer must be
1
.
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| cell
Complex Number Support: Yes
features
— Feature data
datastore | numeric array | table
Feature data, specified as one of the following.
Data Type | Description | Example Usage | |
---|---|---|---|
Datastore | TransformedDatastore | Datastore that transforms batches of data read from an underlying datastore using a custom transformation function |
|
CombinedDatastore | Datastore that reads from two or more underlying datastores |
| |
Custom mini-batch datastore | Custom datastore that returns mini-batches of data | Make predictions using data in a format that other datastores do not support. For details, see Develop Custom Mini-Batch Datastore. | |
Table | Feature data specified as a table | Make predictions using data stored in a table. | |
Numeric array | Feature data specified as numeric array | Make predictions using data that fits in memory and does not require additional processing like custom transformations. |
Datastore
Datastores read mini-batches of feature data and responses. Use datastores when you have data that does not fit in memory or when you want to apply transformations to the data.
These datastores are directly compatible with classify
for feature data:
Custom mini-batch datastore. For details, see Develop Custom Mini-Batch Datastore.
You can use other built-in datastores for making predictions by using the transform
and
combine
functions. These functions can convert the data read from datastores to the table or cell
array format required by classify
. For more information, see Datastores for Deep Learning.
For networks with multiple inputs, the datastore must be a TransformedDatastore
or CombinedDatastore
object.
The datastore must return data in a table or a cell array. Custom mini-batch datastores must output tables. The format of the datastore output depends on the network architecture.
Network Architecture | Datastore Output | Example Output |
---|---|---|
Single input layer | Table or cell array with at least one column, where the first column specifies the predictors. Table elements must be scalars, row vectors, or 1-by-1 cell arrays containing a numeric array. Custom mini-batch datastores must output tables. | Table for network with one input: data = read(ds) data = 4×2 table Predictors __________________ {24×1 double} {24×1 double} {24×1 double} {24×1 double} |
Cell array for network with one input: data = read(ds) data = 4×1 cell array {24×1 double} {24×1 double} {24×1 double} {24×1 double} | ||
Multiple input layers | Cell array with at least The first The order of inputs is given by the | Cell array for network with two inputs: data = read(ds) data = 4×3 cell array {24×1 double} {28×1 double} {24×1 double} {28×1 double} {24×1 double} {28×1 double} {24×1 double} {28×1 double} |
The predictors must be c-by-1 column vectors, where c is the number of features.
For more information, see Datastores for Deep Learning.
Table
For feature data that fits in memory and does not require additional processing like custom transformations, you can specify feature data and responses as a table.
Each row in the table corresponds to an observation. The arrangement of predictors in the table columns depends on the type of task.
Task | Predictors |
---|---|
Feature classification | Features specified in one or more columns as scalars. |
Numeric Array
For feature data that fits in memory and does not require additional processing like custom transformations, you can specify feature data as a numeric array.
The numeric array must be an N-by-numFeatures
numeric array, where N is the number of observations and numFeatures
is the number of features of the input data.
Tip
To input complex-valued data into a neural network, the
SplitComplexInputs
option of the input layer must be
1
.
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| table
Complex Number Support: Yes
X1,...,XN
— Numeric or cell arrays for networks with multiple inputs
numeric array | cell array
Numeric or cell arrays for networks with multiple inputs.
For image, sequence, and feature predictor input, the format of the predictors must match the formats described in the images
, sequences
, or features
argument descriptions, respectively.
For an example showing how to train a network with multiple inputs, see Train Network on Image and Feature Data.
To input complex-valued data into a neural network, the
SplitComplexInputs
option of the input layer must be
1
.
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| cell
Complex Number Support: Yes
mixed
— Mixed data
TransformedDatastore
| CombinedDatastore
| custom mini-batch datastore
Mixed data, specified as one of the following.
Data Type | Description | Example Usage |
---|---|---|
TransformedDatastore | Datastore that transforms batches of data read from an underlying datastore using a custom transformation function |
|
CombinedDatastore | Datastore that reads from two or more underlying datastores |
|
Custom mini-batch datastore | Custom datastore that returns mini-batches of data | Make predictions using data in a format that other datastores do not support. For details, see Develop Custom Mini-Batch Datastore. |
You can use other built-in datastores for making predictions by using the transform
and combine
functions. These functions can convert the data read from datastores to the table or cell array format required by classify
. For more information, see Datastores for Deep Learning.
The datastore must return data in a table or a cell array. Custom mini-batch datastores must output tables. The format of the datastore output depends on the network architecture.
Datastore Output | Example Output |
---|---|
Cell array with The order of inputs is given by the | data = read(ds) data = 4×3 cell array {24×1 double} {28×1 double} {24×1 double} {28×1 double} {24×1 double} {28×1 double} {24×1 double} {28×1 double} |
For image, sequence, and feature predictor input, the format of the predictors must match the formats described in the images
, sequences
, or features
argument descriptions, respectively.
For an example showing how to train a network with multiple inputs, see Train Network on Image and Feature Data.
Tip
To convert a numeric array to a datastore, use arrayDatastore
.
Name-Value Arguments
Specify optional pairs of arguments as
Name1=Value1,...,NameN=ValueN
, where Name
is
the argument name and Value
is the corresponding value.
Name-value arguments must appear after other arguments, but the order of the
pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose
Name
in quotes.
Example: MiniBatchSize=256
specifies the mini-batch size as
256.
MiniBatchSize
— Size of mini-batches
128
(default) | positive integer
Size of mini-batches to use for prediction, specified as a positive integer. Larger mini-batch sizes require more memory, but can lead to faster predictions.
When you make predictions with sequences of different lengths,
the mini-batch size can impact the amount of padding added to the input data, which can result
in different predicted values. Try using different values to see which works best with your
network. To specify mini-batch size and padding options, use the MiniBatchSize
and SequenceLength
options, respectively.
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
Acceleration
— Performance optimization
"auto"
(default) | "mex"
| "none"
Performance optimization, specified as one of the following:
"auto"
— Automatically apply a number of optimizations suitable for the input network and hardware resources."mex"
— Compile and execute a MEX function. This option is available only when you use a GPU. Using a GPU requires a Parallel Computing Toolbox license and a supported GPU device. For information about supported devices, see GPU Computing Requirements (Parallel Computing Toolbox). If Parallel Computing Toolbox or a suitable GPU is not available, then the software returns an error."none"
— Disable all acceleration.
If Acceleration
is "auto"
, then MATLAB® applies a number of compatible optimizations and does not generate a MEX
function.
The "auto"
and "mex"
options can offer performance
benefits at the expense of an increased initial run time. Subsequent calls with
compatible parameters are faster. Use performance optimization when you plan to call the
function multiple times using new input data.
The "mex"
option generates and executes a MEX function based on the network
and parameters used in the function call. You can have several MEX functions associated
with a single network at one time. Clearing the network variable also clears any MEX
functions associated with that network.
The "mex"
option supports networks that contain the layers listed
on the Supported Layers (GPU Coder) page, except for
sequenceInputLayer
objects.
The "mex"
option is available when you use a single GPU.
To use the "mex"
option, you must have a C/C++ compiler installed
and the GPU Coder™ Interface for Deep Learning support package. Install the support package using the Add-On Explorer in
MATLAB. For setup instructions, see MEX Setup (GPU Coder). GPU Coder is not required.
For quantized networks, the "mex"
option requires a CUDA® enabled NVIDIA® GPU with compute capability 6.1, 6.3, or higher.
MATLAB
Compiler™ does not support deploying networks when you use the
"mex"
option.
ExecutionEnvironment
— Hardware resource
"auto"
(default) | "gpu"
| "cpu"
| "multi-gpu"
| "parallel"
Hardware resource, specified as one of the following:
"auto"
— Use a GPU if one is available; otherwise, use the CPU."gpu"
— Use the GPU. Using a GPU requires a Parallel Computing Toolbox license and a supported GPU device. For information about supported devices, see GPU Computing Requirements (Parallel Computing Toolbox). If Parallel Computing Toolbox or a suitable GPU is not available, then the software returns an error."cpu"
— Use the CPU."multi-gpu"
— Use multiple GPUs on one machine, using a local parallel pool based on your default cluster profile. If there is no current parallel pool, the software starts a parallel pool with pool size equal to the number of available GPUs."parallel"
— Use a local or remote parallel pool based on your default cluster profile. If there is no current parallel pool, the software starts one using the default cluster profile. If the pool has access to GPUs, then only workers with a unique GPU perform computation. If the pool does not have GPUs, then computation takes place on all available CPU workers instead.
For more information on when to use the different execution environments, see Scale Up Deep Learning in Parallel, on GPUs, and in the Cloud.
The "gpu"
, "multi-gpu"
, and
"parallel"
options require Parallel Computing Toolbox. To use a GPU for deep
learning, you must also have a supported GPU device. For information on supported devices, see
GPU Computing Requirements (Parallel Computing Toolbox). If you choose one of these options and Parallel Computing Toolbox or a suitable GPU is not available, then the software returns an
error.
To make predictions in parallel with networks with recurrent layers (by setting
ExecutionEnvironment
to either "multi-gpu"
or "parallel"
), the SequenceLength
option must
be "shortest"
or "longest"
.
Networks with custom layers that contain State
parameters do not
support making predictions in parallel.
SequenceLength
— Option to pad or truncate sequences
"longest"
(default) | "shortest"
| positive integer
Option to pad, truncate, or split input sequences, specified as one of the following:
"longest"
— Pad sequences in each mini-batch to have the same length as the longest sequence. This option does not discard any data, though padding can introduce noise to the neural network."shortest"
— Truncate sequences in each mini-batch to have the same length as the shortest sequence. This option ensures that no padding is added, at the cost of discarding data.Positive integer — For each mini-batch, pad the sequences to the length of the longest sequence in the mini-batch, and then split the sequences into smaller sequences of the specified length. If splitting occurs, then the software creates extra mini-batches. If the specified sequence length does not evenly divide the sequence lengths of the data, then the mini-batches containing the ends those sequences have length shorter than the specified sequence length. Use this option if the full sequences do not fit in memory. Alternatively, try reducing the number of sequences per mini-batch by setting the
MiniBatchSize
option to a lower value.This option supports the
trainNetwork
function only.
To learn more about the effect of padding, truncating, and splitting the input sequences, see Sequence Padding, Truncation, and Splitting.
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| char
| string
SequencePaddingDirection
— Direction of padding or truncation
"right"
(default) | "left"
Direction of padding or truncation, specified as one of the following:
"right"
— Pad or truncate sequences on the right. The sequences start at the same time step and the software truncates or adds padding to the end of the sequences."left"
— Pad or truncate sequences on the left. The software truncates or adds padding to the start of the sequences so that the sequences end at the same time step.
Because recurrent layers process sequence data one time step at a time, when the recurrent
layer OutputMode
property is "last"
, any padding in
the final time steps can negatively influence the layer output. To pad or truncate sequence
data on the left, set the SequencePaddingDirection
option to "left"
.
For sequence-to-sequence neural networks (when the OutputMode
property is
"sequence"
for each recurrent layer), any padding in the first time
steps can negatively influence the predictions for the earlier time steps. To pad or
truncate sequence data on the right, set the SequencePaddingDirection
option to "right"
.
To learn more about the effect of padding, truncating, and splitting the input sequences, see Sequence Padding, Truncation, and Splitting.
SequencePaddingValue
— Value to pad sequences
0
(default) | scalar
Value by which to pad input sequences, specified as a scalar.
Do not pad sequences with NaN
, because doing so can propagate
errors throughout the neural network.
Data Types: single
| double
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
Output Arguments
Y
— Predicted class labels
categorical vector | cell array of categorical vectors
Predicted class labels, returned as a categorical vector or a cell array
of categorical vectors. The format of Y
depends on the
type of task.
The following table describes the format for classification tasks.
Task | Format |
---|---|
Image or feature classification | N-by-1 categorical vector of labels, where N is the number of observations |
Sequence-to-label classification | |
Sequence-to-sequence classification | N-by-1 cell array of categorical sequences of labels, where
N is the number of
observations. Each sequence has the same number of
time steps as the corresponding input sequence
after the For
sequence-to-sequence classification tasks with one
observation, |
scores
— Predicted class scores
matrix | cell array of matrices
Predicted scores or responses, returned as a matrix or a cell array of
matrices. The format of scores
depends on the type of
task.
The following table describes the format of
scores
.
Task | Format |
---|---|
Image classification | N-by-K matrix, where N is the number of observations and K is the number of classes |
Sequence-to-label classification | |
Feature classification | |
Sequence-to-sequence classification | N-by-1 cell array of matrices, where N is the
number of observations. The sequences are matrices with K
rows, where K is the number of classes. Each sequence has
the same number of time steps as the corresponding input sequence after the
|
For sequence-to-sequence classification tasks with one observation,
sequences
can be a matrix. In this case,
scores
is a matrix of predicted class
scores.
For an example exploring classification scores, see Classify Webcam Images Using Deep Learning.
Algorithms
Floating-Point Arithmetic
When you train a neural network using the trainnet
or
trainNetwork
functions, or when you use prediction or validation functions
with DAGNetwork
and
SeriesNetwork
objects, the software performs these computations using single-precision, floating-point
arithmetic. Functions for prediction and validation include predict
,
classify
, and
activations
.
The software uses single-precision arithmetic when you train neural networks using both CPUs
and GPUs.
Reproducibility
To provide the best performance, deep learning using a GPU in MATLAB is not guaranteed to be deterministic. Depending on your network architecture, under some conditions you might get different results when using a GPU to train two identical networks or make two predictions using the same network and data.
Alternatives
To classify data using a network with multiple output layers, use the predict
function and set the ReturnCategorical
option to 1
(true).
To compute the predicted classification scores, you can also use the predict
function.
To compute the activations from a network layer, use the activations
function.
For recurrent networks such as LSTM networks, you can make predictions and update the
network state using classifyAndUpdateState
and predictAndUpdateState
.
References
[1] Kudo, Mineichi, Jun Toyama, and Masaru Shimbo. “Multidimensional Curve Classification Using Passing-through Regions.” Pattern Recognition Letters 20, no. 11–13 (November 1999): 1103–11. https://doi.org/10.1016/S0167-8655(99)00077-X.
[2] UCI Machine Learning Repository: Japanese Vowels Dataset. https://archive.ics.uci.edu/ml/datasets/Japanese+Vowels.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
C++ code generation supports the following syntaxes:
[Y,scores] = classify(net,images)
, whereimages
is a numeric array[Y,scores] = classify(net,sequences)
, wheresequences
is a cell array[Y,scores] = classify(net,features)
, wherefeatures
is a numeric array[Y,scores] = classify(__,Name=Value)
using any of the previous syntaxes.
C++ code generation for the
classify
function is not supported for regression networks and networks with multiple outputs.For vector sequence inputs, the number of features must be a constant during code generation. The sequence length can be variable sized.
For image sequence inputs, the height, width, and the number of channels must be a constant during code generation.
Only the
MiniBatchSize
,SequenceLength
,SequencePaddingDirection
, andSequencePaddingValue
name-value pair arguments are supported for code generation. All name-value pairs must be compile-time constants.Only the
"longest"
and"shortest"
option of theSequenceLength
name-value pair is supported for code generation.If you use a GCC C/C++ compiler version 8.2 or above, you might get a
-Wstringop-overflow
warning.Code generation for Intel® MKL-DNN target does not support the combination of
SequenceLength="longest"
,SequencePaddingDirection="left"
, andSequencePaddingValue=0
name-value arguments.
GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.
Usage notes and limitations:
GPU code generation supports the following syntaxes:
Y = classify(net,images)
, whereimages
is a numeric arrayY = classify(net,sequences)
, wheresequences
is a cell array or numeric arrayY = classify(net,features)
, wherefeatures
is a numeric array[Y,scores] = classify(__)
using any of the previous syntaxes.[Y,scores] = classify(__,Name=Value)
using any of the previous syntaxes.
GPU code generation for the
classify
function is not supported for regression networks and networks with multiple outputs.GPU code generation does not support
gpuArray
inputs to theclassify
function.The cuDNN library supports vector and 2-D image sequences. The TensorRT library support only vector input sequences. The ARM®
Compute Library
for GPU does not support recurrent networks.For vector sequence inputs, the number of features must be a constant during code generation. The sequence length can be variable sized.
For image sequence inputs, the height, width, and the number of channels must be a constant during code generation.
Only the
MiniBatchSize
,SequenceLength
,SequencePaddingDirection
, andSequencePaddingValue
name-value pair arguments are supported for code generation. All name-value pairs must be compile-time constants.Only the
"longest"
and"shortest"
option of theSequenceLength
name-value pair is supported for code generation.GPU code generation for the
classify
function supports inputs that are defined as half-precision floating point data types. For more information, seehalf
(GPU Coder).If you use a GCC C/C++ compiler version 8.2 or above, you might get a
-Wstringop-overflow
warning.
Automatic Parallel Support
Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
To run computations in parallel, set the ExecutionEnvironment
option to "multi-gpu"
or "parallel"
.
For details, see Scale Up Deep Learning in Parallel, on GPUs, and in the Cloud.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
The
ExecutionEnvironment
option must be"auto"
or"gpu"
when the input data is:A
gpuArray
A cell array containing
gpuArray
objectsA table containing
gpuArray
objectsA datastore that outputs cell arrays containing
gpuArray
objectsA datastore that outputs tables containing
gpuArray
objects
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Version History
Introduced in R2016aR2022b: Prediction functions pad mini-batches to length of longest sequence before splitting when you specify SequenceLength
option as an integer
Starting in R2022b, when you make predictions with sequence data using the predict
, classify
, predictAndUpdateState
, classifyAndUpdateState
, and activations
functions and the SequenceLength
option is an integer, the software pads sequences to the length of the longest sequence in each mini-batch and then splits the sequences into mini-batches with the specified sequence length. If SequenceLength
does not evenly divide the sequence length of the mini-batch, then the last split mini-batch has a length shorter than SequenceLength
. This behavior prevents time steps that contain only padding values from influencing predictions.
In previous releases, the software pads mini-batches of sequences to have a length matching the nearest multiple of SequenceLength
that is greater than or equal to the mini-batch length and then splits the data. To reproduce this behavior, manually pad the input data such that the mini-batches have the length of the appropriate multiple of SequenceLength
. For sequence-to-sequence workflows, you may also need to manually remove time steps of the output that correspond to padding values.
Open Example
You have a modified version of this example. Do you want to open this example with your edits?
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other bat365 country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)