Class MultiLayerNetwork

    • Field Detail

      • layers

        protected Layer[] layers
      • initCalled

        protected boolean initCalled
      • score

        protected double score
      • initDone

        protected boolean initDone
      • flattenedParams

        protected INDArray flattenedParams
      • flattenedGradients

        protected transient INDArray flattenedGradients
      • clearTbpttState

        protected boolean clearTbpttState
      • layerIndex

        protected int layerIndex
      • solver

        protected transient Solver solver
      • helperWorkspaces

        protected transient Map<String,​org.bytedeco.javacpp.Pointer> helperWorkspaces
      • WS_LAYER_WORKING_MEM

        protected static final String WS_LAYER_WORKING_MEM
        Workspace for working memory for a single layer: forward pass and backward pass Note that this is opened/closed once per op (activate/backpropGradient call)
        See Also:
        Constant Field Values
      • WS_ALL_LAYERS_ACT

        protected static final String WS_ALL_LAYERS_ACT
        Workspace for storing all layers' activations - used only to store activations (layer inputs) as part of backprop Not used for inference
        See Also:
        Constant Field Values
      • WS_LAYER_ACT_1

        protected static final String WS_LAYER_ACT_1
        Next 2 workspaces: used for: (a) Inference: holds activations for one layer only (b) Backprop: holds activation gradients for one layer only In both cases, they are opened and closed on every second layer
        See Also:
        Constant Field Values
      • WS_OUTPUT_MEM

        protected static final String WS_OUTPUT_MEM
        Workspace for output methods that use OutputAdapter
        See Also:
        Constant Field Values
      • WS_RNN_LOOP_WORKING_MEM

        protected static final String WS_RNN_LOOP_WORKING_MEM
        Workspace for working memory in RNNs - opened and closed once per RNN time step
        See Also:
        Constant Field Values
      • WS_RNN_LOOP_WORKING_MEM_CONFIG

        protected static final WorkspaceConfiguration WS_RNN_LOOP_WORKING_MEM_CONFIG
    • Constructor Detail

      • MultiLayerNetwork

        public MultiLayerNetwork​(String conf,
                                 INDArray params)
        Initialize the network based on the configuration (a MultiLayerConfiguration in JSON format) and parameters array
        Parameters:
        conf - the configuration json
        params - the parameters for the network
      • MultiLayerNetwork

        public MultiLayerNetwork​(MultiLayerConfiguration conf,
                                 INDArray params)
        Initialize the network based on the configuration and parameters array
        Parameters:
        conf - the configuration
        params - the parameters
    • Method Detail

      • getLayerWorkingMemWSConfig

        protected static WorkspaceConfiguration getLayerWorkingMemWSConfig​(int numWorkingMemCycles)
      • getLayerActivationWSConfig

        protected static WorkspaceConfiguration getLayerActivationWSConfig​(int numLayers)
      • setCacheMode

        public void setCacheMode​(CacheMode mode)
        This method sets specified CacheMode for all layers within network
        Specified by:
        setCacheMode in interface Layer
        Parameters:
        mode -
      • setLastEtlTime

        public void setLastEtlTime​(long time)
        Set the last ETL time in milliseconds, for informational/reporting purposes. Generally used internally.
        Parameters:
        time - ETL time
      • getLastEtlTime

        public long getLastEtlTime()
        Get the last ETL time. This in informational, and is the amount of time in milliseconds that was required to obtain the last DataSet/MultiDataSet during fitting. A value consistently above 0 may indicate a data feeding bottleneck, or no asynchronous data prefetching (async prefetch is enabled by default)
        Returns:
        The last ETL time in milliseconds, if avaliable (or 0 if not)
      • intializeConfigurations

        protected void intializeConfigurations()
      • pretrain

        public void pretrain​(DataSetIterator iter,
                             int numEpochs)
        Perform layerwise unsupervised training on all pre-trainable layers in the network (VAEs, Autoencoders, etc), for the specified number of epochs each. For example, if numEpochs=3, then layer 0 will be fit for 3 epochs, followed by layer 1 for 3 epochs, and so on.
        Note that pretraining will be performed on one layer after the other. To perform unsupervised training on a single layer, use pretrainLayer(int, DataSetIterator)
        Parameters:
        iter - Training data
      • pretrainLayer

        public void pretrainLayer​(int layerIdx,
                                  DataSetIterator iter,
                                  int numEpochs)
        Perform layerwise unsupervised training on a single pre-trainable layer in the network (VAEs, Autoencoders, etc) for the specified number of epochs
        If the specified layer index (0 to numLayers - 1) is not a pretrainable layer, this is a no-op.
        Parameters:
        layerIdx - Index of the layer to train (0 to numLayers-1)
        iter - Training data
        numEpochs - Number of epochs to fit the specified layer for
      • pretrainLayer

        public void pretrainLayer​(int layerIdx,
                                  INDArray features)
        Perform layerwise unsupervised training on a single pre-trainable layer in the network (VAEs, Autoencoders, etc)
        If the specified layer index (0 to numLayers - 1) is not a pretrainable layer, this is a no-op.
        Parameters:
        layerIdx - Index of the layer to train (0 to numLayers-1)
        features - Training data array
      • batchSize

        public int batchSize()
        Description copied from interface: Model
        The current inputs batch size
        Specified by:
        batchSize in interface Model
        Returns:
        the current inputs batch size
      • conf

        public NeuralNetConfiguration conf()
        Description copied from interface: Model
        The configuration for the neural network
        Specified by:
        conf in interface Model
        Returns:
        the configuration for the neural network
      • input

        public INDArray input()
        Description copied from interface: Model
        The input/feature matrix for the model
        Specified by:
        input in interface Model
        Returns:
        the input/feature matrix for the model
      • getParam

        public INDArray getParam​(String param)
        Get one parameter array for the network.
        In MultiLayerNetwork, parameters are keyed like "0_W" and "0_b" to mean "weights of layer index 0" and "biases of layer index 0" respectively. Numbers increment sequentially, and the suffixes ("W", "b" etc) depend on the layer type, and are defined in the relevant parameter initializers for each layer.
        Note that the returned INDArrays are views of the underlying network parameters, so modifications of the returned arrays will impact the parameters of the network.
        Specified by:
        getParam in interface Model
        Parameters:
        param - the key of the parameter
        Returns:
        The specified parameter array for the network
        See Also:
        paramTable() method, for a map of all parameters
      • paramTable

        public Map<String,​INDArray> paramTable()
        Return a map of all parameters in the network. Parameter names are as described in getParam(String). As per getParam(String) the returned arrays are views - modifications to these will impact the underlying network parameters
        Specified by:
        paramTable in interface Model
        Returns:
        A map of all parameters in the network
      • paramTable

        public Map<String,​INDArray> paramTable​(boolean backpropParamsOnly)
        Returns a map of all parameters in the network as per paramTable().
        Optionally (with backpropParamsOnly=true) only the 'backprop' parameters are returned - that is, any parameters involved only in unsupervised layerwise pretraining not standard inference/backprop are excluded from the returned list.
        Specified by:
        paramTable in interface Model
        Specified by:
        paramTable in interface Trainable
        Parameters:
        backpropParamsOnly - If true, return backprop params only. If false: return all params
        Returns:
        Parameters for the network
      • updaterDivideByMinibatch

        public boolean updaterDivideByMinibatch​(String paramName)
        Intended for internal use
        Specified by:
        updaterDivideByMinibatch in interface Trainable
        Parameters:
        paramName - Name of the parameter
        Returns:
        True if gradients should be divided by minibatch (most params); false otherwise (edge cases like batch norm mean/variance estimates)
      • setParamTable

        public void setParamTable​(Map<String,​INDArray> paramTable)
        Set the parameters of the netowrk. Note that the parameter keys must match the format as described in getParam(String) and paramTable(). Note that the values of the parameters used as an argument to this method are copied - i.e., it is safe to later modify/reuse the values in the provided paramTable without this impacting the network.
        Specified by:
        setParamTable in interface Model
        Parameters:
        paramTable - Parameters to set
      • getLayerWiseConfigurations

        public MultiLayerConfiguration getLayerWiseConfigurations()
        Get the configuration for the network
        Returns:
        Network configuration
      • setLayerWiseConfigurations

        public void setLayerWiseConfigurations​(MultiLayerConfiguration layerWiseConfigurations)
        This method is intended for internal/developer use only.
      • init

        public void init()
        Initialize the MultiLayerNetwork. This should be called once before the network is used. This is functionally equivalent to calling init(null, false).
        Specified by:
        init in interface Model
        Specified by:
        init in interface NeuralNetwork
        See Also:
        init(INDArray, boolean)
      • init

        public void init​(INDArray parameters,
                         boolean cloneParametersArray)
        Initialize the MultiLayerNetwork, optionally with an existing parameters array. If an existing parameters array is specified, it will be used (and the values will not be modified) in the network; if no parameters array is specified, parameters will be initialized randomly according to the network configuration.
        Parameters:
        parameters - Network parameter. May be null. If null: randomly initialize.
        cloneParametersArray - Whether the parameter array (if any) should be cloned, or used directly
      • setGradientsAccumulator

        public void setGradientsAccumulator​(GradientsAccumulator accumulator)
        This method allows you to specificy GradientsAccumulator instance to be used with this model

        PLEASE NOTE: Do not use this method unless you understand how to use GradientsAccumulator & updates sharing.
        PLEASE NOTE: Do not use this method on standalone model
        Parameters:
        accumulator - Gradient accumulator to use for the network
      • isInitCalled

        public boolean isInitCalled()
      • initGradientsView

        public void initGradientsView()
        This method: initializes the flattened gradients array (used in backprop) and sets the appropriate subset in all layers. As a general rule, this shouldn't ever need to be called manually when doing training via fit(DataSet) or fit(DataSetIterator)
      • activateSelectedLayers

        public INDArray activateSelectedLayers​(int from,
                                               int to,
                                               INDArray input)
        Calculate activation for few layers at once. Suitable for autoencoder partial activation. In example: in 10-layer deep autoencoder, layers 0 - 4 inclusive are used for encoding part, and layers 5-9 inclusive are used for decoding part.
        Parameters:
        from - first layer to be activated, inclusive
        to - last layer to be activated, inclusive
        Returns:
        the activation from the last layer
      • feedForward

        public List<INDArray> feedForward​(INDArray input,
                                          boolean train)
        Compute all layer activations, from input to output of the output layer. Note that the input is included in the list: thus feedForward(in,train).get(0) is the inputs, .get(1) is the activations of layer 0, and so on.
        Parameters:
        train - Training: if true, perform forward pass/inference at training time. Usually, inference is performed with train = false. This impacts whether dropout etc is applied or not.
        Returns:
        The list of activations for each layer, including the input
      • feedForward

        public List<INDArray> feedForward​(boolean train,
                                          boolean clearInputs)
        Perform feed-forward, optionally (not) clearing the layer input arrays.
        Note: when using clearInputs=false, there can be some performance and memory overhead: this is because the arrays are defined outside of workspaces (which are enabled by default) - otherwise, old/invalidated arrays could still be accessed after calling this method. Consequently: Don't use clearInputs=false unless you have a use case that requires them to remain after feed-forward has been completed
        Parameters:
        train - training mode (true) or test mode (false)
        clearInputs - If false: don't clear the layer inputs
        Returns:
        Activations from feed-forward
      • feedForwardToLayer

        public List<INDArray> feedForwardToLayer​(int layerNum,
                                                 INDArray input)
        Compute the activations from the input to the specified layer.
        To compute activations for all layers, use feedForward(...) methods
        Note: output list includes the original input. So list.get(0) is always the original input, and list.get(i+1) is the activations of the ith layer.
        Parameters:
        layerNum - Index of the last layer to calculate activations for. Layers are zero-indexed. feedForwardToLayer(i,input) will return the activations for layers 0..i (inclusive)
        input - Input to the network
        Returns:
        list of activations.
      • feedForwardToLayer

        public List<INDArray> feedForwardToLayer​(int layerNum,
                                                 INDArray input,
                                                 boolean train)
        Compute the activations from the input to the specified layer.
        To compute activations for all layers, use feedForward(...) methods
        Note: output list includes the original input. So list.get(0) is always the original input, and list.get(i+1) is the activations of the ith layer.
        Parameters:
        layerNum - Index of the last layer to calculate activations for. Layers are zero-indexed. feedForwardToLayer(i,input) will return the activations for layers 0..i (inclusive)
        input - Input to the network
        train - true for training, false for test (i.e., false if using network after training)
        Returns:
        list of activations.
      • feedForwardToLayer

        public List<INDArray> feedForwardToLayer​(int layerNum,
                                                 boolean train)
        Compute the activations from the input to the specified layer, using the currently set input for the network.
        To compute activations for all layers, use feedForward(...) methods
        Note: output list includes the original input. So list.get(0) is always the original input, and list.get(i+1) is the activations of the ith layer.
        Parameters:
        layerNum - Index of the last layer to calculate activations for. Layers are zero-indexed. feedForwardToLayer(i,input) will return the activations for layers 0..i (inclusive)
        train - true for training, false for test (i.e., false if using network after training)
        Returns:
        list of activations.
      • ffToLayerActivationsDetached

        protected List<INDArray> ffToLayerActivationsDetached​(boolean train,
                                                              @NonNull
                                                              @NonNull FwdPassType fwdPassType,
                                                              boolean storeLastForTBPTT,
                                                              int layerIndex,
                                                              @NonNull
                                                              @NonNull INDArray input,
                                                              INDArray fMask,
                                                              INDArray lMask,
                                                              boolean clearInputs)
        Feed-forward through the network - returning all array activations in a list, detached from any workspace. Note that no workspace should be active externally when calling this method (an exception will be thrown if a workspace is open externally)
        Parameters:
        train - Training mode (true) or test/inference mode (false)
        fwdPassType - Type of forward pass to perform (STANDARD or RNN_ACTIVATE_WITH_STORED_STATE only)
        storeLastForTBPTT - ONLY used if fwdPassType == FwdPassType.RNN_ACTIVATE_WITH_STORED_STATE
        layerIndex - Index (inclusive) to stop forward pass at. For all layers, use numLayers-1
        input - Input to the network
        fMask - Feature mask array. May be null.
        lMask - Label mask array. May be null.
        clearInputs - Whether the layer inputs should be cleared
        Returns:
        List of activations (including the input), detached from any workspace
      • ffToLayerActivationsInWs

        protected List<INDArray> ffToLayerActivationsInWs​(int layerIndex,
                                                          @NonNull
                                                          @NonNull FwdPassType fwdPassType,
                                                          boolean storeLastForTBPTT,
                                                          @NonNull
                                                          @NonNull INDArray input,
                                                          INDArray fMask,
                                                          INDArray lMask)
        Feed-forward through the network at training time - returning a list of all activations in a workspace (WS_ALL_LAYERS_ACT) if workspaces are enabled for training; or detached if no workspaces are used.
        Note: if using workspaces for training, this method requires that WS_ALL_LAYERS_ACT is open externally.
        If using NO workspaces, requires that no external workspace is open
        Note that this method does NOT clear the inputs to each layer - instead, they are in the WS_ALL_LAYERS_ACT workspace for use in later backprop.
        Parameters:
        layerIndex - Index (inclusive) to stop forward pass at. For all layers, use numLayers-1
        fwdPassType - Type of forward pass to perform (STANDARD or RNN_ACTIVATE_WITH_STORED_STATE only)
        storeLastForTBPTT - ONLY used if fwdPassType == FwdPassType.RNN_ACTIVATE_WITH_STORED_STATE
        input - Input to network
        fMask - Feature mask array. May be null
        lMask - Label mask aray. May be null.
        Returns:
      • outputOfLayerDetached

        protected INDArray outputOfLayerDetached​(boolean train,
                                                 @NonNull
                                                 @NonNull FwdPassType fwdPassType,
                                                 int layerIndex,
                                                 @NonNull
                                                 @NonNull INDArray input,
                                                 INDArray featureMask,
                                                 INDArray labelsMask,
                                                 MemoryWorkspace outputWorkspace)
        Provide the output of the specified layer, detached from any workspace. This is most commonly used at inference/test time, and is more memory efficient than ffToLayerActivationsDetached(boolean, FwdPassType, boolean, int, INDArray, INDArray, INDArray, boolean) and ffToLayerActivationsInWs(int, FwdPassType, boolean, INDArray, INDArray, INDArray).
        This method clears all layer inputs. NOTE: in general, no workspaces should be activated externally for this method! This method handles the workspace activation as required
        Parameters:
        train - Training mode (true) or test/inference mode (false)
        fwdPassType - Type of forward pass to perform (STANDARD, RNN_TIMESTEP or RNN_ACTIVATE_WITH_STORED_STATE)
        layerIndex - Index (inclusive) to stop forward pass at. For all layers, use numLayers-1
        input - Input to the network
        featureMask - Input/feature mask array. May be null.
        labelsMask - Labels mask array. May be null
        outputWorkspace - Optional - if provided, outputs should be placed in this workspace. NOTE: this workspace must be open
        Returns:
        Output of the specified layer, detached from any workspace
      • feedForward

        public List<INDArray> feedForward()
        Compute activations of all layers from input (inclusive) to output of the final/output layer. Equivalent to calling feedForward(boolean) with train=false
        Returns:
        the list of activations for each layer, including the input
      • feedForward

        public List<INDArray> feedForward​(INDArray input)
        Compute activations of all layers from input (inclusive) to output of the final/output layer. Equivalent to calling feedForward(INDArray, boolean) with train = false
        Returns:
        the list of activations for each layer, including the input
      • feedForward

        public List<INDArray> feedForward​(INDArray input,
                                          INDArray featuresMask,
                                          INDArray labelsMask)
        Compute the activations from the input to the output layer, given mask arrays (that may be null) The masking arrays are used in situations such an one-to-many and many-to-one rucerrent neural network (RNN) designs, as well as for supporting time series of varying lengths within the same minibatch for RNNs. Other than mask arrays, this is equivalent to calling feedForward(INDArray, boolean) with train = false
      • gradient

        public Gradient gradient()
        Description copied from interface: Model
        Get the gradient. Note that this method will not calculate the gradient, it will rather return the gradient that has been computed before. For calculating the gradient, see Model.computeGradientAndScore(LayerWorkspaceMgr) } .
        Specified by:
        gradient in interface Model
        Returns:
        the gradient for this model, as calculated before
      • gradientAndScore

        public Pair<Gradient,​Double> gradientAndScore()
        Description copied from interface: Model
        Get the gradient and score
        Specified by:
        gradientAndScore in interface Model
        Returns:
        the gradient and score
      • clone

        public MultiLayerNetwork clone()
        Clone the MultiLayerNetwork
        Overrides:
        clone in class Object
        Returns:
        A cloned MultiLayerNetwork with a copy of the configuration, parameters and updater identical to the current network.
      • hasAFrozenLayer

        protected boolean hasAFrozenLayer()
      • params

        public INDArray params()
        Returns a 1 x m vector where the vector is composed of a flattened vector of all of the parameters in the network.
        See getParam(String) and paramTable() for a more useful/interpretable representation of the parameters.
        Note that the parameter vector is not a copy, and changes to the returned INDArray will impact the network parameters.
        Specified by:
        params in interface Model
        Specified by:
        params in interface NeuralNetwork
        Specified by:
        params in interface Trainable
        Returns:
        the parameters for this neural net
      • setParams

        public void setParams​(INDArray params)
        Set the parameters for this model. This expects a linear ndarray which then be unpacked internally relative to the expected ordering of the model.
        See also: setParamTable(Map) and setParam(String, INDArray)
        Specified by:
        setParams in interface Model
        Parameters:
        params - the parameters for the model
      • setParamsViewArray

        public void setParamsViewArray​(INDArray params)
        Description copied from interface: Model
        Set the initial parameters array as a view of the full (backprop) network parameters NOTE: this is intended to be used internally in MultiLayerNetwork and ComputationGraph, not by users.
        Specified by:
        setParamsViewArray in interface Model
        Parameters:
        params - a 1 x nParams row vector that is a view of the larger (MLN/CG) parameters array
      • setBackpropGradientsViewArray

        public void setBackpropGradientsViewArray​(INDArray gradients)
        Description copied from interface: Model
        Set the gradients array as a view of the full (backprop) network parameters NOTE: this is intended to be used internally in MultiLayerNetwork and ComputationGraph, not by users.
        Specified by:
        setBackpropGradientsViewArray in interface Model
        Parameters:
        gradients - a 1 x nParams row vector that is a view of the larger (MLN/CG) gradients array
      • numParams

        public long numParams()
        Returns the number of parameters in the network
        Specified by:
        numParams in interface Model
        Specified by:
        numParams in interface Trainable
        Returns:
        The number of parameters
      • numParams

        public long numParams​(boolean backwards)
        Returns the number of parameters in the network
        Specified by:
        numParams in interface Model
        Parameters:
        backwards - If true: exclude any parameters uned only in unsupervised layerwise training (such as the decoder parameters in an autoencoder)
        Returns:
        The number of parameters
      • f1Score

        public double f1Score​(DataSet data)
        Sets the input and labels and returns the F1 score for the prediction with respect to the true labels
        Specified by:
        f1Score in interface Classifier
        Parameters:
        data - the data to score
        Returns:
        the score for the given input,label pairs
      • fit

        public void fit​(@NonNull
                        @NonNull DataSetIterator iterator,
                        int numEpochs)
        Perform minibatch training on all minibatches in the DataSetIterator, for the specified number of epochs. Equvalent to calling fit(DataSetIterator) numEpochs times in a loop
        Parameters:
        iterator - Training data (DataSetIterator). Iterator must support resetting
        numEpochs - Number of training epochs, >= 1
      • fit

        public void fit​(DataSetIterator iterator)
        Perform minibatch training on all minibatches in the DataSetIterator for 1 epoch.
        Note that this method does not do layerwise pretraining.
        For pretraining use method pretrain.. pretrain(DataSetIterator)
        Specified by:
        fit in interface Classifier
        Specified by:
        fit in interface NeuralNetwork
        Parameters:
        iterator - Training data (DataSetIterator)
      • calculateGradients

        public Pair<Gradient,​INDArray> calculateGradients​(@NonNull
                                                                @NonNull INDArray features,
                                                                @NonNull
                                                                @NonNull INDArray label,
                                                                INDArray fMask,
                                                                INDArray labelMask)
        Calculate parameter gradients and input activation gradients given the input and labels, and optionally mask arrays
        Parameters:
        features - Features for gradient calculation
        label - Labels for gradient
        fMask - Features mask array (may be null)
        labelMask - Label mask array (may be null)
        Returns:
        A pair of gradient arrays: parameter gradients (in Gradient object) and input activation gradients
      • calcBackpropGradients

        protected Pair<Gradient,​INDArray> calcBackpropGradients​(INDArray epsilon,
                                                                      boolean withOutputLayer,
                                                                      boolean tbptt,
                                                                      boolean returnInputActGrad)
        Calculate gradients and errors. Used in two places: (a) backprop (for standard multi layer network learning) (b) backpropGradient (layer method, for when MultiLayerNetwork is used as a layer)
        Parameters:
        epsilon - Errors (technically errors .* activations). Not used if withOutputLayer = true
        withOutputLayer - if true: assume last layer is output layer, and calculate errors based on labels. In this case, the epsilon input is not used (may/should be null). If false: calculate backprop gradients
        returnInputActGrad - If true: terun the input activation gradients (detached). False: don't return
        Returns:
        Gradients and the error (epsilon) at the input
      • updateRnnStateWithTBPTTState

        public void updateRnnStateWithTBPTTState()
        Intended for internal/developer use
      • addListeners

        public void addListeners​(TrainingListener... listeners)
        This method ADDS additional TrainingListener to existing listeners
        Specified by:
        addListeners in interface Model
        Parameters:
        listeners -
      • setListeners

        public void setListeners​(TrainingListener... listeners)
        Description copied from interface: Model
        Set the trainingListeners for the ComputationGraph (and all layers in the network)
        Specified by:
        setListeners in interface Layer
        Specified by:
        setListeners in interface Model
      • predict

        public int[] predict​(INDArray d)
        Usable only for classification networks in conjunction with OutputLayer. Cannot be used with RnnOutputLayer, CnnLossLayer, or networks used for regression.
        To get the raw output activations of the output layer, use output(INDArray) or similar.

        Equivalent to argmax(this.output(input)): Returns the predicted class indices corresponding to the predictions for each example in the features array.
        Specified by:
        predict in interface Classifier
        Parameters:
        d - The input features to perform inference on
        Returns:
        The predicted class index for each example
      • predict

        public List<String> predict​(DataSet dataSet)
        As per predict(INDArray) but the returned values are looked up from the list of label names in the provided DataSet
        Specified by:
        predict in interface Classifier
        Parameters:
        dataSet - the examples to classify
        Returns:
        the labels for each example
      • fit

        public void fit​(INDArray data,
                        INDArray labels)
        Fit the model for one iteration on the provided data
        Specified by:
        fit in interface Classifier
        Parameters:
        data - the examples to classify (one example in each row)
        labels - the example labels(a binary outcome matrix)
      • fit

        public void fit​(INDArray features,
                        INDArray labels,
                        INDArray featuresMask,
                        INDArray labelsMask)
        Fit the model for one iteration on the provided data
        Parameters:
        features - the examples to classify (one example in each row)
        labels - the example labels(a binary outcome matrix)
        featuresMask - The mask array for the features (used for variable length time series, etc). May be null.
        labelsMask - The mask array for the labels (used for variable length time series, etc). May be null.
      • fit

        public void fit​(INDArray data,
                        LayerWorkspaceMgr workspaceMgr)
        Description copied from interface: Model
        Fit the model to the given data
        Specified by:
        fit in interface Model
        Parameters:
        data - the data to fit the model to
      • fit

        public void fit​(DataSet data)
        Fit the model for one iteration on the provided data
        Specified by:
        fit in interface Classifier
        Specified by:
        fit in interface NeuralNetwork
        Parameters:
        data - the data to train on
      • fit

        public void fit​(INDArray examples,
                        int[] labels)
        Fit the model for one iteration on the provided data
        Specified by:
        fit in interface Classifier
        Parameters:
        examples - the examples to classify (one example in each row)
        labels - the labels for each example (the number of labels must match
      • output

        public INDArray output​(INDArray input,
                               Layer.TrainingMode train)
        Perform inference on the provided input/features - i.e., perform forward pass using the provided input/features and return the output of the final layer.
        Parameters:
        input - Input to the network
        train - whether the output is test or train. This mainly affect hyper parameters such as dropout and batch normalization, which have different behaviour for test vs. train
        Returns:
        The network predictions - i.e., the activations of the final layer
      • output

        public INDArray output​(INDArray input,
                               boolean train)
        Perform inference on the provided input/features - i.e., perform forward pass using the provided input/features and return the output of the final layer.
        Parameters:
        input - Input to the network
        train - whether the output is test or train. This mainly affect hyper parameters such as dropout and batch normalization, which have different behaviour for test vs. train
        Returns:
        The network predictions - i.e., the activations of the final layer
      • output

        public INDArray output​(INDArray input,
                               boolean train,
                               INDArray featuresMask,
                               INDArray labelsMask)
        Calculate the output of the network, with masking arrays. The masking arrays are used in situations such as one-to-many and many-to-one recurrent neural network (RNN) designs, as well as for supporting time series of varying lengths within the same minibatch.
      • output

        public INDArray output​(INDArray input,
                               boolean train,
                               MemoryWorkspace outputWorkspace)
        Get the network output, which is optionally placed in the specified memory workspace.
        If no memory workspace is provided, the output will be detached (not in any workspace).
        If a memory workspace is provided, the output activation array (i.e., the INDArray returned by this method) will be placed in the specified workspace. This workspace must be opened by the user before calling this method - and the user is responsible for (a) closing this workspace, and (b) ensuring the output array is not used out of scope (i.e., not used after closing the workspace to which it belongs - as this is likely to cause either an exception when used, or a crash).
        Parameters:
        input - Input to the network
        train - True for train, false otherwise
        outputWorkspace - May be null. If not null: the workspace MUST be opened before calling this method.
        Returns:
        The output/activations from the network (either detached or in the specified workspace if provided)
      • output

        public INDArray output​(INDArray input,
                               boolean train,
                               INDArray featuresMask,
                               INDArray labelsMask,
                               MemoryWorkspace outputWorkspace)
        Get the network output, which is optionally placed in the specified memory workspace.
        If no memory workspace is provided, the output will be detached (not in any workspace).
        If a memory workspace is provided, the output activation array (i.e., the INDArray returned by this method) will be placed in the specified workspace. This workspace must be opened by the user before calling this method - and the user is responsible for (a) closing this workspace, and (b) ensuring the output array is not used out of scope (i.e., not used after closing the workspace to which it belongs - as this is likely to cause either an exception when used, or a crash).
        Parameters:
        input - Input to the network
        train - True for train, false otherwise
        outputWorkspace - May be null. If not null: the workspace MUST be opened before calling this method.
        Returns:
        The output/activations from the network (either detached or in the specified workspace if provided)
      • output

        public <T> T output​(@NonNull
                            @NonNull INDArray inputs,
                            INDArray inputMasks,
                            INDArray labelMasks,
                            @NonNull
                            @NonNull OutputAdapter<T> outputAdapter)
        This method uses provided OutputAdapter to return custom object built from INDArray PLEASE NOTE: This method uses dedicated Workspace for output generation to avoid redundant allocations
        Type Parameters:
        T - T extends Object
        Parameters:
        inputs - Input arrays to the netwonk
        inputMasks - Optional input mask arrays (may be null)
        labelMasks - Optional label mask arrays (may be null
        outputAdapter - OutputAdapter instance
        Returns:
        T instance produced by OutputAdapter
      • output

        public INDArray output​(INDArray input)
        Perform inference on the provided input/features - i.e., perform forward pass using the provided input/features and return the output of the final layer. Equivalent to output(INDArray, boolean) with train=false - i.e., this method is used for inference.
        Parameters:
        input - Input to the network
        Returns:
        The network predictions - i.e., the activations of the final layer
      • output

        public INDArray output​(DataSetIterator iterator,
                               boolean train)
        Generate the output for all examples/batches in the input iterator, and concatenate them into a single array. See output(INDArray)
        NOTE 1: The output array can require a considerable amount of memory for iterators with a large number of examples
        NOTE 2: This method cannot be used for variable length time series outputs, as this would require padding arrays for some outputs, or returning a mask array (which cannot be done with this method). For variable length time series applications, use one of the other output methods. This method also cannot be used with fully convolutional networks with different output sizes (for example, segmentation on different input image sizes).
        Parameters:
        iterator - Data to pass through the network
        Returns:
        output for all examples in the iterator, concatenated into a
      • f1Score

        public double f1Score​(INDArray input,
                              INDArray labels)
        Perform inference and then calculate the F1 score of the output(input) vs. the labels.
        Specified by:
        f1Score in interface Classifier
        Parameters:
        input - the input to perform inference with
        labels - the true labels
        Returns:
        the score for the given input,label pairs
      • numLabels

        @Deprecated
        public int numLabels()
        Deprecated.
        Will be removed in a future release
        Description copied from interface: Classifier
        Returns the number of possible labels
        Specified by:
        numLabels in interface Classifier
        Returns:
        the number of possible labels for this classifier
      • score

        public double score​(DataSet data)
        Sets the input and labels and calculates the score (value of the output layer loss function plus l1/l2 if applicable) for the prediction with respect to the true labels
        This is equivalent to score(DataSet, boolean) with training==false.
        Parameters:
        data - the data to score
        Returns:
        the score for the given input,label pairs
        See Also:
        score(DataSet, boolean)
      • score

        public double score​(DataSet data,
                            boolean training)
        Sets the input and labels and calculates the score (value of the output layer loss function plus l1/l2 if applicable) for the prediction with respect to the true labels
        Parameters:
        data - data to calculate score for
        training - If true: score during training. If false: score at test time. This can affect the application of certain features, such as dropout and dropconnect (which are applied at training time only)
        Returns:
        the score (value of the loss function)
      • scoreExamples

        public INDArray scoreExamples​(DataSet data,
                                      boolean addRegularizationTerms)
        Calculate the score for each example in a DataSet individually. Unlike score(DataSet) and score(DataSet, boolean) this method does not average/sum over examples. This method allows for examples to be scored individually (at test time only), which may be useful for example for autoencoder architectures and the like.
        Each row of the output (assuming addRegularizationTerms == true) is equivalent to calling score(DataSet) with a single example.
        Parameters:
        data - The data to score
        addRegularizationTerms - If true: add l1/l2 regularization terms (if any) to the score. If false: don't add regularization terms
        Returns:
        An INDArray (column vector) of size input.numRows(); the ith entry is the score (loss value) of the ith example
      • fit

        public void fit()
        Description copied from interface: Model
        All models have a fit method
        Specified by:
        fit in interface Model
      • update

        public void update​(INDArray gradient,
                           String paramType)
        Description copied from interface: Model
        Perform one update applying the gradient
        Specified by:
        update in interface Model
        Parameters:
        gradient - the gradient to apply
      • score

        public double score()
        Score of the model (relative to the objective function) - previously calculated on the last minibatch
        Specified by:
        score in interface Model
        Returns:
        the score of the model (relative to the objective function)
      • setScore

        public void setScore​(double score)
        Intended for developer/internal use
      • computeGradientAndScore

        public void computeGradientAndScore()
      • clear

        public void clear()
        Clear the inputs. Clears optimizer state.
        Specified by:
        clear in interface Model
      • applyConstraints

        public void applyConstraints​(int iteration,
                                     int epoch)
        Description copied from interface: Model
        Apply any constraints to the model
        Specified by:
        applyConstraints in interface Model
      • setInput

        public void setInput​(INDArray input)
        Set the input array for the network
        Parameters:
        input - Input array to set
      • getOutputLayer

        public Layer getOutputLayer()
        Get the output layer - i.e., the last layer in the netwok
        Returns:
      • getDefaultConfiguration

        public NeuralNetConfiguration getDefaultConfiguration()
        Intended for internal/developer use
      • getLabels

        public INDArray getLabels()
      • setLabels

        public void setLabels​(INDArray labels)
        Parameters:
        labels - Labels to set
      • getnLayers

        public int getnLayers()
        Get the number of layers in the network
        Returns:
        the number of layers in the network
      • getLayers

        public Layer[] getLayers()
        Returns:
        The layers in the network
      • getLayer

        public Layer getLayer​(int i)
      • getLayerNames

        public List<String> getLayerNames()
      • setLayers

        public void setLayers​(Layer[] layers)
      • setMask

        public void setMask​(INDArray mask)
      • isPretrainLayer

        public boolean isPretrainLayer()
        Description copied from interface: Layer
        Returns true if the layer can be trained in an unsupervised/pretrain manner (AE, VAE, etc)
        Specified by:
        isPretrainLayer in interface Layer
        Returns:
        true if the layer can be pretrained (using fit(INDArray), false otherwise
      • allowInputModification

        public void allowInputModification​(boolean allow)
        Description copied from interface: Layer
        A performance optimization: mark whether the layer is allowed to modify its input array in-place. In many cases, this is totally safe - in others, the input array will be shared by multiple layers, and hence it's not safe to modify the input array. This is usually used by ops such as dropout.
        Specified by:
        allowInputModification in interface Layer
        Parameters:
        allow - If true: the input array is safe to modify. If false: the input array should be copied before it is modified (i.e., in-place modifications are un-safe)
      • feedForwardMaskArray

        public Pair<INDArray,​MaskState> feedForwardMaskArray​(INDArray maskArray,
                                                                   MaskState currentMaskState,
                                                                   int minibatchSize)
        Description copied from interface: Layer
        Feed forward the input mask array, setting in the layer as appropriate. This allows different layers to handle masks differently - for example, bidirectional RNNs and normal RNNs operate differently with masks (the former sets activations to 0 outside of the data present region (and keeps the mask active for future layers like dense layers), whereas normal RNNs don't zero out the activations/errors )instead relying on backpropagated error arrays to handle the variable length case.
        This is also used for example for networks that contain global pooling layers, arbitrary preprocessors, etc.
        Specified by:
        feedForwardMaskArray in interface Layer
        Parameters:
        maskArray - Mask array to set
        currentMaskState - Current state of the mask - see MaskState
        minibatchSize - Current minibatch size. Needs to be known as it cannot always be inferred from the activations array due to reshaping (such as a DenseLayer within a recurrent neural network)
        Returns:
        New mask array after this layer, along with the new mask state.
      • getHelper

        public LayerHelper getHelper()
        Specified by:
        getHelper in interface Layer
        Returns:
        Get the layer helper, if any
      • type

        public Layer.Type type()
        Description copied from interface: Layer
        Returns the layer type
        Specified by:
        type in interface Layer
        Returns:
      • backpropGradient

        public Pair<Gradient,​INDArray> backpropGradient​(INDArray epsilon,
                                                              LayerWorkspaceMgr workspaceMgr)
        Description copied from interface: Layer
        Calculate the gradient relative to the error in the next layer
        Specified by:
        backpropGradient in interface Layer
        Parameters:
        epsilon - w^(L+1)*delta^(L+1). Or, equiv: dC/da, i.e., (dC/dz)*(dz/da) = dC/da, where C is cost function a=sigma(z) is activation.
        workspaceMgr - Workspace manager
        Returns:
        Pair where Gradient is gradient for this layer, INDArray is epsilon (activation gradient) needed by next layer, but before element-wise multiply by sigmaPrime(z). So for standard feed-forward layer, if this layer is L, then return.getSecond() == dL/dIn = (w^(L)*(delta^(L))^T)^T. Note that the returned array should be placed in the ArrayType.ACTIVATION_GRAD workspace via the workspace manager
      • setIndex

        public void setIndex​(int index)
        Description copied from interface: Layer
        Set the layer index.
        Specified by:
        setIndex in interface Layer
      • getIndex

        public int getIndex()
        Description copied from interface: Layer
        Get the layer index.
        Specified by:
        getIndex in interface Layer
      • getIterationCount

        public int getIterationCount()
        Specified by:
        getIterationCount in interface Layer
        Returns:
        The current iteration count (number of parameter updates) for the layer/network
      • getEpochCount

        public int getEpochCount()
        Specified by:
        getEpochCount in interface Layer
        Returns:
        The current epoch count (number of training epochs passed) for the layer/network
      • setIterationCount

        public void setIterationCount​(int iterationCount)
        Description copied from interface: Layer
        Set the current iteration count (number of parameter updates) for the layer/network
        Specified by:
        setIterationCount in interface Layer
      • setEpochCount

        public void setEpochCount​(int epochCount)
        Description copied from interface: Layer
        Set the current epoch count (number of epochs passed ) for the layer/network
        Specified by:
        setEpochCount in interface Layer
      • calcRegularizationScore

        public double calcRegularizationScore​(boolean backpropParamsOnly)
        Description copied from interface: Layer
        Calculate the regularization component of the score, for the parameters in this layer
        For example, the L1, L2 and/or weight decay components of the loss function
        Specified by:
        calcRegularizationScore in interface Layer
        Parameters:
        backpropParamsOnly - If true: calculate regularization score based on backprop params only. If false: calculate based on all params (including pretrain params, if any)
        Returns:
        the regularization score of
      • update

        public void update​(Gradient gradient)
        Description copied from interface: Model
        Update layer weights and biases with gradient change
        Specified by:
        update in interface Model
      • activate

        public INDArray activate​(boolean training,
                                 LayerWorkspaceMgr mgr)
        Description copied from interface: Layer
        Perform forward pass and return the activations array with the last set input
        Specified by:
        activate in interface Layer
        Parameters:
        training - training or test mode
        mgr - Workspace manager
        Returns:
        the activation (layer output) of the last specified input. Note that the returned array should be placed in the ArrayType.ACTIVATIONS workspace via the workspace manager
      • activate

        public INDArray activate​(INDArray input,
                                 boolean training,
                                 LayerWorkspaceMgr mgr)
        Description copied from interface: Layer
        Perform forward pass and return the activations array with the specified input
        Specified by:
        activate in interface Layer
        Parameters:
        input - the input to use
        training - train or test mode
        mgr - Workspace manager.
        Returns:
        Activations array. Note that the returned array should be placed in the ArrayType.ACTIVATIONS workspace via the workspace manager
      • setInputMiniBatchSize

        public void setInputMiniBatchSize​(int size)
        Description copied from interface: Layer
        Set current/last input mini-batch size.
        Used for score and gradient calculations. Mini batch size may be different from getInput().size(0) due to reshaping operations - for example, when using RNNs with DenseLayer and OutputLayer. Called automatically during forward pass.
        Specified by:
        setInputMiniBatchSize in interface Layer
      • rnnTimeStep

        public INDArray rnnTimeStep​(INDArray input)
        If this MultiLayerNetwork contains one or more RNN layers: conduct forward pass (prediction) but using previous stored state for any RNN layers. The activations for the final step are also stored in the RNN layers for use next time rnnTimeStep() is called.
        This method can be used to generate output one or more steps at a time instead of always having to do forward pass from t=0. Example uses are for streaming data, and for generating samples from network output one step at a time (where samples are then fed back into the network as input)
        If no previous state is present in RNN layers (i.e., initially or after calling rnnClearPreviousState()), the default initialization (usually 0) is used.
        Supports mini-batch (i.e., multiple predictions/forward pass in parallel) as well as for single examples.
        Parameters:
        input - Input to network. May be for one or multiple time steps. For single time step: input has shape [miniBatchSize,inputSize] or [miniBatchSize,inputSize,1]. miniBatchSize=1 for single example.
        For multiple time steps: [miniBatchSize,inputSize,inputTimeSeriesLength]
        Returns:
        Output activations. If output is RNN layer (such as RnnOutputLayer): if input has shape [miniBatchSize,inputSize] i.e., is 2d, output has shape [miniBatchSize,outputSize] (i.e., also 2d).
        Otherwise output is 3d [miniBatchSize,outputSize,inputTimeSeriesLength] when using RnnOutputLayer.
        See Also:
        For outputting the activations in the specified workspace
      • rnnTimeStep

        public INDArray rnnTimeStep​(INDArray input,
                                    MemoryWorkspace outputWorkspace)
        See rnnTimeStep(INDArray) for details
        If no memory workspace is provided, the output will be detached (not in any workspace).
        If a memory workspace is provided, the output activation array (i.e., the INDArray returned by this method) will be placed in the specified workspace. This workspace must be opened by the user before calling this method - and the user is responsible for (a) closing this workspace, and (b) ensuring the output array is not used out of scope (i.e., not used after closing the workspace to which it belongs - as this is likely to cause either an exception when used, or a crash).
        Parameters:
        input - Input activations
        outputWorkspace - Output workspace. May be null
        Returns:
        The output/activations from the network (either detached or in the specified workspace if provided)
      • rnnGetPreviousState

        public Map<String,​INDArray> rnnGetPreviousState​(int layer)
        Get the state of the RNN layer, as used in rnnTimeStep().
        Parameters:
        layer - Number/index of the layer.
        Returns:
        Hidden state, or null if layer is not an RNN layer
      • rnnSetPreviousState

        public void rnnSetPreviousState​(int layer,
                                        Map<String,​INDArray> state)
        Set the state of the RNN layer.
        Parameters:
        layer - The number/index of the layer.
        state - The state to set the specified layer to
      • rnnClearPreviousState

        public void rnnClearPreviousState()
        Clear the previous state of the RNN layers (if any).
      • rnnActivateUsingStoredState

        public List<INDArray> rnnActivateUsingStoredState​(INDArray input,
                                                          boolean training,
                                                          boolean storeLastForTBPTT)
        Similar to rnnTimeStep and feedForward() methods. Difference here is that this method:
        (a) like rnnTimeStep does forward pass using stored state for RNN layers, and
        (b) unlike rnnTimeStep does not modify the RNN layer state
        Therefore multiple calls to this method with the same input should have the same output.
        Typically used during training only. Use rnnTimeStep for prediction/forward pass at test time.
        Parameters:
        input - Input to network
        training - Whether training or not
        storeLastForTBPTT - set to true if used as part of truncated BPTT training
        Returns:
        Activations for each layer (including input, as per feedforward() etc)
      • getUpdater

        public Updater getUpdater()
        Get the updater for this MultiLayerNetwork
        Returns:
        Updater for MultiLayerNetwork
      • getUpdater

        public Updater getUpdater​(boolean initializeIfReq)
      • setUpdater

        public void setUpdater​(Updater updater)
        Set the updater for the MultiLayerNetwork
      • setLayerMaskArrays

        public void setLayerMaskArrays​(INDArray featuresMaskArray,
                                       INDArray labelsMaskArray)
        Set the mask arrays for features and labels. Mask arrays are typically used in situations such as one-to-many and many-to-one learning with recurrent neural networks, as well as for supporting time series of varying lengths within the same minibatch.
        For example, with RNN data sets with input of shape [miniBatchSize,nIn,timeSeriesLength] and outputs of shape [miniBatchSize,nOut,timeSeriesLength], the features and mask arrays will have shape [miniBatchSize,timeSeriesLength] and contain values 0 or 1 at each element (to specify whether a given input/example is present - or merely padding - at a given time step).
        NOTE: This method is not usually used directly. Instead, methods such as feedForward(INDArray, INDArray, INDArray) and output(INDArray, boolean, INDArray, INDArray) handle setting of masking internally.
        Parameters:
        featuresMaskArray - Mask array for features (input)
        labelsMaskArray - Mask array for labels (output)
        See Also:
        clearLayerMaskArrays()
      • evaluate

        public <T extends Evaluation> T evaluate​(@NonNull
                                                 @NonNull DataSetIterator iterator)
        Evaluate the network (classification performance)
        Parameters:
        iterator - Iterator to evaluate on
        Returns:
        Evaluation object; results of evaluation on all examples in the data set
      • evaluate

        public Evaluation evaluate​(@NonNull
                                   @NonNull MultiDataSetIterator iterator)
        Evaluate the network (classification performance). Can only be used with MultiDataSetIterator instances with a single input/output array
        Parameters:
        iterator - Iterator to evaluate on
        Returns:
        Evaluation object; results of evaluation on all examples in the data set
      • evaluateRegression

        public <T extends RegressionEvaluation> T evaluateRegression​(DataSetIterator iterator)
        Evaluate the network for regression performance
        Parameters:
        iterator - Data to evaluate on
        Returns:
        Regression evaluation
      • evaluateRegression

        public RegressionEvaluation evaluateRegression​(MultiDataSetIterator iterator)
        Evaluate the network for regression performance Can only be used with MultiDataSetIterator instances with a single input/output array
        Parameters:
        iterator - Data to evaluate on
      • evaluateROC

        public <T extends ROC> T evaluateROC​(DataSetIterator iterator,
                                             int rocThresholdSteps)
        Evaluate the network (must be a binary classifier) on the specified data, using the ROC class
        Parameters:
        iterator - Data to evaluate on
        rocThresholdSteps - Number of threshold steps to use with ROC - see that class for details.
        Returns:
        ROC evaluation on the given dataset
      • evaluateROCMultiClass

        public <T extends ROCMultiClass> T evaluateROCMultiClass​(DataSetIterator iterator,
                                                                 int rocThresholdSteps)
        Evaluate the network on the specified data, using the ROCMultiClass class
        Parameters:
        iterator - Data to evaluate on
        rocThresholdSteps - Number of threshold steps to use with ROCMultiClass
        Returns:
        Multi-class ROC evaluation on the given dataset
      • doEvaluation

        public <T extends IEvaluation> T[] doEvaluation​(DataSetIterator iterator,
                                                        T... evaluations)
        Perform evaluation using an arbitrary IEvaluation instance.
        Specified by:
        doEvaluation in interface NeuralNetwork
        Parameters:
        iterator - data to evaluate on
      • evaluate

        public Evaluation evaluate​(DataSetIterator iterator,
                                   List<String> labelsList)
        Evaluate the network on the provided data set. Used for evaluating the performance of classifiers
        Parameters:
        iterator - Data to undertake evaluation on
        Returns:
        Evaluation object, summarizing the results of the evaluation on the provided DataSetIterator
      • fit

        public void fit​(@NonNull
                        @NonNull MultiDataSetIterator iterator,
                        int numEpochs)
        Perform minibatch training on all minibatches in the MultiDataSetIterator, for the specified number of epochs. Equvalent to calling fit(MultiDataSetIterator) numEpochs times in a loop
        Parameters:
        iterator - Training data (DataSetIterator). Iterator must support resetting
        numEpochs - Number of training epochs, >= 1
      • fit

        public void fit​(MultiDataSetIterator iterator)
        Perform minibatch training on all minibatches in the MultiDataSetIterator.
        Note: The MultiDataSets in the MultiDataSetIterator must have exactly 1 input and output array (as MultiLayerNetwork only supports 1 input and 1 output)
        Specified by:
        fit in interface NeuralNetwork
        Parameters:
        iterator - Training data (DataSetIterator). Iterator must support resetting
      • evaluate

        public Evaluation evaluate​(DataSetIterator iterator,
                                   List<String> labelsList,
                                   int topN)
        Evaluate the network (for classification) on the provided data set, with top N accuracy in addition to standard accuracy. For 'standard' accuracy evaluation only, use topN = 1
        Parameters:
        iterator - Iterator (data) to evaluate on
        labelsList - List of labels. May be null.
        topN - N value for top N accuracy evaluation
        Returns:
        Evaluation object, summarizing the results of the evaluation on the provided DataSetIterator
      • update

        protected void update​(Task task)
      • summary

        public String summary()
        String detailing the architecture of the multilayernetwork. Columns are LayerIndex with layer type, nIn, nOut, Total number of parameters and the Shapes of the parameters Will also give information about frozen layers, if any.
        Returns:
        Summary as a string
        See Also:
        memoryInfo(int, InputType)
      • summary

        public String summary​(InputType inputType)
        String detailing the architecture of the multilayernetwork. Will also display activation size when given an input type. Columns are LayerIndex with layer type, nIn, nOut, Total number of parameters, Shapes of the parameters, Input activation shape, Output activation shape Will also give information about frozen layers, if any.
        Returns:
        Summary as a string
        See Also:
        memoryInfo(int, InputType)
      • memoryInfo

        public String memoryInfo​(int minibatch,
                                 InputType inputType)
        Generate information regarding memory use for the network, for the given input type and minibatch size. Note that when using workspaces or CuDNN, the network should be trained for some iterations so that the memory workspaces have time to initialize. Without this, the memory requirements during training may be underestimated. Note also that this is the same information that is generated during an OOM crash when training or performing inference.
        Parameters:
        minibatch - Minibatch size to estimate memory for
        inputType - Input type to the network
        Returns:
        A String with information about network memory use information
      • clearLayersStates

        public void clearLayersStates()
        This method just makes sure there's no state preserved within layers
      • incrementEpochCount

        public void incrementEpochCount()
        Increment the epoch count (in the underlying MultiLayerConfiguration by 1). Note that this is done automatically when using iterator-based fitting methods, such as fit(DataSetIterator). However, when using non-iterator fit methods (DataSet, INDArray/INDArray etc), the network has no way to know when one epoch ends and another starts. In such situations, this method can be used to increment the epoch counter.
        Note that the epoch counter is used for situations such as some learning rate schedules, and the like. The current epoch count can be obtained using MultiLayerConfiguration.getLayerwiseConfiguration().getEpochCount()
      • synchronizeIterEpochCounts

        protected void synchronizeIterEpochCounts()
      • toComputationGraph

        public ComputationGraph toComputationGraph()
        Convert this MultiLayerNetwork to a ComputationGraph
        Returns:
        ComputationGraph equivalent to this network (including parameters and updater state)
      • convertDataType

        public MultiLayerNetwork convertDataType​(@NonNull
                                                 @NonNull DataType dataType)
        Return a copy of the network with the parameters and activations set to use the specified (floating point) data type. If the existing datatype is the same as the requested dataype, the original network will be returned unchanged. Only floating point datatypes (DOUBLE, FLOAT, HALF) may be used.
        Parameters:
        dataType - Datatype to convert the network to
        Returns:
        The network, set to use the specified datatype for the parameters and activations
      • setLearningRate

        public void setLearningRate​(double newLr)
        Set the learning rate for all layers in the network to the specified value. Note that if any learning rate schedules are currently present, these will be removed in favor of the new (fixed) learning rate.

        Note: This method not free from a performance point of view: a proper learning rate schedule should be used in preference to calling this method at every iteration.
        Parameters:
        newLr - New learning rate for all layers
        See Also:
        setLearningRate(ISchedule), setLearningRate(int, double)
      • setLearningRate

        public void setLearningRate​(ISchedule newLr)
        Set the learning rate schedule for all layers in the network to the specified schedule. This schedule will replace any/all existing schedules, and also any fixed learning rate values.
        Note that the iteration/epoch counts will not be reset. Use MultiLayerConfiguration#setIterationCount(int) and MultiLayerConfiguration.setEpochCount(int) if this is required
        Parameters:
        newLr - New learning rate schedule for all layers
        See Also:
        setLearningRate(ISchedule), setLearningRate(int, double)
      • setLearningRate

        public void setLearningRate​(int layerNumber,
                                    double newLr)
        Set the learning rate for a single layer in the network to the specified value. Note that if any learning rate schedules are currently present, these will be removed in favor of the new (fixed) learning rate.

        Note: This method not free from a performance point of view: a proper learning rate schedule should be used in preference to calling this method at every iteration. Note also that setLearningRate(double) should also be used in preference, when all layers need to be set to a new LR
        Parameters:
        layerNumber - Number of the layer to set the LR for
        newLr - New learning rate for a single layer
        See Also:
        setLearningRate(ISchedule), setLearningRate(int, double)
      • setLearningRate

        public void setLearningRate​(int layerNumber,
                                    ISchedule newLr)
        Set the learning rate schedule for a single layer in the network to the specified value.
        Note also that setLearningRate(ISchedule) should also be used in preference, when all layers need to be set to a new LR schedule.
        This schedule will replace any/all existing schedules, and also any fixed learning rate values.
        Note also that the iteration/epoch counts will not be reset. Use MultiLayerConfiguration#setIterationCount(int) and MultiLayerConfiguration.setEpochCount(int) if this is required
        Parameters:
        layerNumber - Number of the layer to set the LR schedule for
        newLr - New learning rate for a single layer
        See Also:
        setLearningRate(ISchedule), setLearningRate(int, double)
      • getLearningRate

        public Double getLearningRate​(int layerNumber)
        Get the current learning rate, for the specified layer, from the network. Note: If the layer has no learning rate (no parameters, or an updater without a learning rate) then null is returned
        Parameters:
        layerNumber - Layer number to get the learning rate for
        Returns:
        Learning rate for the specified layer, or null
      • layerSize

        public int layerSize​(int layer)
        Return the layer size (number of units) for the specified layer.
        Note that the meaning of the "layer size" can depend on the type of layer. For example:
        - DenseLayer, OutputLayer, recurrent layers: number of units (nOut configuration option)
        - ConvolutionLayer: the channels (number of channels)
        - Subsampling layers, global pooling layers, etc: size of 0 is always returned
        Parameters:
        layer - Index of the layer to get the size of. Must be in range 0 to nLayers-1 inclusive
        Returns:
        Size of the layer
      • layerInputSize

        public int layerInputSize​(int layer)
        Return the input size (number of inputs) for the specified layer.
        Note that the meaning of the "input size" can depend on the type of layer. For example:
        - DenseLayer, OutputLayer, etc: the feature vector size (nIn configuration option)
        - Recurrent layers: the feature vector size per time step (nIn configuration option)
        - ConvolutionLayer: the channels (number of channels)
        - Subsampling layers, global pooling layers, etc: size of 0 is always returned
        Parameters:
        layer - Index of the layer to get the size of. Must be in range 0 to nLayers-1 inclusive
        Returns:
        Size of the layer
      • equals

        public boolean equals​(Object obj)
        Indicates whether some other object is "equal to" this one.

        The equals method implements an equivalence relation on non-null object references:

        • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
        • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
        • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
        • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
        • For any non-null reference value x, x.equals(null) should return false.

        The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

        Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

        Overrides:
        equals in class Object
        Parameters:
        obj - the reference object with which to compare.
        Returns:
        true if this object is the same as the obj argument; false otherwise.
        See Also:
        Object.hashCode(), HashMap
      • close

        public void close()
        Close the network and deallocate all native memory, including: parameters, gradients, updater memory and workspaces Note that the network should not be used again for any purpose after it has been closed
        Specified by:
        close in interface Model