classify

Classify data using a trained deep learning neural network

Description

You can make predictions using a trained neural network for deep learning on either a CPU or GPU. Using a GPU requires Parallel Computing Toolbox™ and a CUDA® enabled NVIDIA® GPU with compute capability 3.0 or higher. Specify the hardware requirements using the ExecutionEnvironment name-value pair argument.

For networks with multiple outputs, use the predict and set the 'ReturnCategorial' option to true.

YPred = classify(net,imds) predicts class labels for the images in the image datastore imds using the trained network net.

YPred = classify(net,ds) predicts class labels for the data in the datastore ds.

example

YPred = classify(net,X) predicts class labels for the image or feature data specified by the numeric array X.

YPred = classify(net,X1,...,XN) predicts class labels for the data in the numeric arrays X1, …, XN for the mutli-input network net. The input Xi corresponds to the network input net.InputNames(i).

example

YPred = classify(net,sequences) predicts class labels for the time series or sequence data in sequences for the recurrent network (for example, an LSTM or GRU network) net.

example

YPred = classify(net,tbl) predicts class labels for the data in the table tbl.

example

YPred = classify(___,Name,Value) predicts class labels with additional options specified by one or more name-value pair arguments using any of the previous syntaxes.

[YPred,scores] = classify(___) also returns the classification scores corresponding to the class labels using any of the previous syntaxes.

Tip

When making 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

collapse all

Load the sample data.

[XTrain,YTrain] = digitTrain4DArrayData;

digitTrain4DArrayData loads the digit training set as 4-D array data. XTrain is a 28-by-28-by-1-by-5000 array, where 28 is the height and 28 is the width of the images. 1 is the number of channels and 5000 is the number of synthetic images of handwritten digits. YTrain is a categorical vector containing the labels for each observation.

Construct the convolutional neural network architecture.

layers = [ ...
    imageInputLayer([28 28 1])
    convolution2dLayer(5,20)
    reluLayer
    maxPooling2dLayer(2,'Stride',2)
    fullyConnectedLayer(10)
    softmaxLayer
    classificationLayer];

Set the options to default settings for the stochastic gradient descent with momentum.

options = trainingOptions('sgdm');

Train the network.

rng('default')
net = trainNetwork(XTrain,YTrain,layers,options);
Training on single CPU.
Initializing input data normalization.
|========================================================================================|
|  Epoch  |  Iteration  |  Time Elapsed  |  Mini-batch  |  Mini-batch  |  Base Learning  |
|         |             |   (hh:mm:ss)   |   Accuracy   |     Loss     |      Rate       |
|========================================================================================|
|       1 |           1 |       00:00:00 |       10.16% |       2.3195 |          0.0100 |
|       2 |          50 |       00:00:02 |       50.78% |       1.7102 |          0.0100 |
|       3 |         100 |       00:00:03 |       63.28% |       1.1632 |          0.0100 |
|       4 |         150 |       00:00:05 |       60.16% |       1.0859 |          0.0100 |
|       6 |         200 |       00:00:07 |       68.75% |       0.8996 |          0.0100 |
|       7 |         250 |       00:00:09 |       76.56% |       0.7919 |          0.0100 |
|       8 |         300 |       00:00:11 |       73.44% |       0.8411 |          0.0100 |
|       9 |         350 |       00:00:12 |       81.25% |       0.5514 |          0.0100 |
|      11 |         400 |       00:00:14 |       90.62% |       0.4744 |          0.0100 |
|      12 |         450 |       00:00:16 |       92.19% |       0.3614 |          0.0100 |
|      13 |         500 |       00:00:18 |       94.53% |       0.3159 |          0.0100 |
|      15 |         550 |       00:00:20 |       96.09% |       0.2543 |          0.0100 |
|      16 |         600 |       00:00:21 |       92.19% |       0.2765 |          0.0100 |
|      17 |         650 |       00:00:23 |       95.31% |       0.2461 |          0.0100 |
|      18 |         700 |       00:00:25 |       99.22% |       0.1418 |          0.0100 |
|      20 |         750 |       00:00:26 |       98.44% |       0.1000 |          0.0100 |
|      21 |         800 |       00:00:27 |       98.44% |       0.1448 |          0.0100 |
|      22 |         850 |       00:00:29 |       98.44% |       0.0989 |          0.0100 |
|      24 |         900 |       00:00:30 |       96.88% |       0.1316 |          0.0100 |
|      25 |         950 |       00:00:32 |      100.00% |       0.0859 |          0.0100 |
|      26 |        1000 |       00:00:33 |      100.00% |       0.0701 |          0.0100 |
|      27 |        1050 |       00:00:35 |      100.00% |       0.0759 |          0.0100 |
|      29 |        1100 |       00:00:36 |       99.22% |       0.0663 |          0.0100 |
|      30 |        1150 |       00:00:38 |       98.44% |       0.0775 |          0.0100 |
|      30 |        1170 |       00:00:39 |       99.22% |       0.0732 |          0.0100 |
|========================================================================================|

