This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

classify

Classify data using a trained deep learning neural network

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.

Syntax

[YPred,scores] = classify(net,X)
[YPred,scores] = classify(net,sequences)
[YPred,scores] = classify(___,Name,Value)

Description

example

[YPred,scores] = classify(net,X) predicts class labels for the image data in X using the trained network, net.

example

[YPred,scores] = classify(net,sequences) predicts class labels for the time series or sequence data in sequences using the trained LSTM network, net.

example

[YPred,scores] = classify(___,Name,Value) predicts class labels with additional options specified by one or more name-value pair arguments.

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 image normalization.
|========================================================================================|
|  Epoch  |  Iteration  |  Time Elapsed  |  Mini-batch  |  Mini-batch  |  Base Learning  |
|         |             |   (hh:mm:ss)   |   Accuracy   |     Loss     |      Rate       |
|========================================================================================|
|       1 |           1 |       00:00:00 |        7.81% |       2.3026 |          0.0100 |
|       2 |          50 |       00:00:04 |       33.59% |       2.2735 |          0.0100 |
|       3 |         100 |       00:00:08 |       48.44% |       1.6613 |          0.0100 |
|       4 |         150 |       00:00:16 |       64.06% |       1.1803 |          0.0100 |
|       6 |         200 |       00:00:23 |       64.06% |       1.0499 |          0.0100 |
|       7 |         250 |       00:00:31 |       76.56% |       0.8392 |          0.0100 |
|       8 |         300 |       00:00:39 |       77.34% |       0.6981 |          0.0100 |
|       9 |         350 |       00:00:47 |       77.34% |       0.7084 |          0.0100 |
|      11 |         400 |       00:00:53 |       87.50% |       0.4902 |          0.0100 |
|      12 |         450 |       00:00:57 |       91.41% |       0.3839 |          0.0100 |
|      13 |         500 |       00:01:01 |       92.19% |       0.2986 |          0.0100 |
|      15 |         550 |       00:01:05 |       93.75% |       0.2583 |          0.0100 |
|      16 |         600 |       00:01:10 |       97.66% |       0.2009 |          0.0100 |
|      17 |         650 |       00:01:17 |       92.97% |       0.2642 |          0.0100 |
|      18 |         700 |       00:01:24 |       97.66% |       0.1448 |          0.0100 |
|      20 |         750 |       00:01:31 |       96.88% |       0.1314 |          0.0100 |
|      21 |         800 |       00:01:38 |       97.66% |       0.1233 |          0.0100 |
|      22 |         850 |       00:01:42 |       98.44% |       0.1009 |          0.0100 |
|      24 |         900 |       00:01:46 |      100.00% |       0.1051 |          0.0100 |
|      25 |         950 |       00:01:49 |       97.66% |       0.1483 |          0.0100 |
|      26 |        1000 |       00:01:53 |       99.22% |       0.0743 |          0.0100 |
|      27 |        1050 |       00:01:57 |      100.00% |       0.0603 |          0.0100 |
|      29 |        1100 |       00:02:08 |       99.22% |       0.0769 |          0.0100 |
|      30 |        1150 |       00:02:15 |      100.00% |       0.0524 |          0.0100 |
|      30 |        1170 |       00:02:18 |      100.00% |       0.0566 |          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 array
     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.9770

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.

load JapaneseVowelsTest

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 array
     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

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 alexnet function) or by training your own network using trainNetwork.

Image data, specified as one of the following.

  • 3-D array representing a single image. X has size h-by-w-by-c, where h, w, and c correspond to the height, width, and the number of channels of the image, respectively.

  • 4-D array representing a stack of images. X has size h-by-w-by-c-by-N, where N is the number of images.

  • table, where the first column contains either paths to images, or 3-D arrays representing images.

  • ImageDatastore.

  • mini-batch datastore. For more information on built-in and custom mini-batch datastores, see Preprocess Images for Deep Learning.

Sequence or time series data, specified as a matrix representing a single time series, or a cell array of matrices representing multiple time series.

  • If sequences is a matrix representing a single time series, then sequences is a D-by-S matrix, where D is the number of data points per time step, and S is the number of time steps.

  • If sequences is a cell array of time series, then sequences is an N-by-1 cell array, where N is the number of observations. Each entry of sequences is a time series represented by a matrix, with rows corresponding to data points and columns corresponding to time steps.

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.

Example: 'MiniBatchSize',256

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.

  • 'shortest' — Truncate sequences in each mini-batch to have the same length as the shortest sequence.

  • Positive integer — Pad sequences in each mini-batch to have the same length as the longest sequence, then split into smaller sequences of the specified length. If splitting occurs, then the function creates extra mini-batches.

The function pads and truncates the sequences on the right. To learn more about the effect of padding, truncating, and splitting the input sequences, see Sequence Padding, Truncation, and Splitting.

Example: 'SequenceLength','shortest'

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

The following table describes the format for classification problems.

TaskFormat
Image 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.

For sequence-to-sequence classification problems 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 problem.

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
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 responses. Each sequence has the same number of time steps as the corresponding input sequence.

For sequence-to-sequence classification problems 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

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

Introduced in R2016a