Compute deep learning network layer activations
You can extract features using a trained deep learning network 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.
returns network activations with additional options specified by one or more
name-value pair arguments. For example, features
= activations(___,Name,Value
)'OutputAs','rows'
specifies the activation output format as 'rows'
. Specify
name-value pair arguments after all other input arguments.
This example shows how to extract learned image features from a pretrained convolutional neural network, and use those features to train an image classifier. Feature extraction is the easiest and fastest way to use the representational power of pretrained deep networks. For example, you can train a support vector machine (SVM) using fitcecoc
(Statistics and Machine Learning Toolbox™) on the extracted features. Because feature extraction only requires a single pass through the data, it is a good starting point if you do not have a GPU to accelerate network training with.
Load Data
Unzip and load the sample images as an image datastore. imageDatastore
automatically labels the images based on folder names and stores the data as an ImageDatastore
object. An image datastore lets you store large image data, including data that does not fit in memory. Split the data into 70% training and 30% test data.
unzip('MerchData.zip'); imds = imageDatastore('MerchData', ... 'IncludeSubfolders',true, ... 'LabelSource','foldernames'); [imdsTrain,imdsTest] = splitEachLabel(imds,0.7,'randomized');
There are now 55 training images and 20 validation images in this very small data set. Display some sample images.
numImagesTrain = numel(imdsTrain.Labels); idx = randperm(numImagesTrain,16); for i = 1:16 I{i} = readimage(imdsTrain,idx(i)); end figure imshow(imtile(I))
Load Pretrained Network
Load a pretrained AlexNet network. If the Deep Learning Toolbox Model for AlexNet Network support package is not installed, then the software provides a download link. AlexNet is trained on more than a million images and can classify images into 1000 object categories. For example, keyboard, mouse, pencil, and many animals. As a result, the model has learned rich feature representations for a wide range of images.
net = alexnet;
Display the network architecture. The network has five convolutional layers and three fully connected layers.
net.Layers
ans = 25x1 Layer array with layers: 1 'data' Image Input 227x227x3 images with 'zerocenter' normalization 2 'conv1' Convolution 96 11x11x3 convolutions with stride [4 4] and padding [0 0 0 0] 3 'relu1' ReLU ReLU 4 'norm1' Cross Channel Normalization cross channel normalization with 5 channels per element 5 'pool1' Max Pooling 3x3 max pooling with stride [2 2] and padding [0 0 0 0] 6 'conv2' Grouped Convolution 2 groups of 128 5x5x48 convolutions with stride [1 1] and padding [2 2 2 2] 7 'relu2' ReLU ReLU 8 'norm2' Cross Channel Normalization cross channel normalization with 5 channels per element 9 'pool2' Max Pooling 3x3 max pooling with stride [2 2] and padding [0 0 0 0] 10 'conv3' Convolution 384 3x3x256 convolutions with stride [1 1] and padding [1 1 1 1] 11 'relu3' ReLU ReLU 12 'conv4' Grouped Convolution 2 groups of 192 3x3x192 convolutions with stride [1 1] and padding [1 1 1 1] 13 'relu4' ReLU ReLU 14 'conv5' Grouped Convolution 2 groups of 128 3x3x192 convolutions with stride [1 1] and padding [1 1 1 1] 15 'relu5' ReLU ReLU 16 'pool5' Max Pooling 3x3 max pooling with stride [2 2] and padding [0 0 0 0] 17 'fc6' Fully Connected 4096 fully connected layer 18 'relu6' ReLU ReLU 19 'drop6' Dropout 50% dropout 20 'fc7' Fully Connected 4096 fully connected layer 21 'relu7' ReLU ReLU 22 'drop7' Dropout 50% dropout 23 'fc8' Fully Connected 1000 fully connected layer 24 'prob' Softmax softmax 25 'output' Classification Output crossentropyex with 'tench' and 999 other classes
The first layer, the image input layer, requires input images of size 227-by-227-by-3, where 3 is the number of color channels.
inputSize = net.Layers(1).InputSize
inputSize = 1×3
227 227 3
Extract Image Features
The network constructs a hierarchical representation of input images. Deeper layers contain higher-level features, constructed using the lower-level features of earlier layers. To get the feature representations of the training and test images, use activations
on the fully connected layer 'fc7'
. To get a lower-level representation of the images, use an earlier layer in the network.
The network requires input images of size 227-by-227-by-3, but the images in the image datastores have different sizes. To automatically resize the training and test images before they are input to the network, create augmented image datastores, specify the desired image size, and use these datastores as input arguments to activations
.
augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain); augimdsTest = augmentedImageDatastore(inputSize(1:2),imdsTest); layer = 'fc7'; featuresTrain = activations(net,augimdsTrain,layer,'OutputAs','rows'); featuresTest = activations(net,augimdsTest,layer,'OutputAs','rows');
Extract the class labels from the training and test data.
YTrain = imdsTrain.Labels; YTest = imdsTest.Labels;
Fit Image Classifier
Use the features extracted from the training images as predictor variables and fit a multiclass support vector machine (SVM) using fitcecoc
(Statistics and Machine Learning Toolbox).
mdl = fitcecoc(featuresTrain,YTrain);
Classify Test Images
Classify the test images using the trained SVM model and the features extracted from the test images.
YPred = predict(mdl,featuresTest);
Display four sample test images with their predicted labels.
idx = [1 5 10 15]; figure for i = 1:numel(idx) subplot(2,2,i) I = readimage(imdsTest,idx(i)); label = YPred(idx(i)); imshow(I) title(label) end
Calculate the classification accuracy on the test set. Accuracy is the fraction of labels that the network predicts correctly.
accuracy = mean(YPred == YTest)
accuracy = 1
This SVM has high accuracy. If the accuracy is not high enough using feature extraction, then try transfer learning instead.
net
— Trained networkSeriesNetwork
object | DAGNetwork
objectTrained 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
.
imds
— Image datastoreImageDatastore
objectImage 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.
Use augmentedImageDatastore
for efficient preprocessing of images for deep
learning including image resizing.
Do not use the readFcn
option of imageDatastore
as this option is usually significantly slower.
ds
— DatastoreDatastore of input data.
For networks with a single input, ds
can return either:
a single image or sequence
a cell array of images or sequences
a table, where the first column contains images or sequences
For networks with multiple image inputs layers, ds
must be a
combined or transformed datastore that returns a cell array with
numInputs
columns containing the input data, where
numInputs
is the number of network inputs. The
i
th element of the cell array corresponds to the input
net.InputNames(i)
.
For more information, see Datastores for Deep Learning.
X
— Image dataImage data, specified as a numeric array. The size of the array depends on the type of image input:
Input | Description |
---|---|
2-D images | A 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 | A 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. |
If the array contains NaN
s, then they are propagated through
the network.
For image input, if the 'OutputAs'
option is 'channels'
, then the images in the input data X
can be larger than the input size of the image input layer of the network. For other output formats, the images in X
must have the same size as the input size of the image input layer of the network.
sequences
— Sequence or time series dataSequence 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.
Input | Description |
---|---|
Vector sequences | c-by-s matrices, where c is the number of features of the sequences 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. |
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.
tbl
— Table of imagestable
Table of images containing the input data in the first column. Each row in the table corresponds to an observation. The table contains absolute or relative file paths to an image, specified as a character vector or images specified as a numeric array.
Data Types: table
layer
— Layer to extract features fromLayer to extract features from, specified as a numeric index or a character vector.
To compute the activations of a SeriesNetwork
object, specify the layer using its numeric
index, or as a character vector corresponding to the layer name.
To compute the activations of a DAGNetwork
object, specify the layer as the character vector
corresponding to the layer name. If the layer has multiple outputs, specify
the layer and output as the layer name, followed by the character “/”,
followed by the name of the layer output. That is,
layer
is of the form
'layerName/outputName'
.
Example: 3
Example: 'conv1'
Example: 'mpool/out'
Specify optional
comma-separated pairs of Name,Value
arguments. Name
is
the argument name and Value
is the corresponding value.
Name
must appear inside quotes. You can specify several name and value
pair arguments in any order as
Name1,Value1,...,NameN,ValueN
.
activations(net,X,layer,'OutputAs','rows')
'OutputAs'
— Format of output activations'channels'
(default) | 'rows'
| 'columns'
Format of output activations, specified as the comma-separated pair
consisting of 'OutputAs'
and either
'channels'
, 'rows'
, or
'columns'
. For descriptions of the different
output formats, see features
.
For image input, if the 'OutputAs'
option is 'channels'
, then the images in the input data X
can be larger than the input size of the image input layer of the network. For other output formats, the images in X
must have the same size as the input size of the image input layer of the network.
Example: 'OutputAs','rows'
'MiniBatchSize'
— Size of mini-batchesSize 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
'SequenceLength'
— Option to pad, truncate, or split input sequences'longest'
(default) | 'shortest'
| positive integerOption 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'
'SequencePaddingValue'
— Value to pad input sequencesValue 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
'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 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.
'Acceleration'
— Performance optimization'auto'
(default) | 'mex'
| 'none'
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.
You cannot use MATLAB
Compiler™ to deploy your network when using the 'mex'
option.
Example: 'Acceleration','mex'
'ExecutionEnvironment'
— Hardware resource'auto'
(default) | 'gpu'
| 'cpu'
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'
features
— Activations from the network layerActivations from the network layer, returned as a numeric array or a cell
array of numeric arrays. The format of features
depends
on the type of input data, the type of layer output, and the
'OutputAs'
option.
If net
has an image input layer, then
features
is a numeric array.
'OutputAs' | features |
---|---|
'channels' | For 2-D image data,
For 3-D
image data, |
'rows' | n-by-m
matrix, where n is the number of
observations, and m is the
number of output elements from the chosen layer. In
this case, features(i,:) contains
the activations for the i th
image. |
'columns' | m-by-n
matrix, where m is the number of
output elements from the chosen layer, and
n is the number of
observations. In this case,
features(:,i) contains the
activations for the i th
image. |
If net
has a sequence input layer, and
layer
has sequence output (for example, LSTM
layers with output mode 'sequence'
), then
features
is a cell array. In this case, the
'OutputAs'
option must be
'channels'
.
'OutputAs' | features |
---|---|
'channels' | For vector sequence input,
For 2-D image sequence input,
For 3-D image
sequence input, In these cases,
|
If net
has a sequence input layer and
layer
outputs non-sequence data (for example,
an LSTM layer with output mode 'last'
), then
features
is a numeric array.
'OutputAs' | features |
---|---|
'channels' | For vector sequence input,
For 2-D image sequence
input, For 3-D
image sequence input, In these cases,
|
'rows' | n-by-m
matrix, where n is the number of
observations, and m is the
number of output elements from the chosen layer. In
this case, features(i,:) contains
the activations for the i th
sequence. |
'columns' | m-by-n
matrix, where m is the number of
output elements from the chosen layer, and
n is the number of
observations. In this case,
features(:,i) contains the
activations for the i th
image. |
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.
[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
Usage notes and limitations:
The input X
must not have a variable size. The
size must be fixed at code generation time.
The layer
argument must be constant.
Only the 'OutputAs'
name-value pair argument is
supported. The value must be 'channels'
.
For more information about generating code for deep learning neural networks, see Workflow for Deep Learning Code Generation with MATLAB Coder (MATLAB Coder).
Usage notes and limitations:
GPU code generation supports the following syntaxes:
features =
activations(net,X,layer)
features =
activations(__,Name,Value)
The input X
must not have variable size. The size
must be fixed at code generation time.
GPU code generation for the activations
function
supports inputs that are defined as half-precision floating point data
types. For more information, see half
.
The layer
argument must be a compile-time
constant.
Only the 'OutputAs'
and
'MiniBatchSize'
name-value pair arguments are
supported for code generation. The value of the
'OutputAs'
name-value pair must be
'channels'
.
All name-value pairs must be compile-time constants.
You have a modified version of this example. Do you want to open this example with your edits?