Run the trained network on a test set.

[XTest,YTest]= digitTest4DArrayData;
YPred = classify(net,XTest);

Display the first 10 images in the test data and compare to the classification from classify.

[YTest(1:10,:) YPred(1:10,:)]
ans = 10x2 categorical
     0      0 
     0      0 
     0      0 
     0      0 
     0      0 
     0      0 
     0      0 
     0      0 
     0      0 
     0      0 

The results from classify match the true digits for the first ten images.

Calculate the accuracy over all test data.

accuracy = sum(YPred == YTest)/numel(YTest)
accuracy = 0.9820

Load pretrained network. JapaneseVowelsNet is a pretrained LSTM network trained on the Japanese Vowels dataset as described in [1] and [2]. It was trained on the sequences sorted by sequence length with a mini-batch size of 27.

load JapaneseVowelsNet

View the network architecture.

net.Layers
ans = 
  5x1 Layer array with layers:

     1   'sequenceinput'   Sequence Input          Sequence input with 12 dimensions
     2   'lstm'            LSTM                    LSTM with 100 hidden units
     3   'fc'              Fully Connected         9 fully connected layer
     4   'softmax'         Softmax                 softmax
     5   'classoutput'     Classification Output   crossentropyex with '1' and 8 other classes

Load the test data.

[XTest,YTest] = japaneseVowelsTestData;

Classify the test data.

YPred = classify(net,XTest);

View the labels of the first 10 sequences with their predicted labels.

[YTest(1:10) YPred(1:10)]
ans = 10x2 categorical
     1      1 
     1      1 
     1      1 
     1      1 
     1      1 
     1      1 
     1      1 
     1      1 
     1      1 
     1      1 

Calculate the classification accuracy of the predictions.

accuracy = sum(YPred == YTest)/numel(YTest)
accuracy = 0.8595

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.mat

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. In this data set, there are two categorical features with names "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 to insert 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)
ans=8×23 table
    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  

Predict the labels of the test data using the trained network and calculate the accuracy. Specify the same mini-batch size used for training.

YPred = classify(net,tbl(:,1:end-1));

Calculate the classification accuracy. The accuracy is the proportion of the labels that the network predicts correctly.

YTest = tbl{:,labelName};
accuracy = sum(YPred == YTest)/numel(YTest)
accuracy = 0.9952

Input Arguments

collapse all

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.

Image datastore, specified as an ImageDatastore object.

ImageDatastore allows batch reading of JPG or PNG image files using prefetching. If you use a custom function for reading the images, then ImageDatastore does not prefetch.

Tip

Use augmentedImageDatastore for efficient preprocessing of images for deep learning including image resizing.

Do not use the readFcn option of imageDatastore for preprocessing or resizing as this option is usually significantly slower.

Datastore for out-of-memory data and preprocessing. The datastore must return data in a table or a cell array. The format of the datastore output depends on the network architecture.

Network ArchitectureDatastore OutputExample 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 numInputs columns, where numInputs is the number of network inputs.

The first numInputs columns specify the predictors for each input.

The order of inputs is given by the InputNames property of the network.

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 depend on the type of data.

DataFormat of Predictors
2-D image

h-by-w-by-c numeric array, where h, w, and c are the height, width, and number of channels of the image, respectively.

3-D image

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 image, respectively.

Vector sequence

c-by-s matrix, where c is the number of features of the sequence and s is the 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.

Features

c-by-1 column vector, where c is the number of features.

For more information, see Datastores for Deep Learning.

Image or feature data, specified as a numeric array. The size of the array depends on the type of input:

InputDescription
2-D imagesA 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 imagesA 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.
FeaturesA N-by-numFeatures numeric array, where N is the number of observations and numFeatures is the number of features of the input data.

If the array contains NaNs, then they are propagated through the network.

For networks with multiple inputs, you can specify multiple arrays X1, …, XN, where N is the number of network inputs and the input Xi corresponds to the network input net.InputNames(i).

Sequence or time series data, specified as an N-by-1 cell array of numeric arrays, where N is the number of observations, a numeric array representing a single sequence, or a datastore.

For cell array or numeric array input, the dimensions of the numeric arrays containing the sequences depend on the type of data.

InputDescription
Vector sequencesc-by-s matrices, where c is the number of features of the sequences and s is the sequence length.
2-D image sequencesh-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 sequencesh-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.

For datastore input, the datastore must return data as a cell array of sequences or a table whose first column contains sequences. The dimensions of the sequence data must correspond to the table above.

