UNPKG

@tensorflow/tfjs-layers

Version:

TensorFlow layers API in JavaScript

240 lines (239 loc) 9.52 kB
/** * @license * Copyright 2018 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ============================================================================= */ /// <amd-module name="@tensorflow/tfjs-layers/dist/engine/container" /> import { NamedTensorMap, Scalar, serialization, Tensor } from '@tensorflow/tfjs-core'; import { Shape } from '../keras_format/common'; import { PyJsonDict } from '../keras_format/types'; import { Kwargs } from '../types'; import { LayerVariable } from '../variables'; import { DisposeResult, Layer, Node, SymbolicTensor } from './topology'; /** Constructor config for Container. */ export interface ContainerArgs { inputs: SymbolicTensor | SymbolicTensor[]; outputs: SymbolicTensor | SymbolicTensor[]; name?: string; } /** * A Container is a directed acyclic graph of layers. * * It is the topological form of a "model". A LayersModel * is simply a Container with added training routines. * */ export declare abstract class Container extends Layer { inputs: SymbolicTensor[]; outputs: SymbolicTensor[]; inputLayers: Layer[]; inputLayersNodeIndices: number[]; inputLayersTensorIndices: number[]; outputLayers: Layer[]; outputLayersNodeIndices: number[]; outputLayersTensorIndices: number[]; layers: Layer[]; layersByDepth: { [depth: string]: Layer[]; }; nodesByDepth: { [depth: string]: Node[]; }; internalContainerRefs: Container[]; containerNodes: Set<string>; inputNames: string[]; outputNames: string[]; feedInputShapes: Shape[]; protected internalInputShapes: Shape[]; protected internalOutputShapes: Shape[]; protected feedInputNames: string[]; protected feedOutputNames: string[]; constructor(args: ContainerArgs); protected assertNotDisposed(): void; /** * Attempt to dispose a LayersModel's weights. * * This method decrease the reference count of the LayersModel object by 1. * * A LayersModel is reference-counted. Its reference count is incremented by 1 * when it is first constructed and when it is used as a Layer of another * LayersModel. * * If the reference count of a LayersModel becomes 0, the `dispose` method of * all its constituent `Layer`s will be called. * * Note: If the reference count is greater than 0 after the decrement, the * `dispose` method of its constituent `Layer`s will *not* be called. * * After a LayersModel is disposed, it cannot be used in calls such as * 'predict`, `evaluate` or `fit` anymore. * * @returns A DisposeResult Object with the following fields: * - refCountAfterDispose: The reference count of the LayersModel after this * `dispose()` call. * - numDisposedVariables: Number of `tf.Variable`s (i.e., weights) disposed * during this `dispose()` call. * @throws {Error} If the layer is not built yet, or if the LayersModel has * already been disposed. */ dispose(): DisposeResult; get trainable(): boolean; set trainable(trainable: boolean); get trainableWeights(): LayerVariable[]; get nonTrainableWeights(): LayerVariable[]; get weights(): LayerVariable[]; /** * Loads all layer weights from a JSON object. * * Porting Note: HDF5 weight files cannot be directly loaded in JavaScript / * TypeScript. The utility script at `scripts/pykeras.py` offers means * to convert them into JSON strings compatible with this method. * Porting Note: TensorFlow.js Layers supports only loading by name currently. * * @param weights A JSON mapping weight names to weight values as nested * arrays of numbers, or a `NamedTensorMap`, i.e., a JSON mapping weight * names to `tf.Tensor` objects. * @param strict Require that the provided weights exactly match those * required by the container. Default: `true`. Passing `false` means that * extra weights and missing weights will be silently ignored. */ loadWeights(weights: NamedTensorMap, strict?: boolean): void; protected parseWeights(weights: NamedTensorMap): void; /** * Util shared between different serialization methods. * @returns LayersModel config with Keras version information added. */ protected updatedConfig(): serialization.ConfigDict; /** * Returns a JSON string containing the network configuration. * * To load a network from a JSON save file, use * models.modelFromJSON(jsonString); * @param extraJsonArgs Unused in tfjs-layers, maintained for PyKeras * @param returnString Whether the return value should be stringified * (default: `true`). * @returns a JSON string if `returnString` (default), or a JSON object if * `!returnString`. */ toJSON(unused?: any, returnString?: boolean): string | PyJsonDict; /** * Call the model on new inputs. * * In this case `call` just reapplies all ops in the graph to the new inputs * (e.g. build a new computational graph from the provided inputs). * * @param inputs A tensor or list of tensors. * @param mask A mask or list of masks. A mask can be either a tensor or null * (no mask). * * @return A tensor if there is a single output, or a list of tensors if there * are more than one outputs. */ call(inputs: Tensor | Tensor[], kwargs: Kwargs): Tensor | Tensor[]; /** * Computes an output mask tensor. * * @param inputs Tensor or list of tensors. * @param mask Tensor or list of tensors. * * @return null or a tensor (or list of tensors, one per output tensor of the * layer). */ computeMask(inputs: Tensor | Tensor[], mask?: Tensor | Tensor[]): Tensor | Tensor[]; /** * Computes the output shape of the layer. * * Assumes that the layer will be built to match that input shape provided. * * @param inputShape A shape (tuple of integers) or a list of shape tuples * (one per output tensor of the layer). Shape tuples can include null for * free dimensions, instead of an integer. */ computeOutputShape(inputShape: Shape | Shape[]): Shape | Shape[]; /** * Computes output tensors for new inputs. * * Note: * - Expects `inputs` to be a list (potentially with 1 element). * * @param inputs List of tensors * @param masks List of masks (tensors or null). * @return Three lists: outputTensors, outputMasks, outputShapes */ protected runInternalGraph(inputs: Tensor[], masks?: Tensor[]): [ Tensor[], Tensor[], Shape[] ]; /** * Builds a map of internal node keys to node ordering. * Used in serializaion a node orderings may change as unused nodes are * dropped. Porting Note: This helper method was pulled out of getConfig to * improve readability. * @param layers An array of Layers in the model. * @returns Map of Node Keys to index order within the layer. */ private buildNodeConversionMap; /** * Retrieves a layer based on either its name (unique) or index. * * Indices are based on order of horizontal graph traversal (bottom-up). * * If both `name` and `index` are specified, `index` takes precedence. * * @param name Name of layer. * @param index Index of layer. * @returns A Layer instance. * @throws ValueError: In case of invalid layer name or index. * * @doc { * heading: 'Layers', * subheading: 'Classes', * namespace: 'layers', * subclasses: ['LayersModel'] * } */ getLayer(name: string): Layer; getLayer(index: number): Layer; getLayer(name: string, index: number): Layer; findLayer(index: number): Layer; /** * Retrieves the Container's current loss values. * * Used for regularizers during training. */ calculateLosses(): Scalar[]; getConfig(): serialization.ConfigDict; /** * Instantiates a LayersModel from its config (output of `get_config()`). * @param cls the class to create * @param config LayersModel config dictionary. * @param customObjects An optional dictionary of custom objects. * @param fastWeightInit Optional flag to use fast weight initialization * during deserialization. This is applicable to cases in which * the initialization will be immediately overwritten by loaded weight * values. Default: `false`. * @returns A LayersModel instance. * @throws ValueError: In case of improperly formatted config dict. */ /** @nocollapse */ static fromConfig<T extends serialization.Serializable>(cls: serialization.SerializableConstructor<T>, config: serialization.ConfigDict, customObjects?: serialization.ConfigDict, fastWeightInit?: boolean): T; /** * Determine whether the container is stateful. * * Porting Note: this is the equivalent of the stateful @property of * the Container class in PyKeras. */ get stateful(): boolean; /** * Reset the state of all stateful constituent layers (if any). * * Examples of stateful layers include RNN layers whose `stateful` property * is set as `true`. */ resetStates(): void; }