Main Content


Load network distribution discriminator for code generation

Since R2023a



    discriminator = coder.loadNetworkDistributionDiscriminator(filename) loads a network distribution discriminator saved in the filename MAT-file. filename must be a valid MAT-file on the MATLAB® path, contain a single distribution discriminator object, and be a compile-time constant.


    collapse all

    This example requires the Deep Learning Toolbox™ Verification Library support package. If this support package is not installed, use the Add-On Explorer. To open the Add-On Explorer, go to the MATLAB® Toolstrip and click Add-Ons > Get Add-Ons.

    Load a trained dlnetwork object.


    Load in-distribution training data.

    XTrain = digitTrain4DArrayData;
    XTrain = dlarray(XTrain,"SSCB");

    Create a distribution discriminator. You can use the discriminator to classify observations as in-distribution (ID) or out-of-distribution (OOD). OOD data refers to data that is sufficiently different from the data you use to train the network, which can cause the network to behave unexpectedly.

    method = "baseline";
    discriminator = networkDistributionDiscriminator(dlnet,XTrain,[],method)
    discriminator = 
      BaselineDistributionDiscriminator with properties:
           Method: "baseline"
          Network: [1×1 dlnetwork]
        Threshold: 0.9269

    Save the discriminator.


    Create an entry-point function discriminatorEntryPoint that accepts formatted dlarray data. The entry-point function performs these operations:

    • Define a persistent variable called discriminator. The persistent variable prevents reconstructing and reloading the object during subsequent calls to the discriminatorEntryPoint function.

    • Load the discriminator from the file discriminator.mat file into the discriminator variable using the coder.loadNetworkDistributionDiscriminator function.

    • Calculate a distribution score using the distributionScores function.

    • Return the distribution score as an output.

    An entry-point function is provided with this example as a supporting file. To access the supporting file, open this example as a live script. Show the contents of the entry-point function.

    type discriminatorEntryPoint.m
    function score = discriminatorEntryPoint(X)
    persistent discriminator;
    if isempty(discriminator)
        discriminator = coder.loadNetworkDistributionDiscriminator("discriminator.mat");
    score = distributionScores(discriminator,X);

    To configure the build settings, create a coder configuration object. To create the object, use the coder.gpuConfig function and specify the output as a MEX file that calls generated CUDA code.

    cfg = coder.gpuConfig("mex");
    cfg.TargetLang = "C++";
    cfg.DeepLearningConfig = coder.DeepLearningConfig("cudnn");

    Create an array of example values that define the size and class of the inputs to the generated function.

    X = dlarray(ones(28,28,1,1,"single"),"SSCB");

    Generate the MEX file using the configuration object, the example values, and the entry-point function discriminatorEntryPoint. The generated discriminatorEntryPoint_mex function returns the distribution score for an input observation. Code generation requires a supported compiler. To view a list of supported compilers, see Supported and Compatible Compilers.

    codegen -args {X} -config cfg discriminatorEntryPoint -report
    Code generation successful: View report

    You can view the resulting code generation report by clicking View Report in the MATLAB® Command Window. The report is displayed in the Report Viewer window. If the code generator detects errors or warnings during code generation, then the report describes the issues and provides links to the problematic MATLAB code.

    Test the generated MEX function by comparing the distribution confidence score for an ID image and an OOD image. To create out an OOD image, modify an image from the ID training data set.

    imageIdx = randi(size(XTrain,4));
    XID = dlarray(XTrain(:,:,:,imageIdx),"SSCB");
    XID = single(XID);
    XOOD = XID.*0.3 + 0.1;

    Calculate the distribution score for the ID image and the OOD image.

    IDScore = discriminatorEntryPoint_mex(XID)
    IDScore = single
    OODScore = discriminatorEntryPoint_mex(XOOD)
    OODScore = single

    Input Arguments

    collapse all

    Filename of the MAT-file containing the distribution discriminator, specified as a string scalar. The MAT-file must exist on the MATLAB path and contain only the network to be loaded.

    The distribution discriminator can be any discriminator returned by the networkDistributionDiscriminator function, such as a BaselineDistributionDiscriminator, EnergyDistributionDiscriminator, ODINDistributionDiscriminator, or HBOSDistributionDiscriminator.

    This input argument must be a compile-time constant. You can use a coder.Constant (MATLAB Coder) object to ensure that filename is a compile-time constant.

    Data Types: string

    Output Arguments

    collapse all


    • For the HBOS out-of-distribution discrimination method, running the MATLAB discriminator and the generated code on a test set might produce different results. Specifically, during the execution of generated code, the accumulation of small precision errors might cause crossing of histogram bins and yield larger changes to the distribution scores. To understand this discrepancy, further analysis might be required. The characteristics of the deployed discriminators have to be verified to comply with the project-specific requirements.

    Extended Capabilities

    C/C++ Code Generation
    Generate C and C++ code using MATLAB® Coder™.

    GPU Code Generation
    Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

    Version History

    Introduced in R2023a