Table of image or feature data. Each row in the table corresponds to an observation.

The arrangement of predictors in the table columns depend on the type of input data.

InputPredictors
Image data
  • Absolute or relative file path to an image, specified as a character vector in a single column

  • Image specified as a 3-D numeric array

Specify predictors in a single column.

Feature data

Numeric scalar.

Specify predictors in numFeatures columns of the table, where numFeatures is the number of features of the input data.

This argument supports networks with a single input only.

Data Types: table

Name-Value Pair Arguments

Example: 'MiniBatchSize','256' specifies the mini-batch size as 256.

Specify optional comma-separated pair of Name,Value argument. Name is the argument name and Value is the corresponding value. Name must appear inside single quotes (' ').

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 making 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.

Example: 'MiniBatchSize',256

Performance optimization, specified as the comma-separated pair consisting of 'Acceleration' and one of the following:

  • 'auto' — Automatically apply a number of optimizations suitable for the input network and hardware resource.

  • 'mex' — Compile and execute a MEX function. This option is available when using a GPU only. Using a GPU requires Parallel Computing Toolbox and a CUDA enabled NVIDIA GPU with compute capability 3.0 or higher. If Parallel Computing Toolbox or a suitable GPU is not available, then the software returns an error.

  • 'none' — Disable all acceleration.

The default option is 'auto'. If 'auto' is specified, MATLAB® will apply a number of compatible optimizations. If you use the 'auto' option, MATLAB does not ever generate a MEX function.

Using the 'Acceleration' options 'auto' and 'mex' can offer performance benefits, but 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 is only available when you are using a GPU. You must have a C/C++ compiler installed and the GPU Coder™ Interface for Deep Learning Libraries 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.

The 'mex' option does not support all layers. For a list of supported layers, see Supported Layers (GPU Coder). Recurrent neural networks (RNNs) containing a sequenceInputLayer are not supported.

The 'mex' option does not support networks with multiple input layers or multiple output layers.

You cannot use MATLAB Compiler™ to deploy your network when using the 'mex' option.

Example: 'Acceleration','mex'

Hardware resource, specified as the comma-separated pair consisting of 'ExecutionEnvironment' and one of the following:

  • 'auto' — Use a GPU if one is available; otherwise, use the CPU.

  • 'gpu' — Use the GPU. Using a GPU requires Parallel Computing Toolbox and a CUDA enabled NVIDIA GPU with compute capability 3.0 or higher. If Parallel Computing Toolbox or a suitable GPU is not available, then the software returns an error.

  • 'cpu' — Use the CPU.

Example: 'ExecutionEnvironment','cpu'

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 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 nearest multiple of the specified length that is greater than the longest sequence length 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. 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.

To learn more about the effect of padding, truncating, and splitting the input sequences, see Sequence Padding, Truncation, and Splitting.

Example: 'SequenceLength','shortest'

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 LSTM layers process sequence data one time step at a time, when the 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 networks (when the OutputMode property is 'sequence' for each LSTM 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.

Value by which to pad input sequences, specified as a scalar. The option is valid only when SequenceLength is 'longest' or a positive integer. Do not pad sequences with NaN, because doing so can propagate errors throughout the network.

Example: 'SequencePaddingValue',-1

Output Arguments

collapse all

Predicted class labels, returned as a categorical vector, or a cell array of categorical vectors. The format of YPred depends on the type of task.

The following table describes the format for classification tasks.

TaskFormat
Image or feature classificationN-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 applying the SequenceLength option to each mini-batch independently.

For sequence-to-sequence classification tasks with one observation, sequences can be a matrix. In this case, YPred is a categorical sequence of labels.

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.

TaskFormat
Image classificationN-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 applying the SequenceLength option to each mini-batch independently.

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

All functions for deep learning training, prediction, and validation in Deep Learning Toolbox™ perform computations using single-precision, floating-point arithmetic. Functions for deep learning include trainNetwork, predict, classify, and activations. The software uses single-precision arithmetic when you train networks using both CPUs and GPUs.

Alternatives

For networks with multiple outputs, use the predict and set the 'ReturnCategorial' option to true.

You can compute the predicted scores from a trained network using predict.

You can also compute the activations from a network layer using activations.

For sequence-to-label and sequence-to-sequence classification networks, you can make predictions and update the network state using classifyAndUpdateState and predictAndUpdateState.

References

[1] M. Kudo, J. Toyama, and M. Shimbo. "Multidimensional Curve Classification Using Passing-Through Regions." Pattern Recognition Letters. Vol. 20, No. 11–13, pages 1103–1111.

[2] UCI Machine Learning Repository: Japanese Vowels Dataset. https://archive.ics.uci.edu/ml/datasets/Japanese+Vowels

Extended Capabilities

Introduced in R2016a