Main Content

importTensorFlowLayers

(To be removed) Import layers from TensorFlow network

Since R2021a

    importTensorFlowLayers will be removed in a future release. Use importNetworkFromTensorFlow instead. (since R2023b) For more information about updating your code, see Version History.

    Description

    example

    lgraph = importTensorFlowLayers(modelFolder) returns the layers of a TensorFlow™ network from the folder modelFolder, which contains the model in the saved model format (compatible only with TensorFlow 2). The function can import TensorFlow networks created with the TensorFlow-Keras sequential or functional API. importTensorFlowLayers imports the layers defined in the saved_model.pb file and the learned weights contained in the variables subfolder, and returns lgraph as a LayerGraph object.

    importTensorFlowLayers requires the Deep Learning Toolbox™ Converter for TensorFlow Models support package. If this support package is not installed, then importTensorFlowLayers provides a download link.

    Note

    importTensorFlowLayers tries to generate a custom layer when you import a custom TensorFlow layer or when the software cannot convert a TensorFlow layer into an equivalent built-in MATLAB® layer. For a list of layers for which the software supports conversion, see TensorFlow-Keras Layers Supported for Conversion into Built-In MATLAB Layers.

    importTensorFlowLayers saves the generated custom layers and the associated TensorFlow operators in the package +modelFolder.

    importTensorFlowLayers does not automatically generate a custom layer for each TensorFlow layer that is not supported for conversion into a built-in MATLAB layer. For more information on how to handle unsupported layers, see Tips.

    example

    lgraph = importTensorFlowLayers(modelFolder,Name,Value) imports the layers and weights from a TensorFlow network with additional options specified by one or more name-value arguments. For example, 'OutputLayerType','classification' appends a classification output layer to the end of the imported network architecture.

    Examples

    collapse all

    Import a pretrained TensorFlow network in the saved model format as a LayerGraph object. Then, assemble the imported layers into a DAGNetwork object, and use the assembled network to classify an image.

    Specify the model folder.

    if ~exist('digitsDAGnet','dir')
        unzip('digitsDAGnet.zip')
    end
    modelFolder = './digitsDAGnet';

    Specify the class names.

    classNames = {'0','1','2','3','4','5','6','7','8','9'};

    Import the layers and weights of a TensorFlow network in the saved model format. By default, importTensorFlowLayers imports the network as a LayerGraph object compatible with a DAGNetwork object. Specify the output layer type for an image classification problem.

    lgraph = importTensorFlowLayers(modelFolder,'OutputLayerType','classification')
    Importing the saved model...
    Translating the model, this may take a few minutes...
    Finished translation.
    
    lgraph = 
      LayerGraph with properties:
    
             Layers: [13×1 nnet.cnn.layer.Layer]
        Connections: [13×2 table]
         InputNames: {'input_1'}
        OutputNames: {'ClassificationLayer_activation_1'}
    
    

    Display the last layer of the imported network. The output shows that importTensorFlowLayers appends a ClassificationOutputLayer to the end of the network architecture.

    lgraph.Layers(end)
    ans = 
      ClassificationOutputLayer with properties:
    
                Name: 'ClassificationLayer_activation_1'
             Classes: 'auto'
        ClassWeights: 'none'
          OutputSize: 'auto'
    
       Hyperparameters
        LossFunction: 'crossentropyex'
    
    

    The classification layer does not contain the classes, so you must specify these before assembling the network. If you do not specify the classes, then the software automatically sets the classes to 1, 2, ..., N, where N is the number of classes.

    The classification layer has the name 'ClassificationLayer_activation_1'. Set the classes to classNames and then replace the imported classification layer with the new one.

    cLayer = lgraph.Layers(end);
    cLayer.Classes = classNames;
    lgraph = replaceLayer(lgraph,'ClassificationLayer_activation_1',cLayer);

    Assemble the layer graph using assembleNetwork to return a DAGNetwork object.

    net = assembleNetwork(lgraph)
    net = 
      DAGNetwork with properties:
    
             Layers: [13×1 nnet.cnn.layer.Layer]
        Connections: [13×2 table]
         InputNames: {'input_1'}
        OutputNames: {'ClassificationLayer_activation_1'}
    
    

    Read the image you want to classify.

    digitDatasetPath = fullfile(toolboxdir('nnet'),'nndemos','nndatasets','DigitDataset');
    I = imread(fullfile(digitDatasetPath,'5','image4009.png'));

    Classify the image using the imported network.

    label = classify(net,I);

    Display the image and the classification result.

    imshow(I)
    title(['Classification result ' classNames{label}])

    Import a pretrained TensorFlow network in the saved model format as a LayerGraph object compatible with a dlnetwork object. Then, convert the LayerGraph object to a dlnetwork to classify an image.

    Specify the model folder.

    if ~exist('digitsDAGnet','dir')
        unzip('digitsDAGnet.zip')
    end
    modelFolder = './digitsDAGnet';

    Specify the class names.

    classNames = {'0','1','2','3','4','5','6','7','8','9'};

    Import the TensorFlow network as layers compatible with a dlnetwork object.

    lgraph = importTensorFlowLayers(modelFolder,'TargetNetwork','dlnetwork')
    Importing the saved model...
    Translating the model, this may take a few minutes...
    Finished translation.
    
    lgraph = 
      LayerGraph with properties:
    
             Layers: [12×1 nnet.cnn.layer.Layer]
        Connections: [12×2 table]
         InputNames: {'input_1'}
        OutputNames: {1×0 cell}
    
    

    Read the image you want to classify and display the size of the image. The image is a grayscale (one-channel) image with size 28-by-28 pixels.

    digitDatasetPath = fullfile(toolboxdir('nnet'),'nndemos','nndatasets','DigitDataset');
    I = imread(fullfile(digitDatasetPath,'5','image4009.png'));
    size(I)
    ans = 1×2
    
        28    28
    
    

    Convert the imported layer graph to a dlnetwork object.

    dlnet = dlnetwork(lgraph);

    Display the input size of the network. In this case, the image size matches the network input size. If they do not match, you must resize the image by using imresize(I, netInputSize(1:2)).

    dlnet.Layers(1).InputSize
    ans = 1×3
    
        28    28     1
    
    

    Convert the image to a dlarray. Format the images with the dimensions 'SSCB' (spatial, spatial, channel, batch). In this example, the batch size is 1 and you can omit it ('SSC').

    I_dlarray = dlarray(single(I),'SSCB');

    Classify the sample image and find the predicted label.

    prob = predict(dlnet,I_dlarray);
    [~,label] = max(prob);

    Display the image and the classification result.

    imshow(I)
    title(['Classification result ' classNames{label}])

    Import a pretrained TensorFlow network in the saved model format as a LayerGraph object. Then, assemble the imported layers into a DAGNetwork object. The imported network contains layers that are not supported for conversion into built-in MATLAB layers. The software automatically generates custom layers when you import these layers.

    This example uses the helper function findCustomLayers. To view the code for this function, see Helper Function.

    Specify the model folder.

    if ~exist('digitsDAGnetwithnoise','dir')
        unzip('digitsDAGnetwithnoise.zip')
    end
    modelFolder = './digitsDAGnetwithnoise';

    Specify the class names.

    classNames = {'0','1','2','3','4','5','6','7','8','9'};

    Import the layers and weights of a TensorFlow network in the saved model format. By default, importTensorFlowLayers imports the network as a LayerGraph object compatible with a DAGNetwork object. Specify the output layer type for an image classification problem.

    lgraph = importTensorFlowLayers(modelFolder,'OutputLayerType','classification');
    Importing the saved model...
    Translating the model, this may take a few minutes...
    Finished translation.
    

    If the imported network contains layers not supported for conversion into built-in MATLAB layers, then importTensorFlowLayers can automatically generate custom layers in place of these layers. importTensorFlowLayers saves each generated custom layer to a separate .m file in the package +digitsDAGnetwithnoise in the current folder.

    Find the indices of the automatically generated custom layers, using the helper function findCustomLayers, and display the custom layers.

    ind = findCustomLayers(lgraph.Layers,'+digitsDAGnetwithnoise');
    lgraph.Layers(ind)
    ans = 
      2×1 Layer array with layers:
    
         1   'gaussian_noise_1'   GaussianNoise   digitsDAGnetwithnoise.kGaussianNoise1Layer3766
         2   'gaussian_noise_2'   GaussianNoise   digitsDAGnetwithnoise.kGaussianNoise2Layer3791
    

    The classification layer does not contain the classes, so you must specify these before assembling the network. If you do not specify the classes, then the software automatically sets the classes to 1, 2, ..., N, where N is the number of classes.

    The classification layer has the name 'ClassificationLayer_activation_1'. Set the classes to classNames and then replace the imported classification layer with the new one.

    cLayer = lgraph.Layers(end);
    cLayer.Classes = classNames;
    lgraph = replaceLayer(lgraph,'ClassificationLayer_activation_1',cLayer);

    Assemble the layer graph using assembleNetwork. The function returns a DAGNetwork object that is ready to use for prediction.

    net = assembleNetwork(lgraph)
    net = 
      DAGNetwork with properties:
    
             Layers: [15×1 nnet.cnn.layer.Layer]
        Connections: [15×2 table]
         InputNames: {'input_1'}
        OutputNames: {'ClassificationLayer_activation_1'}
    
    

    Helper Function

    This section provides the code of the helper function findCustomLayers used in this example. findCustomLayers returns the indices of the custom layers that importTensorFlowNetwork automatically generates.

    function indices = findCustomLayers(layers,PackageName)
    
    s = what(['.\' PackageName]);
    
    indices = zeros(1,length(s.m));
    for i = 1:length(layers)
        for j = 1:length(s.m)
            if strcmpi(class(layers(i)),[PackageName(2:end) '.' s.m{j}(1:end-2)])
                indices(j) = i;
            end
        end
    end
    
    end

    Input Arguments

    collapse all

    Name of the folder containing the TensorFlow model, specified as a character vector or string scalar. modelFolder must be in the current folder, or you must include a full or relative path to the folder. modelFolder must contain the file saved_model.pb, and the subfolder variables. It can also contain the subfolders assets and assets.extra.

    • The file saved_model.pb contains the layer graph architecture and training options (for example, optimizer, losses, and metrics).

    • The subfolder variables contains the weights learned by the pretrained TensorFlow network. By default, importTensorFlowLayers imports the weights.

    • The subfolder assets contains supplementary files (for example, vocabularies), which the layer graph can use. importTensorFlowLayers does not import the files in assets.

    • The subfolder assets.extra contains supplementary files (for example, information for users), which coexist with the layer graph.

    Example: 'MobileNet'

    Example: './MobileNet'

    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: importTensorFlowLayers(modelFolder,'TargetNetwork','dagnetwork','OutputLayerType','classification') imports the network layers and weights from modelFolder, saves the automatically generated custom layers in the package +modelFolder in the current folder, specifies that the imported layers are compatible with a DAGNetwork object, and appends a classification output layer to the end of the imported layers.

    Name of the package in which importTensorFlowLayers saves custom layers, specified as a character vector or string scalar. importTensorFlowLayers saves the custom layers package +PackageName in the current folder. If you do not specify 'PackageName', then importTensorFlowLayers saves the custom layers in a package named +modelFolder in the current folder. For more information on packages, see Packages Create Namespaces.

    importTensorFlowLayers tries to generate a custom layer when you import a custom TensorFlow layer or when the software cannot convert a TensorFlow layer into an equivalent built-in MATLAB layer. importTensorFlowLayers saves each generated custom layer to a separate .m file in +PackageName. To view or edit a custom layer, open the associated .m file. For more information on custom layers, see Custom Layers.

    The package +PackageName can also contain the subpackage +ops. This subpackage contains MATLAB functions corresponding to TensorFlow operators (see Supported TensorFlow Operators) that are used in the automatically generated custom layers. importTensorFlowLayers saves the associated MATLAB function for each operator in a separate .m file in the subpackage +ops. The object functions of dlnetwork, such as the predict function, use these operators when interacting with the custom layers.

    Example: 'PackageName','MobileNet'

    Example: 'PackageName','CustomLayers'

    Target type of Deep Learning Toolbox network for imported network architecture, specified as 'dagnetwork' or 'dlnetwork'.

    • If you specify 'TargetNetwork' as 'dagnetwork', the imported network architecture is compatible with a DAGNetwork object. In this case, the imported lgraph must include an output layer specified by the TensorFlow saved model loss function or the name-value argument 'OutputLayerType'.

    • If you specify 'TargetNetwork' as 'dlnetwork', the imported network architecture is compatible with a dlnetwork object. In this case, the imported lgraph does not include an output layer.

    Example: 'TargetNetwork','dlnetwork' imports a LayerGraph object compatible with a dlnetwork object.

    Type of output layer that importTensorFlowLayers appends to the end of the imported network architecture, specified as 'classification', 'regression', or 'pixelclassification'. Appending a pixelClassificationLayer (Computer Vision Toolbox) object requires Computer Vision Toolbox™.

    • If you specify 'TargetNetwork' as 'dagnetwork' and the saved model in modelFolder does not specify a loss function, you must assign a value to the name-value argument 'OutputLayerType'. A DAGNetwork object must have an output layer.

    • If you specify 'TargetNetwork' as 'dlnetwork', importTensorFlowLayers ignores the name-value argument 'OutputLayerType'. A dlnetwork object does not have an output layer.

    Example: 'OutputLayerType','classification'

    Size of the input images for the network, specified as a vector of two or three numerical values corresponding to [height,width] for grayscale images and [height,width,channels] for color images, respectively. The network uses this information when the saved_model.pb file in modelFolder does not specify the input size.

    Example: 'ImageInputSize',[28 28]

    Indicator to display import progress information in the command window, specified as a numeric or logical 1 (true) or 0 (false).

    Example: 'Verbose','true'

    Output Arguments

    collapse all

    Network architecture, returned as a LayerGraph object.

    To use the imported layer graph for prediction, you must convert the LayerGraph object to a DAGNetwork or dlnetwork object. Specify the name-value argument 'TargetNetwork' as 'dagnetwork' or 'dlnetwork' depending on the intended workflow.

    • Convert a LayerGraph to a DAGNetwork by using assembleNetwork. On the DAGNetwork object, you then predict class labels using the classify function.

    • Convert a LayerGraph to a dlnetwork by using dlnetwork. On the dlnetwork object, you then predict class labels using the predict function. Specify the input data as a dlarray using the correct data format (for more information, see the fmt argument of dlarray).

    Limitations

    • importTensorFlowLayers supports TensorFlow versions v2.0 to 2.6.

    More About

    collapse all

    TensorFlow-Keras Layers Supported for Conversion into Built-In MATLAB Layers

    importTensorFlowLayers supports the following TensorFlow-Keras layer types for conversion into built-in MATLAB layers, with some limitations.

    TensorFlow-Keras LayerCorresponding Deep Learning Toolbox Layer
    AddadditionLayer

    Activation, with activation names:

    • elu

    • gelu

    • relu

    • linear

    • softmax

    • sigmoid

    • swish

    • tanh

    Layers:

    Advanced activations:

    • ELU

    • Softmax

    • ReLU

    • LeakyReLU

    • PReLu*

    Layers:

    AveragePooling1DaveragePooling1dLayer with PaddingValue specified as 'mean'
    AveragePooling2DaveragePooling2dLayer with PaddingValue specified as 'mean'
    BatchNormalizationbatchNormalizationLayer
    Bidirectional(LSTM(__))bilstmLayer
    Conv1Dconvolution1dLayer
    Conv2Dconvolution2dLayer
    Conv2DTransposetransposedConv2dLayer
    CuDNNGRUgruLayer
    CuDNNLSTMlstmLayer
    DensefullyConnectedLayer
    DepthwiseConv2DgroupedConvolution2dLayer
    DropoutdropoutLayer
    EmbeddingwordEmbeddingLayer (Text Analytics Toolbox)
    Flattennnet.keras.layer.FlattenCStyleLayer
    GlobalAveragePooling1DglobalAveragePooling1dLayer
    GlobalAveragePooling2DglobalAveragePooling2dLayer
    GlobalMaxPool1DglobalMaxPooling1dLayer
    GlobalMaxPool2DglobalMaxPooling2dLayer
    GRUgruLayer
    InputimageInputLayer, sequenceInputLayer, or featureInputLayer
    LSTMlstmLayer
    MaxPool1DmaxPooling1dLayer
    MaxPool2DmaxPooling2dLayer
    MultiplymultiplicationLayer
    SeparableConv2DgroupedConvolution2dLayer or convolution2dLayer
    TimeDistributedsequenceFoldingLayer before the wrapped layer, and sequenceUnfoldingLayer after the wrapped layer
    UpSampling2Dresize2dLayer (Image Processing Toolbox)
    UpSampling3Dresize3dLayer (Image Processing Toolbox)
    ZeroPadding1Dnnet.keras.layer.ZeroPadding1DLayer
    ZeroPadding2Dnnet.keras.layer.ZeroPadding2DLayer

    * For a PReLU layer, importTensorFlowLayers replaces a vector-valued scaling parameter with the average of the vector elements. You can change the parameter back to a vector after import. For an example, see Import Keras PReLU Layer.

    Supported TensorFlow-Keras Loss Functions

    importTensorFlowLayers supports the following Keras loss functions:

    • mean_squared_error

    • categorical_crossentropy

    • sparse_categorical_crossentropy

    • binary_crossentropy

    Supported TensorFlow Operators

    importTensorFlowLayers supports the following TensorFlow operators for conversion into MATLAB functions with dlarray support.

    TensorFlow OperatorCorresponding MATLAB Function
    AddtfAdd
    AddNtfAddN
    AddV2tfAdd
    AlltfAll
    Assertassert
    AvgPooltfAvgPool
    BatchMatMulV2tfBatchMatMulV2
    BiasAddtfBiasAdd
    BroadcastTotfBroadcastTo
    CasttfCast
    ConcatV2tfCat
    ConstNone (translated to weights in custom layer)
    Conv2DtfConv2D
    DepthToSpacedepthToSpace (Image Processing Toolbox)
    DepthwiseConv2dNativetfDepthwiseConv2D
    Equal==
    Expexp
    ExpandDimstfExpandDims
    FilltfFill
    FusedBatchNormV3tfBatchnorm
    GatherV2tfGather
    Greatergt>
    GreaterEqualge, >=
    IdentityNone (translated to value assignment in custom layer)
    IdentityNtfIdentityN
    L2LosstfL2Loss
    LeakyReluleakyrelu
    Lesslt, <
    Loglog
    MatMultfMatMul
    MaxPooltfMaxPool
    MaximumtfMaximum
    MeantfMean
    MinimumtfMinimum
    MirrorPadtfMirrorPad
    MultfMul
    Negminus, -
    NonMaxSuppressionV5tfNonMaxSuppressionV5
    PacktfStack
    PadtfPad
    PadV2tfPad
    PartitionedCallNone (translated to function in custom layer methods)
    Powpower, .^
    ProdtfProd
    RandomStandardNormaltfRandomStandardNormal
    RangetfRange
    ReadVariableOpNone (translated to value assignment in custom layer)
    RealDivtfDiv
    Relurelu
    Relu6relu and min
    ReshapetfReshape
    ResizeBilineardlresize (Image Processing Toolbox)
    ResizeNearestNeighbordlresize (Image Processing Toolbox)
    Rsqrtsqrt
    SelecttfSelect
    ShapetfShape
    Sigmoidsigmoid
    SizetfSize
    SlicetfSlice
    Softmaxsoftmax
    SpaceToDepthspaceToDepth (Image Processing Toolbox)
    SplittfSplit
    Square.^2
    Sqrtsqrt
    SquaredDifferencetfMul or tfSub
    SqueezetfSqueeze
    StatefulPartitionedCallNone (translated to function in custom layer methods)
    StopGradienttfStopGradient
    StridedSlicetfStridedSlice or tfSqueeze
    SubtfSub
    SumtfSum
    Tanhtanh
    TiletfTile
    TransposetfTranspose
    UnpacktfUnpack
    WheretfWhere

    For more information on functions that operate on dlarray objects, see List of Functions with dlarray Support.

    Generate Code for Imported Network Architecture

    You can use MATLAB Coder™ or GPU Coder™ together with Deep Learning Toolbox to generate MEX, standalone CPU, CUDA® MEX, or standalone CUDA code for an imported network. For more information, see Code Generation.

    • Use MATLAB Coder with Deep Learning Toolbox to generate MEX or standalone CPU code that runs on desktop or embedded targets. You can deploy generated standalone code that uses the Intel® MKL-DNN library or the ARM® Compute library. Alternatively, you can generate generic C or C++ code that does not call third-party library functions. For more information, see Deep Learning with MATLAB Coder (MATLAB Coder).

    • Use GPU Coder with Deep Learning Toolbox to generate CUDA MEX or standalone CUDA code that runs on desktop or embedded targets. You can deploy generated standalone CUDA code that uses the CUDA deep neural network library (cuDNN), the TensorRT™ high performance inference library, or the ARM Compute library for Mali GPU. For more information, see Deep Learning with GPU Coder (GPU Coder).

    importTensorFlowLayers returns the network architecture lgraph as a LayerGraph object. For code generation, you must first convert the imported LayerGraph object to a network. Convert a LayerGraph object to a DAGNetwork or dlnetwork object by using assembleNetwork or dlnetwork. For more information on MATLAB Coder and GPU Coder support for Deep Learning Toolbox objects, see Supported Classes (MATLAB Coder) and Supported Classes (GPU Coder), respectively.

    You can generate code for any imported network whose layers support code generation. For lists of the layers that support code generation with MATLAB Coder and GPU Coder, see Supported Layers (MATLAB Coder) and Supported Layers (GPU Coder), respectively. For more information on the code generation capabilities and limitations of each built-in MATLAB layer, see the Extended Capabilities section of the layer. For example, see Code Generation and GPU Code Generation of imageInputLayer.

    Use Imported Network Layers on GPU

    importTensorFlowLayers does not execute on a GPU. However, importTensorFlowLayers imports the layers of a pretrained neural network for deep learning as a LayerGraph object, which you can use on a GPU.

    • Convert the imported LayerGraph object to a DAGNetwork object by using assembleNetwork. On the DAGNetwork object, you can then predict class labels on either a CPU or GPU by using classify. Specify the hardware requirements using the name-value argument ExecutionEnvironment. For networks with multiple outputs, use the predict function and specify the name-value argument ReturnCategorical as true.

    • Convert the imported LayerGraph object to a dlnetwork object by using dlnetwork. On the dlnetwork object, you can then predict class labels on either a CPU or GPU by using predict. The function predict executes on the GPU if either the input data or network parameters are stored on the GPU.

      • If you use minibatchqueue to process and manage the mini-batches of input data, the minibatchqueue object converts the output to a GPU array by default if a GPU is available.

      • Use dlupdate to convert the learnable parameters of a dlnetwork object to GPU arrays.

        net = dlupdate(@gpuArray,net)

    • You can train the imported LayerGraph object on either a CPU or GPU by using the trainnet and trainNetwork functions. To specify training options, including options for the execution environment, use the trainingOptions function. Specify the hardware requirements using the name-value argument ExecutionEnvironment. For more information on how to accelerate training, see Scale Up Deep Learning in Parallel, on GPUs, and in the Cloud.

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

    Tips

    • If the imported network contains a layer not supported for conversion into a built-in MATLAB layer (see TensorFlow-Keras Layers Supported for Conversion into Built-In MATLAB Layers) and importTensorFlowLayers does not automatically generate a custom layer, then importTensorFlowLayers inserts a placeholder layer in place of the unsupported layer. To find the names and indices of the unsupported layers in the network, use the findPlaceholderLayers function. You then can replace a placeholder layer with a new layer that you define. To replace a layer, use replaceLayer.

    • To use a pretrained network for prediction or transfer learning on new images, you must preprocess your images in the as same way the images that you use to train the imported model. The most common preprocessing steps are resizing images, subtracting image average values, and converting the images from BGR format to RGB format.

      • To resize images, use imresize. For example, imresize(image,[227 227 3]).

      • To convert images from RGB to BGR format, use flip. For example, flip(image,3).

      For more information about preprocessing images for training and prediction, see Preprocess Images for Deep Learning.

    • The members of the package +PackageName (custom layers and TensorFlow operators) are not accessible if the package parent folder is not on the MATLAB path. For more information, see Packages and the MATLAB Path.

    • MATLAB uses one-based indexing, whereas Python® uses zero-based indexing. In other words, the first element in an array has an index of 1 and 0 in MATLAB and Python, respectively. For more information about MATLAB indexing, see Array Indexing. In MATLAB, to use an array of indices (ind) created in Python, convert the array to ind+1.

    • For more tips, see Tips on Importing Models from TensorFlow, PyTorch, and ONNX.

    Alternative Functionality

    Use importTensorFlowNetwork or importTensorFlowLayers to import a TensorFlow network in the saved model format [2]. Alternatively, if the network is in HDF5 or JSON format, use importKerasNetwork or importKerasLayers to import the network.

    References

    [2] Using the SavedModel format. https://www.tensorflow.org/guide/saved_model.

    Version History

    Introduced in R2021a

    expand all

    R2023b: importTensorFlowLayers will be removed

    Starting in R2023b, the importTensorFlowLayers function warns. Use importNetworkFromTensorFlow instead. The importNetworkFromTensorFlow function has these advantages over importTensorFlowLayers:

    • Imports a TensorFlow model into a dlnetwork object in a single step

    • Provides a simplified workflow for importing models with unknown input and output information

    • Has improved name-value arguments that you can use to more easily specify import options