///
export declare const Abs = "Abs";
export declare const abs: typeof abs_;
/**
* Computes absolute value element-wise: `abs(x)`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.abs().print(); // or tf.abs(x)
* ```
* @param x The input `tf.Tensor`.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function abs_(x: T | TensorLike): T;
export declare type AbsInputs = UnaryInputs;
export declare const Acos = "Acos";
export declare const acos: typeof acos_;
/**
* Computes acos of the input `tf.Tensor` element-wise: `acos(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.acos().print(); // or tf.acos(x)
* ```
* @param x The input tensor.
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function acos_(x: T | TensorLike): T;
export declare const Acosh = "Acosh";
export declare const acosh: typeof acosh_;
/**
* Computes the inverse hyperbolic cos of the input `tf.Tensor` element-wise:
* `acosh(x)`
*
* ```js
* const x = tf.tensor1d([10, 1, 3, 5.7]);
*
* x.acosh().print(); // or tf.acosh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function acosh_(x: T | TensorLike): T;
export declare type AcoshInputs = UnaryInputs;
export declare type AcosInputs = UnaryInputs;
declare type Activation = 'linear' | 'relu' | 'prelu' | 'elu' | 'relu6' | 'leakyrelu' | 'sigmoid';
/** @doclink Optimizer */
export declare class AdadeltaOptimizer extends Optimizer {
protected learningRate: number;
protected rho: number;
protected epsilon: number;
/** @nocollapse */
static get className(): string;
private accumulatedGrads;
private accumulatedUpdates;
constructor(learningRate: number, rho: number, epsilon?: number);
applyGradients(variableGradients: NamedVariableMap | NamedTensor[]): void;
dispose(): void;
getWeights(): Promise;
setWeights(weightValues: NamedTensor[]): Promise;
getConfig(): ConfigDict;
/** @nocollapse */
static fromConfig(cls: SerializableConstructor, config: ConfigDict): T;
}
/** @doclink Optimizer */
export declare class AdagradOptimizer extends Optimizer {
protected learningRate: number;
private initialAccumulatorValue;
/** @nocollapse */
static get className(): string;
private accumulatedGrads;
constructor(learningRate: number, initialAccumulatorValue?: number);
applyGradients(variableGradients: NamedVariableMap | NamedTensor[]): void;
dispose(): void;
getWeights(): Promise;
setWeights(weightValues: NamedTensor[]): Promise;
getConfig(): ConfigDict;
/** @nocollapse */
static fromConfig(cls: SerializableConstructor, config: ConfigDict): T;
}
export declare class AdamaxOptimizer extends Optimizer {
protected learningRate: number;
protected beta1: number;
protected beta2: number;
protected epsilon: number;
protected decay: number;
/** @nocollapse */
static get className(): string;
private accBeta1;
private iteration;
private accumulatedFirstMoment;
private accumulatedWeightedInfNorm;
constructor(learningRate: number, beta1: number, beta2: number, epsilon?: number, decay?: number);
applyGradients(variableGradients: NamedVariableMap | NamedTensor[]): void;
dispose(): void;
getWeights(): Promise;
setWeights(weightValues: NamedTensor[]): Promise;
getConfig(): ConfigDict;
/** @nocollapse */
static fromConfig(cls: SerializableConstructor, config: ConfigDict): T;
}
export declare class AdamOptimizer extends Optimizer {
protected learningRate: number;
protected beta1: number;
protected beta2: number;
protected epsilon: number;
/** @nocollapse */
static get className(): string;
private accBeta1;
private accBeta2;
private accumulatedFirstMoment;
private accumulatedSecondMoment;
constructor(learningRate: number, beta1: number, beta2: number, epsilon?: number);
applyGradients(variableGradients: NamedVariableMap | NamedTensor[]): void;
dispose(): void;
getWeights(): Promise;
setWeights(weightValues: NamedTensor[]): Promise;
getConfig(): ConfigDict;
/** @nocollapse */
static fromConfig(cls: SerializableConstructor, config: ConfigDict): T;
}
export declare const Add = "Add";
export declare const add: typeof add_;
/**
* Adds two `tf.Tensor`s element-wise, A + B. Supports broadcasting.
*
*
* ```js
* const a = tf.tensor1d([1, 2, 3, 4]);
* const b = tf.tensor1d([10, 20, 30, 40]);
*
* a.add(b).print(); // or tf.add(a, b)
* ```
*
* ```js
* // Broadcast add a with b.
* const a = tf.scalar(5);
* const b = tf.tensor1d([10, 20, 30, 40]);
*
* a.add(b).print(); // or tf.add(a, b)
* ```
* @param a The first `tf.Tensor` to add.
* @param b The second `tf.Tensor` to add. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
declare function add_(a: Tensor | TensorLike, b: Tensor | TensorLike): T;
export declare type AddInputs = BinaryInputs;
export declare const AddN = "AddN";
export declare const addN: typeof addN_;
/**
* Adds a list of `tf.Tensor`s element-wise, each with the same shape and dtype.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
*
* tf.addN([a, b, c]).print();
* ```
* @param tensors A list of tensors with the same shape and dtype.
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
declare function addN_(tensors: Array): T;
export declare type AddNInputs = TensorInfo[];
export declare const All = "All";
export declare const all: typeof all_;
/**
* Computes the logical and of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and a
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 1, 1], 'bool');
*
* x.all().print(); // or tf.all(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');
*
* const axis = 1;
* x.all(axis).print(); // or tf.all(x, axis)
* ```
*
* @param x The input tensor. Must be of dtype bool.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
declare function all_(x: Tensor | TensorLike, axis?: number | number[], keepDims?: boolean): T;
export declare interface AllAttrs {
axis: number | number[];
keepDims: boolean;
}
export declare type AllInputs = Pick;
export declare const Any = "Any";
export declare const any: typeof any_;
/**
* Computes the logical or of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and a
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 1, 1], 'bool');
*
* x.any().print(); // or tf.any(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');
*
* const axis = 1;
* x.any(axis).print(); // or tf.any(x, axis)
* ```
*
* @param x The input tensor. Must be of dtype bool.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
declare function any_(x: Tensor | TensorLike, axis?: number | number[], keepDims?: boolean): T;
export declare interface AnyAttrs {
axis: number | number[];
keepDims: boolean;
}
export declare type AnyInputs = Pick;
declare function applyActivation(x: Tensor, activation: Activation, preluActivationWeights?: Tensor, leakyreluAlpha?: number): Tensor;
export declare const ArgMax = "ArgMax";
export declare const argMax: typeof argMax_;
/**
* Returns the indices of the maximum values along an `axis`.
*
* The result has the same shape as `input` with the dimension along `axis`
* removed.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.argMax().print(); // or tf.argMax(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);
*
* const axis = 1;
* x.argMax(axis).print(); // or tf.argMax(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
declare function argMax_(x: Tensor | TensorLike, axis?: number): T;
export declare interface ArgMaxAttrs {
axis: number;
}
export declare type ArgMaxInputs = Pick;
export declare const ArgMin = "ArgMin";
export declare const argMin: typeof argMin_;
/**
* Returns the indices of the minimum values along an `axis`.
*
* The result has the same shape as `input` with the dimension along `axis`
* removed.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.argMin().print(); // or tf.argMin(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);
*
* const axis = 1;
* x.argMin(axis).print(); // or tf.argMin(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
declare function argMin_(x: Tensor | TensorLike, axis?: number): T;
export declare interface ArgMinAttrs {
axis: number;
}
export declare type ArgMinInputs = Pick;
/** @docalias number[] */
declare interface ArrayMap {
R0: number;
R1: number[];
R2: number[][];
R3: number[][][];
R4: number[][][][];
R5: number[][][][][];
R6: number[][][][][][];
}
declare function arraysEqual(n1: FlatVector, n2: FlatVector): boolean;
declare function arraysEqualWithNull(n1: number[], n2: number[]): boolean;
export declare const Asin = "Asin";
export declare const asin: typeof asin_;
/**
* Computes asin of the input `tf.Tensor` element-wise: `asin(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.asin().print(); // or tf.asin(x)
* ```
* @param x The input tensor.
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function asin_(x: T | TensorLike): T;
export declare const Asinh = "Asinh";
export declare const asinh: typeof asinh_;
/**
* Computes inverse hyperbolic sin of the input `tf.Tensor` element-wise:
* `asinh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.asinh().print(); // or tf.asinh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function asinh_(x: T | TensorLike): T;
export declare type AsinhInputs = UnaryInputs;
export declare type AsinInputs = UnaryInputs;
/**
* Asserts that the expression is true. Otherwise throws an error with the
* provided message.
*
* ```js
* const x = 2;
* tf.util.assert(x === 2, 'x is not 2');
* ```
*
* @param expr The expression to assert (as a boolean).
* @param msg A function that returns the message to report when throwing an
* error. We use a function for performance reasons.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
declare function assert(expr: boolean, msg: () => string): void;
declare function assertAndGetBroadcastShape(shapeA: number[], shapeB: number[]): number[];
declare function assertAxesAreInnerMostDims(msg: string, axes: number[], rank: number): void;
declare function assertNonNegativeIntegerDimensions(shape: number[]): void;
declare function assertNonNull(a: TensorLike): void;
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
declare function assertParamsConsistent(shapes: number[][], axis: number): void;
declare function assertParamsValid(input: TensorInfo, begin: number[], size: number[]): void;
declare function assertShapesMatch(shapeA: number[], shapeB: number[], errorMessagePrefix?: string): void;
declare function assertTypesMatch(a: Tensor, b: Tensor): void;
/**
* Insert a given complex value into the TypedArray.
* @param data The array in which the complex value is inserted.
* @param c The complex value to be inserted.
* @param index An index of the target complex value.
*/
declare function assignToTypedArray(data: TypedArray, real: number, imag: number, index: number): void;
export declare const Atan = "Atan";
export declare const atan: typeof atan_;
export declare const Atan2 = "Atan2";
export declare const atan2: typeof atan2_;
/**
* Computes arctangent of `tf.Tensor`s a / b element-wise: `atan2(a, b)`.
* Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1.0, 1.0, -1.0, .7]);
* const b = tf.tensor1d([2.0, 13.0, 3.5, .21]);
*
* tf.atan2(a, b).print()
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function atan2_(a: Tensor | TensorLike, b: Tensor | TensorLike): T;
export declare type Atan2Inputs = BinaryInputs;
/**
* Computes atan of the input `tf.Tensor` element-wise: `atan(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.atan().print(); // or tf.atan(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function atan_(x: T | TensorLike): T;
export declare const Atanh = "Atanh";
export declare const atanh: typeof atanh_;
/**
* Computes inverse hyperbolic tan of the input `tf.Tensor` element-wise:
* `atanh(x)`
*
* ```js
* const x = tf.tensor1d([0, .1, -.1, .7]);
*
* x.atanh().print(); // or tf.atanh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function atanh_(x: T | TensorLike): T;
export declare type AtanhInputs = UnaryInputs;
export declare type AtanInputs = UnaryInputs;
/** These are extra non-tensor/primitive params passed to kernel functions. */
export declare type Attribute = AttributeValue | RecursiveArray;
declare type AttributeValue = number | number[] | boolean | boolean[] | string | string[] | NamedAttrMap;
export declare const AvgPool = "AvgPool";
export declare const avgPool: typeof avgPool_;
export declare const AvgPool3D = "AvgPool3D";
export declare const avgPool3d: typeof avgPool3d_;
/**
* Computes the 3D average pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.avgPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
declare function avgPool3d_(x: T | TensorLike, filterSize: [number, number, number] | number, strides: [number, number, number] | number, pad: 'valid' | 'same' | number, dimRoundingMode?: 'floor' | 'round' | 'ceil', dataFormat?: 'NDHWC' | 'NCDHW'): T;
export declare interface AvgPool3DAttrs {
filterSize: [number, number, number] | number;
strides: [number, number, number] | number;
pad: 'valid' | 'same' | number;
dimRoundingMode?: 'floor' | 'round' | 'ceil';
dataFormat: 'NDHWC' | 'NCDHW';
}
export declare const AvgPool3DGrad = "AvgPool3DGrad";
export declare interface AvgPool3DGradAttrs {
filterSize: [number, number, number] | number;
strides: [number, number, number] | number;
pad: 'valid' | 'same' | number;
dimRoundingMode?: 'floor' | 'round' | 'ceil';
}
export declare type AvgPool3DGradInputs = Pick;
export declare type AvgPool3DInputs = Pick;
/**
* Computes the 2D average pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
declare function avgPool_(x: T | TensorLike, filterSize: [number, number] | number, strides: [number, number] | number, pad: 'valid' | 'same' | number | conv_util.ExplicitPadding, dimRoundingMode?: 'floor' | 'round' | 'ceil'): T;
export declare interface AvgPoolAttrs {
filterSize: [number, number] | number;
strides: [number, number] | number;
pad: 'valid' | 'same' | number | ExplicitPadding;
dimRoundingMode?: 'floor' | 'round' | 'ceil';
}
export declare const AvgPoolGrad = "AvgPoolGrad";
export declare interface AvgPoolGradAttrs {
filterSize: [number, number] | number;
strides: [number, number] | number;
pad: 'valid' | 'same' | number | ExplicitPadding;
}
export declare type AvgPoolGradInputs = Pick;
export declare type AvgPoolInputs = Pick;
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Returns true if the axis specifies the inner most dimensions of the
* array.
*/
declare function axesAreInnerMostDims(axes: number[], rank: number): boolean;
declare interface Backend {
}
/**
* Gets the current backend. If no backends have been initialized, this will
* attempt to initialize the best backend. Will throw an error if the highest
* priority backend has async initialization, in which case you should call
* 'await tf.ready()' before running other code.
*
* @doc {heading: 'Backends'}
*/
export declare function backend(): KernelBackend;
declare namespace backend_util {
export {
fromUint8ToStringArray,
fromStringArrayToUint8,
slice_util,
BackendValues,
TypedArray,
upcastType,
PixelData,
MemoryInfo,
TimingInfo,
segment_util,
axesAreInnerMostDims,
combineLocations,
computeOutAndReduceShapes,
expandShapeToKeepDim,
assertAxesAreInnerMostDims,
getAxesPermutation,
getUndoAxesPermutation,
getInnerMostAxes,
getBroadcastDims,
getReductionAxes,
assertAndGetBroadcastShape,
assertParamsConsistent,
computeOutShape_3 as computeOutShape,
computeDilation2DInfo,
computePool2DInfo,
computePool3DInfo,
computeConv2DInfo,
computeConv3DInfo,
computeDefaultPad,
tupleValuesAreOne,
eitherStridesOrDilationsAreOne,
stridesOrDilationsArePositive,
convertConv2DDataFormat,
checkPadOnDimRoundingMode,
ExplicitPadding,
PadInfo,
PadInfo3D,
Conv2DInfo,
Conv3DInfo,
getFusedDyActivation,
getFusedBiasGradient,
applyActivation,
shouldFuse,
FusedConv2DConfig,
FusedBatchMatMulConfig,
Activation,
combineRaggedTensorToTensorShapes,
getRowPartitionTypesHelper,
getRaggedRank,
validateDefaultValueShape,
RowPartitionType,
computeOptimalWindowSize,
PARALLELIZE_THRESHOLD,
ReduceInfo,
getImageCenter,
getReshaped,
getPermuted,
getReshapedPermuted,
getSliceBeginCoords,
getSliceSize,
prepareAndValidate,
validateUpdateShape,
validateInput,
calculateShapes,
ScatterShapeInfo,
SELU_SCALEALPHA,
SELU_SCALE,
ERF_P,
ERF_A1,
ERF_A2,
ERF_A3,
ERF_A4,
ERF_A5,
warn,
log_2 as log,
mergeRealAndImagArrays,
splitRealAndImagArrays,
complexWithEvenIndex,
complexWithOddIndex,
getComplexWithIndex,
assignToTypedArray,
exponents,
exponent,
decodeEinsumEquation,
getEinsumPermutation,
checkEinsumDimSizes,
getEinsumComputePath,
isIdentityPermutation,
prepareSplitSize,
getSparseFillEmptyRowsIndicesDenseShapeMismatch,
getSparseFillEmptyRowsNegativeIndexErrorMessage,
getSparseFillEmptyRowsOutOfRangeIndexErrorMessage,
getSparseReshapeMultipleNegativeOneOutputDimErrorMessage,
getSparseReshapeNegativeOutputDimErrorMessage,
getSparseReshapeEmptyTensorZeroOutputDimErrorMessage,
getSparseReshapeInputOutputMultipleErrorMessage,
getSparseReshapeInputOutputMismatchErrorMessage,
getSparseSegmentReductionNegativeSegmentIdsErrorMessage,
getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage,
getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage,
getSparseSegmentReductionIndicesOutOfRangeErrorMessage
}
}
export { backend_util }
declare interface BackendTimer {
timerAvailable(): boolean;
time(f: () => void): Promise;
}
export declare interface BackendTimingInfo {
kernelMs: number | {
error: string;
};
getExtraProfileInfo?(): string;
}
/** The underlying tensor data that gets stored in a backend. */
export declare type BackendValues = Float32Array | Int32Array | Uint8Array | Uint8Array[];
export declare const basicLSTMCell: typeof basicLSTMCell_;
/**
* Computes the next state and output of a BasicLSTMCell.
*
* Returns `[newC, newH]`.
*
* Derived from tf.contrib.rnn.BasicLSTMCell.
*
* @param forgetBias Forget bias for the cell.
* @param lstmKernel The weights for the cell.
* @param lstmBias The bias for the cell.
* @param data The input to the cell.
* @param c Previous cell state.
* @param h Previous cell output.
*
* @doc {heading: 'Operations', subheading: 'RNN'}
*/
declare function basicLSTMCell_(forgetBias: Scalar | TensorLike, lstmKernel: Tensor2D | TensorLike, lstmBias: Tensor1D | TensorLike, data: Tensor2D | TensorLike, c: Tensor2D | TensorLike, h: Tensor2D | TensorLike): [Tensor2D, Tensor2D];
export declare const BatchMatMul = "BatchMatMul";
export declare interface BatchMatMulAttrs {
transposeA: boolean;
transposeB: boolean;
}
export declare type BatchMatMulInputs = Pick;
export declare const batchNorm: typeof batchNorm_;
export declare const batchNorm2d: typeof batchNorm2d_;
/**
* Batch normalization, strictly for 2D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
declare function batchNorm2d_(x: Tensor2D | TensorLike, mean: Tensor2D | Tensor1D | TensorLike, variance: Tensor2D | Tensor1D | TensorLike, offset?: Tensor2D | Tensor1D | TensorLike, scale?: Tensor2D | Tensor1D | TensorLike, varianceEpsilon?: number): Tensor2D;
export declare const batchNorm3d: typeof batchNorm3d_;
/**
* Batch normalization, strictly for 3D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
declare function batchNorm3d_(x: Tensor3D | TensorLike, mean: Tensor3D | Tensor1D | TensorLike, variance: Tensor3D | Tensor1D | TensorLike, offset?: Tensor3D | Tensor1D | TensorLike, scale?: Tensor3D | Tensor1D | TensorLike, varianceEpsilon?: number): Tensor3D;
export declare const batchNorm4d: typeof batchNorm4d_;
/**
* Batch normalization, strictly for 4D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
declare function batchNorm4d_(x: Tensor4D | TensorLike, mean: Tensor4D | Tensor1D | TensorLike, variance: Tensor4D | Tensor1D | TensorLike, offset?: Tensor4D | Tensor1D | TensorLike, scale?: Tensor4D | Tensor1D | TensorLike, varianceEpsilon?: number): Tensor4D;
/**
* Batch normalization.
*
* As described in
* [http://arxiv.org/abs/1502.03167](http://arxiv.org/abs/1502.03167).
*
* Mean, variance, scale, and offset can be of two shapes:
* - The same shape as the input.
* - In the common case, the depth dimension is the last dimension of x, so
* the values would be a `tf.Tensor1D` of shape [depth].
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that parameters passed are of given rank
* - `tf.batchNorm2d`
* - `tf.batchNorm3d`
* - `tf.batchNorm4d`
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
declare function batchNorm_(x: Tensor | TensorLike, mean: Tensor | Tensor1D | TensorLike, variance: Tensor | Tensor1D | TensorLike, offset?: Tensor | Tensor1D | TensorLike, scale?: Tensor | Tensor1D | TensorLike, varianceEpsilon?: number): Tensor;
export declare const BatchToSpaceND = "BatchToSpaceND";
export declare const batchToSpaceND: typeof batchToSpaceND_;
/**
* This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of
* shape `blockShape + [batch]`, interleaves these blocks back into the grid
* defined by the spatial dimensions `[1, ..., M]`, to obtain a result with
* the same rank as the input. The spatial dimensions of this intermediate
* result are then optionally cropped according to `crops` to produce the
* output. This is the reverse of `tf.spaceToBatchND`. See below for a precise
* description.
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [4, 1, 1, 1]);
* const blockShape = [2, 2];
* const crops = [[0, 0], [0, 0]];
*
* x.batchToSpaceND(blockShape, crops).print();
* ```
*
* @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +
* remainingShape`, where spatialShape has `M` dimensions.
* @param blockShape A 1-D array. Must have shape `[M]`, all values must
* be >= 1.
* @param crops A 2-D array. Must have shape `[M, 2]`, all values must be >= 0.
* `crops[i] = [cropStart, cropEnd]` specifies the amount to crop from input
* dimension `i + 1`, which corresponds to spatial dimension `i`. It is required
* that `cropStart[i] + cropEnd[i] <= blockShape[i] * inputShape[i + 1]`
*
* This operation is equivalent to the following steps:
*
* 1. Reshape `x` to `reshaped` of shape: `[blockShape[0], ...,
* blockShape[M-1], batch / prod(blockShape), x.shape[1], ...,
* x.shape[N-1]]`
*
* 2. Permute dimensions of `reshaped` to produce `permuted` of shape `[batch /
* prod(blockShape),x.shape[1], blockShape[0], ..., x.shape[M],
* blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`
*
* 3. Reshape `permuted` to produce `reshapedPermuted` of shape `[batch /
* prod(blockShape),x.shape[1] * blockShape[0], ..., x.shape[M] *
* blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`
*
* 4. Crop the start and end of dimensions `[1, ..., M]` of `reshapedPermuted`
* according to `crops` to produce the output of shape: `[batch /
* prod(blockShape),x.shape[1] * blockShape[0] - crops[0,0] - crops[0,1],
* ..., x.shape[M] * blockShape[M-1] - crops[M-1,0] -
* crops[M-1,1],x.shape[M+1], ..., x.shape[N-1]]`
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
declare function batchToSpaceND_(x: T | TensorLike, blockShape: number[], crops: number[][]): T;
export declare interface BatchToSpaceNDAttrs {
blockShape: number[];
crops: number[][];
}
export declare type BatchToSpaceNDInputs = Pick;
export declare type BinaryInputs = Pick;
export declare const Bincount = "Bincount";
export declare const bincount: typeof bincount_;
/**
* Outputs a vector with length `size` and the same dtype as `weights`.
*
* If `weights` are empty, then index `i` stores the number of times the value
* `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the
* sum of the value in `weights` at each index where the corresponding value in
* `x` is `i`.
*
* Values in `x` outside of the range [0, size) are ignored.
*
* @param x The input int tensor, rank 1.
* @param weights The weights tensor, must have the same shape as x, or a
* length-0 Tensor, in which case it acts as all weights equal to 1.
* @param size Non-negative integer.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
declare function bincount_(x: T | TensorLike, weights: T | TensorLike, size: number): T;
export declare interface BincountAttrs {
size: number;
}
export declare type BincountInputs = Pick;
export declare const BitwiseAnd = "BitwiseAnd";
export declare const bitwiseAnd: typeof bitwiseAnd_;
/**
* Bitwise `AND` operation for input tensors.
*
* Given two input tensors, returns a new tensor
* with the `AND` calculated values.
*
* The method supports int32 values
*
*
* ```js
* const x = tf.tensor1d([0, 5, 3, 14], 'int32');
* const y = tf.tensor1d([5, 0, 7, 11], 'int32');
* tf.bitwiseAnd(x, y).print();
* ```
*
* @param x The input tensor to be calculated.
* @param y The input tensor to be calculated.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
declare function bitwiseAnd_(x: Tensor, y: Tensor): Tensor;
export declare type BitwiseAndInputs = BinaryInputs;
export declare const booleanMaskAsync: typeof booleanMaskAsync_;
/**
* Apply boolean mask to tensor.
*
* ```js
* const tensor = tf.tensor2d([1, 2, 3, 4, 5, 6], [3, 2]);
* const mask = tf.tensor1d([1, 0, 1], 'bool');
* const result = await tf.booleanMaskAsync(tensor, mask);
* result.print();
* ```
*
* @param tensor N-D tensor.
* @param mask K-D boolean tensor, K <= N and K must be known statically.
* @param axis A 0-D int Tensor representing the axis in tensor to mask from.
* By default, axis is 0 which will mask from the first dimension.
* Otherwise K + axis <= N.
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
declare function booleanMaskAsync_(tensor: Tensor | TensorLike, mask: Tensor | TensorLike, axis?: number): Promise;
declare namespace broadcast_util {
export {
getBroadcastDims,
getReductionAxes,
assertAndGetBroadcastShape
}
}
export { broadcast_util }
export declare const BroadcastArgs = "BroadcastArgs";
export declare const broadcastArgs: typeof broadcastArgs_;
/**
* Return the shape of s0 op s1 with broadcast.
*
* compute r0, the broadcasted shape as a tensor.
* s0, s1 and r0 are all integer vectors.
*
* This function returns the shape of the result of an operation between
* two tensors of size s0 and s1 performed with broadcast.
*
* @param s0 A tensor representing a shape
* @param s1 A tensor representing a shape
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
declare function broadcastArgs_(s0: Tensor | TensorLike, s1: Tensor | TensorLike): Tensor;
export declare type BroadcastArgsInputs = Pick;
export declare const BroadcastTo = "BroadcastTo";
export declare const broadcastTo: typeof broadcastTo_;
/**
* Broadcast an array to a compatible shape NumPy-style.
*
* The tensor's shape is compared to the broadcast shape from end to beginning.
* Ones are prepended to the tensor's shape until it has the same length as
* the broadcast shape. If input.shape[i]==shape[i], the (i+1)-th axis is
* already broadcast-compatible. If input.shape[i]==1 and shape[i]==N, then
* the input tensor is tiled N times along that axis (using tf.tile).
*
* @param input The tensor that is to be broadcasted.
* @param shape The input is to be broadcast to this shape.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
declare function broadcastTo_(x: Tensor | TensorLike, shape: ShapeMap[R]): Tensor;
export declare interface BroadCastToAttrs {
shape: number[];
inputShape: number[];
}
export declare type BroadcastToInputs = Pick;
declare namespace browser {
export {
fromPixelsAsync,
toPixels,
draw,
fromPixels
}
}
export { browser }
/**
* Creates an IOHandler that loads model artifacts from user-selected files.
*
* This method can be used for loading from files such as user-selected files
* in the browser.
* When used in conjunction with `tf.loadLayersModel`, an instance of
* `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.
*
* ```js
* // Note: This code snippet won't run properly without the actual file input
* // elements in the HTML DOM.
*
* // Suppose there are two HTML file input (``)
* // elements.
* const uploadJSONInput = document.getElementById('upload-json');
* const uploadWeightsInput = document.getElementById('upload-weights');
* const model = await tf.loadLayersModel(tf.io.browserFiles(
* [uploadJSONInput.files[0], uploadWeightsInput.files[0]]));
* ```
*
* @param files `File`s to load from. Currently, this function supports only
* loading from files that contain Keras-style models (i.e., `tf.Model`s), for
* which an `Array` of `File`s is expected (in that order):
* - A JSON file containing the model topology and weight manifest.
* - Optionally, one or more binary files containing the binary weights.
* These files must have names that match the paths in the `weightsManifest`
* contained by the aforementioned JSON file, or errors will be thrown
* during loading. These weights files have the same format as the ones
* generated by `tensorflowjs_converter` that comes with the `tensorflowjs`
* Python PIP package. If no weights files are provided, only the model
* topology will be loaded from the JSON file above.
* @returns An instance of `Files` `IOHandler`.
*
* @doc {
* heading: 'Models',
* subheading: 'Loading',
* namespace: 'io',
* ignoreCI: true
* }
*/
declare function browserFiles(files: File[]): IOHandler;
/**
* Deprecated. Use `tf.io.http`.
* @param path
* @param loadOptions
*/
declare function browserHTTPRequest(path: string, loadOptions?: LoadOptions): IOHandler;
/**
* Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.
*
* The values are stored in CPU as `TypedArray`. Fill the buffer using
* `buffer.set()`, or by modifying directly `buffer.values`.
*
* When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with
* those values.
*
* ```js
* // Create a buffer and set values at particular indices.
* const buffer = tf.buffer([2, 2]);
* buffer.set(3, 0, 0);
* buffer.set(5, 1, 0);
*
* // Convert the buffer back to a tensor.
* buffer.toTensor().print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The dtype of the buffer. Defaults to 'float32'.
* @param values The values of the buffer as `TypedArray`. Defaults to
* zeros.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
export declare function buffer(shape: ShapeMap[R], dtype?: D, values?: DataTypeMap[D]): TensorBuffer;
/**
* Returns the approximate number of bytes allocated in the string array - 2
* bytes per character. Computing the exact bytes for a native string in JS
* is not possible since it depends on the encoding of the html page that
* serves the website.
*/
declare function bytesFromStringArray(arr: Uint8Array[]): number;
declare function bytesPerElement(dtype: DataType): number;
/**
* Calculate the shape information for the output.
*
* @param update The tensor contains the update values.
* @param indices The tensor contains the indices for the update values.
* @param shape The shape of the output tensor.
*
* @returns ScatterShapeInfo
*/
declare function calculateShapes(updates: TensorInfo, indices: TensorInfo, shape: number[]): ScatterShapeInfo;
export declare const Cast = "Cast";
export declare const cast: typeof cast_;
/**
* Casts a `tf.Tensor` to a new dtype.
*
* ```js
* const x = tf.tensor1d([1.5, 2.5, 3]);
* tf.cast(x, 'int32').print();
* ```
* @param x The input tensor to be casted.
* @param dtype The dtype to cast the input tensor to.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
declare function cast_(x: T | TensorLike, dtype: DataType): T;
export declare interface CastAttrs {
dtype: DataType;
}
export declare type CastInputs = UnaryInputs;
export declare const Ceil = "Ceil";
export declare const ceil: typeof ceil_;
/**
* Computes ceiling of input `tf.Tensor` element-wise: `ceil(x)`
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.ceil().print(); // or tf.ceil(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function ceil_(x: T | TensorLike): T;
export declare type CeilInputs = UnaryInputs;
declare function checkConversionForErrors(vals: DataTypeMap[D] | number[], dtype: D): void;
/**
* Checks that the dimension sizes from different input tensors match the
* equation.
*/
declare function checkEinsumDimSizes(nDims: number, idDims: number[][], tensors: Tensor[]): void;
/**
* Check validity of pad when using dimRoundingMode.
* @param opDesc A string of op description
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid` output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @throws unknown padding parameter
*/
declare function checkPadOnDimRoundingMode(opDesc: string, pad: 'valid' | 'same' | number | ExplicitPadding, dimRoundingMode?: 'floor' | 'round' | 'ceil'): void;
/** Clamps a value to a specified range. */
declare function clamp(min: number, x: number, max: number): number;
export declare const ClipByValue = "ClipByValue";
export declare const clipByValue: typeof clipByValue_;
/**
* Clips values element-wise. `max(min(x, clipValueMax), clipValueMin)`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.clipByValue(-2, 3).print(); // or tf.clipByValue(x, -2, 3)
* ```
* @param x The input tensor.
* @param clipValueMin Lower bound of range to be clipped to.
* @param clipValueMax Upper bound of range to be clipped to.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function clipByValue_(x: T | TensorLike, clipValueMin: number, clipValueMax: number): T;
export declare interface ClipByValueAttrs {
clipValueMin: number;
clipValueMax: number;
}
export declare type ClipByValueInputs = UnaryInputs;
export declare const clone: typeof clone_;
/**
* Creates a new tensor with the same values and shape as the specified
* tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
*
* x.clone().print();
* ```
*
* @param x The tensor to clone.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
declare function clone_(x: T | TensorLike): T;
declare function collectGatherOpShapeInfo(x: TensorInfo, indices: TensorInfo, axis: number, batchDims: number): GatherOpShapeInfo;
declare function combineLocations(outputLoc: number[], reduceLoc: number[], axes: number[]): number[];
declare function combineRaggedTensorToTensorShapes(raggedRank: number, shape: number[], valueShape: number[]): number[];
export declare const Complex = "Complex";
export declare const complex: typeof complex_;
/**
* Converts two real numbers to a complex number.
*
* Given a tensor `real` representing the real part of a complex number, and a
* tensor `imag` representing the imaginary part of a complex number, this
* operation returns complex numbers elementwise of the form [r0, i0, r1, i1],
* where r represents the real part and i represents the imag part.
*
* The input tensors real and imag must have the same shape.
*
* ```js
* const real = tf.tensor1d([2.25, 3.25]);
* const imag = tf.tensor1d([4.75, 5.75]);
* const complex = tf.complex(real, imag);
*
* complex.print();
* ```
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
declare function complex_(real: T | TensorLike, imag: T | TensorLike): T;
export declare const ComplexAbs = "ComplexAbs";
export declare type ComplexAbsInputs = UnaryInputs;
export declare type ComplexInputs = Pick;
/**
* Extracts even indexed complex values in the given array.
* @param complex The complex tensor values
*/
declare function complexWithEvenIndex(complex: Float32Array): {
real: Float32Array;
imag: Float32Array;
};
/**
* Extracts odd indexed comple values in the given array.
* @param complex The complex tensor values
*/
declare function complexWithOddIndex(complex: Float32Array): {
real: Float32Array;
imag: Float32Array;
};
/**
* Wraps a list of ArrayBuffers into a `slice()`-able object without allocating
* a large ArrayBuffer.
*
* Allocating large ArrayBuffers (~2GB) can be unstable on Chrome. TFJS loads
* its weights as a list of (usually) 4MB ArrayBuffers and then slices the
* weight tensors out of them. For small models, it's safe to concatenate all
* the weight buffers into a single ArrayBuffer and then slice the weight
* tensors out of it, but for large models, a different approach is needed.
*/
declare class CompositeArrayBuffer {
private shards;
private previousShardIndex;
private bufferUniformSize?;
readonly byteLength: number;
/**
* Concatenate a number of ArrayBuffers into one.
*
* @param buffers An array of ArrayBuffers to concatenate, or a single
* ArrayBuffer.
* @returns Result of concatenating `buffers` in order.
*/
static join(buffers?: ArrayBuffer[] | ArrayBuffer): ArrayBuffer;
constructor(buffers?: ArrayBuffer | ArrayBuffer[] | TypedArray | TypedArray[]);
slice(start?: number, end?: number): ArrayBuffer;
/**
* Get the index of the shard that contains the byte at `byteIndex`.
*/
private findShardForByte;
}
/**
* Computes the information for a forward pass of a convolution/pooling
* operation.
*/
declare function computeConv2DInfo(inShape: [number, number, number, number], filterShape: [number, number, number, number], strides: number | [number, number], dilations: number | [number, number], pad: 'same' | 'valid' | number | ExplicitPadding, roundingMode?: 'floor' | 'round' | 'ceil', depthwise?: boolean, dataFormat?: 'channelsFirst' | 'channelsLast'): Conv2DInfo;
/**
* Computes the information for a forward pass of a 3D convolution/pooling
* operation.
*/
declare function computeConv3DInfo(inShape: [number, number, number, number, number], filterShape: [number, number, number, number, number], strides: number | [number, number, number], dilations: number | [number, number, number], pad: 'same' | 'valid' | number, depthwise?: boolean, dataFormat?: 'channelsFirst' | 'channelsLast', roundingMode?: 'floor' | 'round' | 'ceil'): Conv3DInfo;
declare function computeDefaultPad(inputShape: [number, number] | [number, number, number, number], fieldSize: number, stride: number, dilation?: number): number;
/**
*
* @param inputShape Input tensor shape is of the following dimensions:
* `[batch, height, width, inChannels]`.
* @param filterShape The filter shape is of the following dimensions:
* `[filterHeight, filterWidth, depth]`.
* @param strides The strides of the sliding window for each dimension of the
* input tensor: `[strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat The data format of the input and output data.
* Defaults to 'NHWC'.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`.
* Defaults to `[1, 1]`. If `dilations` is a single number, then
* `dilationHeight == dilationWidth`.
*/
declare function computeDilation2DInfo(inputShape: [number, number, number, number], filterShape: [number, number, number], strides: number | [number, number], pad: 'same' | 'valid' | number, dataFormat: 'NHWC', dilations: number | [number, number]): Conv2DInfo;
declare function computeFlatOffset(begin: number[], strides: number[]): number;
declare function computeOptimalWindowSize(inSize: number): number;
declare function computeOutAndReduceShapes(aShape: number[], axes: number[]): [number[], number[]];
/** Computes the output shape given the strided slice params. */
declare function computeOutShape(begin: number[], end: number[], strides: number[]): number[];
declare function computeOutShape_2(aShape: number[], axis: number, numSegments: number): number[];
declare function computeOutShape_3(shapes: number[][], axis: number): number[];
declare function computePool2DInfo(inShape: [number, number, number, number], filterSize: [number, number] | number, strides: number | [number, number], dilations: number | [number, number], pad: 'same' | 'valid' | number | ExplicitPadding, roundingMode?: 'floor' | 'round' | 'ceil', dataFormat?: 'channelsFirst' | 'channelsLast'): Conv2DInfo;
/**
* Computes the information for a forward pass of a pooling3D operation.
*/
declare function computePool3DInfo(inShape: [number, number, number, number, number], filterSize: number | [number, number, number], strides: number | [number, number, number], dilations: number | [number, number, number], pad: 'same' | 'valid' | number, roundingMode?: 'floor' | 'round' | 'ceil', dataFormat?: 'NDHWC' | 'NCDHW'): Conv3DInfo;
declare function computeStrides(shape: number[]): number[];
export declare const Concat = "Concat";
export declare const concat: typeof concat_;
export declare const concat1d: typeof concat1d_;
/**
* Concatenates a list of`tf.Tensor1D`s along an axis. See `concat` for details.
*
* For example, if:
* A: shape(3) = |r1, g1, b1|
* B: shape(2) = |r2, g2|
* C = tf.concat1d([A, B]) == |r1, g1, b1, r2, g2|
*
* @param tensors A list of`tf.Tensor`s to concatenate.
* @return The concatenated array.
*/
declare function concat1d_(tensors: Array): Tensor1D;
export declare const concat2d: typeof concat2d_;
/**
* Concatenates a list of`tf.Tensor2D`s along an axis. See `concat` for details.
*
* For example, if:
* A: shape(2, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
*
* B: shape(2, 3) = | r3, g3, b3 |
* | r4, g4, b4 |
*
* C = tf.concat2d([A, B], axis)
*
* if axis = 0:
* C: shape(4, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
* | r3, g3, b3 |
* | r4, g4, b4 |
*
* if axis = 1:
* C = shape(2, 6) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
*
* @param tensors A list of `tf.Tensor`s to concatenate.
* @param axis The axis to concatenate along.
* @return The concatenated array.
*/
declare function concat2d_(tensors: Array, axis: number): Tensor2D;
export declare const concat3d: typeof concat3d_;
/**
* Concatenates a list of `tf.Tensor3D`s along an axis.
* See `concat` for details.
*
* For example, if:
* A: shape(2, 1, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
*
* B: shape(2, 1, 3) = | r3, g3, b3 |
* | r4, g4, b4 |
*
* C = tf.concat3d([A, B], axis)
*
* if axis = 0:
* C: shape(4, 1, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
* | r3, g3, b3 |
* | r4, g4, b4 |
*
* if axis = 1:
* C: shape(2, 2, 3) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
* if axis = 2:
* C = shape(2, 1, 6) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
* @param tensors A list of`tf.Tensor`s to concatenate.
* @param axis The axis to concate along.
* @return The concatenated array.
*/
declare function concat3d_(tensors: Array, axis: number): Tensor3D;
export declare const concat4d: typeof concat4d_;
/**
* Concatenates a list of `tf.Tensor4D`s along an axis.
* See `concat` for details.
*
* @param tensors A list of `tf.Tensor`s to concatenate.
* @param axis The axis to concate along.
* @return The concatenated array.
*/
declare function concat4d_(tensors: Array, axis: number): Tensor4D;
/**
* Concatenates a list of `tf.Tensor`s along a given axis.
*
* The tensors ranks and types must match, and their sizes must match in all
* dimensions except `axis`.
*
* Also available are stricter rank-specific methods that assert that
* `tensors` are of the given rank:
* - `tf.concat1d`
* - `tf.concat2d`
* - `tf.concat3d`
* - `tf.concat4d`
*
* Except `tf.concat1d` (which does not have axis param), all methods have
* same signature as this method.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* a.concat(b).print(); // or a.concat(b)
* ```
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
* tf.concat([a, b, c]).print();
* ```
*
* ```js
* const a = tf.tensor2d([[1, 2], [10, 20]]);
* const b = tf.tensor2d([[3, 4], [30, 40]]);
* const axis = 1;
* tf.concat([a, b], axis).print();
* ```
* @param tensors A list of tensors to concatenate.
* @param axis The axis to concatenate along. Defaults to 0 (the first dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
declare function concat_(tensors: Array, axis?: number): T;
export declare interface ConcatAttrs {
axis: number;
}
/**
* Concatenate a number of ArrayBuffers into one.
*
* @param buffers An array of ArrayBuffers to concatenate, or a single
* ArrayBuffer.
* @returns Result of concatenating `buffers` in order.
*
* @deprecated Use tf.io.CompositeArrayBuffer.join() instead.
*/
declare function concatenateArrayBuffers(buffers: ArrayBuffer[] | ArrayBuffer): ArrayBuffer;
export declare type ConcatInputs = TensorInfo[];
declare interface ConfigDict {
[key: string]: ConfigDictValue;
}
declare interface ConfigDictArray extends Array {
}
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Types to support JSON-esque data structures internally.
*
* Internally ConfigDict's use camelCase keys and values where the
* values are class names to be instantiated. On the python side, these
* will be snake_case. Internally we allow Enums into the values for better
* type safety, but these need to be converted to raw primitives (usually
* strings) for round-tripping with python.
*
* toConfig returns the TS-friendly representation. model.toJSON() returns
* the pythonic version as that's the portable format. If you need to
* python-ify a non-model level toConfig output, you'll need to use a
* convertTsToPythonic from serialization_utils in -Layers.
*
*/
declare type ConfigDictValue = boolean | number | string | null | ConfigDictArray | ConfigDict;
declare const confusionMatrix: typeof confusionMatrix_;
/**
* Computes the confusion matrix from true labels and predicted labels.
*
* ```js
* const labels = tf.tensor1d([0, 1, 2, 1, 0], 'int32');
* const predictions = tf.tensor1d([0, 2, 2, 1, 0], 'int32');
* const numClasses = 3;
* const out = tf.math.confusionMatrix(labels, predictions, numClasses);
* out.print();
* // Expected output matrix:
* // [[2, 0, 0],
* // [0, 1, 1],
* // [0, 0, 1]]
* ```
*
* @param labels The target labels, assumed to be 0-based integers
* for the classes. The shape is `[numExamples]`, where
* `numExamples` is the number of examples included.
* @param predictions The predicted classes, assumed to be
* 0-based integers for the classes. Must have the same shape as `labels`.
* @param numClasses Number of all classes, as an integer.
* Its value must be larger than the largest element in `labels` and
* `predictions`.
* @returns The confusion matrix as a int32-type 2D tensor. The value at
* row `r` and column `c` is the number of times examples of actual class
* `r` were predicted as class `c`.
*
* @doc {heading: 'Operations', subheading: 'Evaluation'}
*/
declare function confusionMatrix_(labels: Tensor1D | TensorLike, predictions: Tensor1D | TensorLike, numClasses: number): Tensor2D;
declare interface ContextOptions {
/**
* Optional. If the canvas has created a context, it would not make effects.
* If it is not set, it would be variable based on the current backend.
*/
contextType?: string;
/**
* Optional. A WebGLContextAttributes configuration. If the canvas has created
* a context, it would not make effects.
*/
contextAttributes?: WebGLContextAttributes;
}
export declare const conv1d: typeof conv1d_;
/**
* Computes a 1D convolution over the input x.
*
* @param x The input tensor, of rank 3 or rank 2, of shape
* `[batch, width, inChannels]`. If rank 2, batch of 1 is assumed.
* @param filter The filter, rank 3, of shape
* `[filterWidth, inDepth, outDepth]`.
* @param stride The number of entries by which the filter is moved right at
* each step.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat An optional string from "NWC", "NCW". Defaults to "NWC",
* the data is stored in the order of [batch, in_width, in_channels]. Only
* "NWC" is currently supported.
* @param dilation The dilation rate in which we sample input values in
* atrous convolution. Defaults to `1`. If it is greater than 1, then
* stride must be `1`.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
declare function conv1d_(x: T | TensorLike, filter: Tensor3D | TensorLike, stride: number, pad: 'valid' | 'same' | number | conv_util.ExplicitPadding, dataFormat?: 'NWC' | 'NCW', dilation?: number, dimRoundingMode?: 'floor' | 'round' | 'ceil'): T;
export declare const Conv2D = "Conv2D";
export declare const conv2d: typeof conv2d_;
/**
* Computes a 2D convolution over the input x.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
declare function conv2d_(x: T | TensorLike, filter: Tensor4D | TensorLike, strides: [number, number] | number, pad: 'valid' | 'same' | number | conv_util.ExplicitPadding, dataFormat?: 'NHWC' | 'NCHW', dilations?: [number, number] | number, dimRoundingMode?: 'floor' | 'round' | 'ceil'): T;
declare const conv2d_2: typeof fusedConv2d_;
export declare interface Conv2DAttrs {
strides: [number, number] | number;
pad: 'valid' | 'same' | number | ExplicitPadding;
dataFormat: 'NHWC' | 'NCHW';
dilations: [number, number] | number;
dimRoundingMode?: 'floor' | 'round' | 'ceil';
}
export declare const Conv2DBackpropFilter = "Conv2DBackpropFilter";
export declare interface Conv2DBackpropFilterAttrs {
strides: [number, number] | number;
pad: 'valid' | 'same' | number | ExplicitPadding;
dataFormat: 'NHWC' | 'NCHW';
dimRoundingMode?: 'floor' | 'round' | 'ceil';
filterShape: [number, number, number, number];
}
export declare type Conv2DBackpropFilterInputs = Pick;
export declare const Conv2DBackpropInput = "Conv2DBackpropInput";
export declare interface Conv2DBackpropInputAttrs {
strides: [number, number] | number;
pad: 'valid' | 'same' | number | ExplicitPadding;
dataFormat: 'NHWC' | 'NCHW';
dimRoundingMode?: 'floor' | 'round' | 'ceil';
inputShape: [number, number, number, number];
}
export declare type Conv2DBackpropInputInputs = Pick;
/**
* Information about the forward pass of a convolution/pooling operation.
* It includes input and output shape, strides, filter size and padding
* information.
*/
declare type Conv2DInfo = {
batchSize: number;
inHeight: number;
inWidth: number;
inChannels: number;
outHeight: number;
outWidth: number;
outChannels: number;
dataFormat: 'channelsFirst' | 'channelsLast';
strideHeight: number;
strideWidth: number;
dilationHeight: number;
dilationWidth: number;
filterHeight: number;
filterWidth: number;
effectiveFilterHeight: number;
effectiveFilterWidth: number;
padInfo: PadInfo;
inShape: [number, number, number, number];
outShape: [number, number, number, number];
filterShape: [number, number, number, number];
};
export declare type Conv2DInputs = Pick;
export declare const conv2dTranspose: typeof conv2dTranspose_;
/**
* Computes the transposed 2D convolution of an image, also known as a
* deconvolution.
*
* @param x The input image, of rank 4 or rank 3, of shape
* `[batch, height, width, inDepth]`. If rank 3, batch of 1 is assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, outDepth, inDepth]`.
* `inDepth` must match `inDepth` in `x`.
* @param outputShape Output shape, of rank 4 or rank 3:
* `[batch, height, width, outDepth]`. If rank 3, batch of 1 is assumed.
* @param strides The strides of the original convolution:
* `[strideHeight, strideWidth]`.
* @param pad The type of padding algorithm used in the non-transpose version
* of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
declare function conv2dTranspose_(x: T | TensorLike, filter: Tensor4D | TensorLike, outputShape: [number, number, number, number] | [number, number, number], strides: [number, number] | number, pad: 'valid' | 'same' | number | ExplicitPadding, dimRoundingMode?: 'floor' | 'round' | 'ceil'): T;
export declare const Conv3D = "Conv3D";
export declare const conv3d: typeof conv3d_;
/**
* Computes a 3D convolution over the input x.
*
* @param x The input tensor, of rank 5 or rank 4, of shape
* `[batch, depth, height, width, channels]`. If rank 4,
* batch of 1 is assumed.
* @param filter The filter, rank 5, of shape
* `[filterDepth, filterHeight, filterWidth, inChannels, outChannels]`.
* inChannels must match between input and filter.
* @param strides The strides of the convolution: `[strideDepth, strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat: An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param dilations The dilation rates: `[dilationDepth, dilationHeight,
* dilationWidth]` in which we sample input values across the height
* and width dimensions in atrous convolution. Defaults to `[1, 1, 1]`.
* If `dilations` is a single number, then
* `dilationDepth == dilationHeight == dilationWidth`. If it is greater
* than 1, then all values of `strides` must be 1.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
declare function conv3d_(x: T | TensorLike, filter: Tensor5D | TensorLike, strides: [number, number, number] | number, pad: 'valid' | 'same', dataFormat?: 'NDHWC' | 'NCDHW', dilations?: [number, number, number] | number): T;
export declare interface Conv3DAttrs {
strides: [number, number, number] | number;
pad: 'valid' | 'same';
dataFormat: 'NDHWC' | 'NCDHW';
dilations: [number, number, number] | number;
}
export declare const Conv3DBackpropFilterV2 = "Conv3DBackpropFilterV2";
export declare interface Conv3DBackpropFilterV2Attrs {
strides: [number, number, number] | number;
pad: 'valid' | 'same';
filterShape: [number, number, number, number, number];
}
export declare type Conv3DBackpropFilterV2Inputs = Pick;
export declare const Conv3DBackpropInputV2 = "Conv3DBackpropInputV2";
export declare interface Conv3DBackpropInputV2Attrs {
strides: [number, number, number] | number;
pad: 'valid' | 'same';
inputShape: [number, number, number, number, number];
}
export declare type Conv3DBackpropInputV2Inputs = Pick;
/**
* Information about the forward pass of a 3D convolution/pooling operation.
* It includes input and output shape, strides, filter size and padding
* information.
*/
declare type Conv3DInfo = {
batchSize: number;
inDepth: number;
inHeight: number;
inWidth: number;
inChannels: number;
outDepth: number;
outHeight: number;
outWidth: number;
outChannels: number;
dataFormat: 'channelsFirst' | 'channelsLast';
strideDepth: number;
strideHeight: number;
strideWidth: number;
dilationDepth: number;
dilationHeight: number;
dilationWidth: number;
filterDepth: number;
filterHeight: number;
filterWidth: number;
effectiveFilterDepth: number;
effectiveFilterHeight: number;
effectiveFilterWidth: number;
padInfo: PadInfo3D;
inShape: [number, number, number, number, number];
outShape: [number, number, number, number, number];
filterShape: [number, number, number, number, number];
};
export declare type Conv3DInputs = Pick;
export declare const conv3dTranspose: typeof conv3dTranspose_;
/**
* Computes the transposed 3D convolution of a volume, also known as a
* deconvolution.
*
* @param x The input image, of rank 5 or rank 4, of shape
* `[batch, depth, height, width, inDepth]`. If rank 4, batch of 1 is assumed.
* @param filter The filter, rank 4, of shape
* `[depth, filterHeight, filterWidth, outDepth, inDepth]`.
* `inDepth` must match `inDepth` in `x`.
* @param outputShape Output shape, of rank 5 or rank 4:
* `[batch, depth, height, width, outDepth]`. If rank 3, batch of 1 is
* assumed.
* @param strides The strides of the original convolution:
* `[strideDepth, strideHeight, strideWidth]`.
* @param pad The type of padding algorithm used in the non-transpose version
* of the op.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
declare function conv3dTranspose_(x: T | TensorLike, filter: Tensor5D | TensorLike, outputShape: [
number,
number,
number,
number,
number
] | [number, number, number, number], strides: [number, number, number] | number, pad: 'valid' | 'same'): T;
declare namespace conv_util {
export {
computeDilation2DInfo,
computePool2DInfo,
computePool3DInfo,
computeConv2DInfo,
computeConv3DInfo,
computeDefaultPad,
tupleValuesAreOne,
eitherStridesOrDilationsAreOne,
stridesOrDilationsArePositive,
convertConv2DDataFormat,
checkPadOnDimRoundingMode,
ExplicitPadding,
PadInfo,
PadInfo3D,
Conv2DInfo,
Conv3DInfo
}
}
declare function convertBackendValuesAndArrayBuffer(data: BackendValues | ArrayBuffer, dtype: DataType): Uint8Array | Int32Array | Float32Array | Uint8Array[];
/**
* Convert Conv2D dataFormat from 'NHWC'|'NCHW' to
* 'channelsLast'|'channelsFirst'
* @param dataFormat in 'NHWC'|'NCHW' mode
* @return dataFormat in 'channelsLast'|'channelsFirst' mode
* @throws unknown dataFormat
*/
declare function convertConv2DDataFormat(dataFormat: 'NHWC' | 'NCHW'): 'channelsLast' | 'channelsFirst';
/**
* Copy a model from one URL to another.
*
* This function supports:
*
* 1. Copying within a storage medium, e.g.,
* `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`
* 2. Copying between two storage mediums, e.g.,
* `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`
*
* ```js
* // First create and save a model.
* const model = tf.sequential();
* model.add(tf.layers.dense(
* {units: 1, inputShape: [10], activation: 'sigmoid'}));
* await model.save('localstorage://demo/management/model1');
*
* // Then list existing models.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Copy the model, from Local Storage to IndexedDB.
* await tf.io.copyModel(
* 'localstorage://demo/management/model1',
* 'indexeddb://demo/management/model1');
*
* // List models again.
* console.log(JSON.stringify(await tf.io.listModels()));
*
* // Remove both models.
* await tf.io.removeModel('localstorage://demo/management/model1');
* await tf.io.removeModel('indexeddb://demo/management/model1');
* ```
*
* @param sourceURL Source URL of copying.
* @param destURL Destination URL of copying.
* @returns ModelArtifactsInfo of the copied model (if and only if copying
* is successful).
* @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or
* if `oldPath` and `newPath` are identical.
*
* @doc {
* heading: 'Models',
* subheading: 'Management',
* namespace: 'io',
* ignoreCI: true
* }
*/
declare function copyModel(sourceURL: string, destURL: string): Promise;
/**
* Finds kernels that have already been registered to a backend and re-registers
* them for a new backend. Useful for registering custom backends.
* @param registeredBackendName Already registered backend.
* @param newBackendName New backend.
*/
export declare function copyRegisteredKernels(registeredBackendName: string, newBackendName: string): void;
export declare const Cos = "Cos";
export declare const cos: typeof cos_;
/**
* Computes cos of the input `tf.Tensor` element-wise: `cos(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.cos().print(); // or tf.cos(x)
* ```
* @param x The input tensor. Must be float32 type.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function cos_(x: T | TensorLike): T;
export declare const Cosh = "Cosh";
export declare const cosh: typeof cosh_;
/**
* Computes hyperbolic cos of the input `tf.Tensor` element-wise: `cosh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.cosh().print(); // or tf.cosh(x)
* ```
* @param x The input tensor. Must be float32 type.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function cosh_(x: T | TensorLike): T;
export declare type CoshInputs = UnaryInputs;
export declare function cosineWindow(windowLength: number, a: number, b: number): Tensor1D;
export declare type CosInputs = UnaryInputs;
/**
* Create typed array for scalar value. Used for storing in `DataStorage`.
*/
declare function createScalarValue(value: DataType, dtype: DataType): BackendValues;
/**
* Creates a new array with randomized indices to a given quantity.
*
* ```js
* const randomTen = tf.util.createShuffledIndices(10);
* console.log(randomTen);
* ```
*
* @param number Quantity of how many shuffled indices to create.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
declare function createShuffledIndices(n: number): Uint32Array;
/** Creates an HTMLVideoElement with autoplay-friendly default settings. */
declare function createVideoElement(source: HTMLSourceElement): Promise;
export declare const CropAndResize = "CropAndResize";
export declare interface CropAndResizeAttrs {
cropSize: [number, number];
method: 'bilinear' | 'nearest';
extrapolationValue: number;
}
export declare type CropAndResizeInputs = Pick;
export declare const Cumprod = "Cumprod";
export declare const cumprod: typeof cumprod_;
/**
* Computes the cumulative product of a `tf.Tensor` along `axis`.
*
* ```js
* const x = tf.tensor([1, 2, 3, 4]);
* x.cumprod().print();
* ```
* ```js
* const x = tf.tensor([[1, 2], [3, 4]]);
* x.cumprod().print();
* ```
*
* @param x The input tensor to cumulatively multiply.
* @param axis The axis along which to multiply. Optional. Defaults to 0.
* @param exclusive Whether to perform exclusive cumulative product. Optional.
* Defaults to false. If set to true then the product of each tensor entry
* does not include its own value, but only the values previous to it
* along the specified axis.
* @param reverse Whether to multiply in the opposite direction. Optional.
* Defaults to false.
*
* @doc {heading: 'Operations', subheading: 'Scan'}
*/
declare function cumprod_(x: Tensor | TensorLike, axis?: number, exclusive?: boolean, reverse?: boolean): T;
export declare interface CumprodAttrs {
axis: number;
exclusive: boolean;
reverse: boolean;
}
export declare type CumprodInputs = Pick;
export declare const Cumsum = "Cumsum";
export declare const cumsum: typeof cumsum_;
/**
* Computes the cumulative sum of a `tf.Tensor` along `axis`.
*
* ```js
* const x = tf.tensor([1, 2, 3, 4]);
* x.cumsum().print();
* ```
* ```js
* const x = tf.tensor([[1, 2], [3, 4]]);
* x.cumsum().print();
* ```
*
* @param x The input tensor to be summed.
* @param axis The axis along which to sum. Optional. Defaults to 0.
* @param exclusive Whether to perform exclusive cumulative sum. Optional.
* Defaults to false. If set to true then the sum of each tensor entry
* does not include its own value, but only the values previous to it
* along the specified axis.
* @param reverse Whether to sum in the opposite direction. Optional.
* Defaults to false.
*
* @doc {heading: 'Operations', subheading: 'Scan'}
*/
declare function cumsum_(x: Tensor | TensorLike, axis?: number, exclusive?: boolean, reverse?: boolean): T;
export declare interface CumsumAttrs {
axis: number;
exclusive: boolean;
reverse: boolean;
}
export declare type CumsumInputs = Pick;
/**
* Overrides the gradient computation of a function `f`.
*
* Takes a function
* `f(...inputs, save) => {value: Tensor, gradFunc: (dy, saved) => Tensor[]}`
* and returns another function `g(...inputs)` which takes the same inputs as
* `f`. When called, `g` returns `f().value`. In backward mode, custom gradients
* with respect to each input of `f` are computed using `f().gradFunc`.
*
* The `save` function passed to `f` should be used for saving tensors needed
* in the gradient. And the `saved` passed to the `gradFunc` is a
* `NamedTensorMap`, which contains those saved tensors.
*
* ```js
* const customOp = tf.customGrad((x, save) => {
* // Save x to make sure it's available later for the gradient.
* save([x]);
* // Override gradient of our custom x ^ 2 op to be dy * abs(x);
* return {
* value: x.square(),
* // Note `saved.x` which points to the `x` we saved earlier.
* gradFunc: (dy, saved) => [dy.mul(saved[0].abs())]
* };
* });
*
* const x = tf.tensor1d([-1, -2, 3]);
* const dx = tf.grad(x => customOp(x));
*
* console.log(`f(x):`);
* customOp(x).print();
* console.log(`f'(x):`);
* dx(x).print();
* ```
*
* @param f The function to evaluate in forward mode, which should return
* `{value: Tensor, gradFunc: (dy, saved) => Tensor[]}`, where `gradFunc`
* returns the custom gradients of `f` with respect to its inputs.
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
export declare function customGrad(f: CustomGradientFunc): (...args: Tensor[]) => T;
/**
* @docalias (a: Tensor, b: Tensor,..., save?: Function) => {
* value: Tensor,
* gradFunc: (dy: Tensor, saved?: NamedTensorMap) => Tensor | Tensor[]
* }
*/
declare type CustomGradientFunc = (...inputs: Array) => {
value: T;
gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[];
};
/**
* We wrap data id since we use weak map to avoid memory leaks.
* Since we have our own memory management, we have a reference counter
* mapping a tensor to its data, so there is always a pointer (even if that
* data is otherwise garbage collectable).
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/
* Global_Objects/WeakMap
*/
export declare type DataId = object;
export declare interface DataMover {
/**
* To be called by backends whenever they see a dataId that they don't own.
* Upon calling this method, the mover will fetch the tensor from another
* backend and register it with the current active backend.
*/
moveData(backend: KernelBackend, dataId: DataId): void;
}
/** Convenient class for storing tensor-related data. */
export declare class DataStorage {
private backend;
private dataMover;
private data;
private dataIdsCount;
constructor(backend: KernelBackend, dataMover: DataMover);
get(dataId: DataId): T;
set(dataId: DataId, value: T): void;
has(dataId: DataId): boolean;
delete(dataId: DataId): boolean;
numDataIds(): number;
}
export declare type DataToGPUOptions = DataToGPUWebGLOption;
export declare interface DataToGPUWebGLOption {
customTexShape?: [number, number];
}
/** @docalias 'float32'|'int32'|'bool'|'complex64'|'string' */
export declare type DataType = keyof DataTypeMap;
export declare type DataTypeFor = T extends number | boolean ? NumericDataType : T extends string ? 'string' : never;
export declare interface DataTypeMap {
float32: Float32Array;
int32: Int32Array;
bool: Uint8Array;
complex64: Float32Array;
string: string[];
}
/** Tensor data used in tensor creation and user-facing API. */
export declare type DataValues = DataTypeMap[DataType];
/**
* Parse an equation for einsum.
*
* @param equation The einsum equation (e.g., "ij,jk->ik").
* @param numTensors Number of tensors provided along with `equation`. Used to
* check matching number of input tensors.
* @returns An object consisting of the following fields:
* - allDims: all dimension names as strings.
* - summedDims: a list of all dimensions being summed over, as indices to
* the elements of `allDims`.
* - idDims: indices of the dimensions in each input tensor, as indices to
* the elements of `allDims.
*/
declare function decodeEinsumEquation(equation: string, numTensors: number): {
allDims: string[];
summedDims: number[];
idDims: number[][];
};
/**
* Decodes the provided bytes into a string using the provided encoding scheme.
* @param bytes The bytes to decode.
*
* @param encoding The encoding scheme. Defaults to utf-8.
*
* @doc {heading: 'Util'}
*/
declare function decodeString(bytes: Uint8Array, encoding?: string): string;
/**
* Decode flat ArrayBuffer as weights.
*
* This function does not handle sharding.
*
* This function is the reverse of `encodeWeights`.
*
* @param weightData A flat ArrayBuffer or an array of ArrayBuffers carrying the
* binary values of the tensors concatenated in the order specified in
* `specs`.
* @param specs Specifications of the names, dtypes and shapes of the tensors
* whose value are encoded by `buffer`.
* @return A map from tensor name to tensor value, with the names corresponding
* to names in `specs`.
* @throws Error, if any of the tensors has unsupported dtype.
*/
declare function decodeWeights(weightData: WeightData, specs: WeightsManifestEntry[]): NamedTensorMap;
export declare const DenseBincount = "DenseBincount";
export declare const denseBincount: typeof denseBincount_;
/**
* Outputs a vector with length `size` and the same dtype as `weights`.
*
* If `weights` are empty, then index `i` stores the number of times the value
* `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the
* sum of the value in `weights` at each index where the corresponding value in
* `x` is `i`.
*
* Values in `x` outside of the range [0, size) are ignored.
*
* @param x The input int tensor, rank 1 or rank 2.
* @param weights The weights tensor, must have the same shape as x, or a
* length-0 Tensor, in which case it acts as all weights equal to 1.
* @param size Non-negative integer.
* @param binaryOutput Optional. Whether the kernel should count the appearance
* or number of occurrences. Defaults to False.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
declare function denseBincount_(x: T | TensorLike, weights: T | TensorLike, size: number, binaryOutput?: boolean): T;
export declare interface DenseBincountAttrs {
size: number;
binaryOutput?: boolean;
}
export declare type DenseBincountInputs = Pick;
/** Warn users about deprecated functionality. */
export declare function deprecationWarn(msg: string): void;
export declare const DepthToSpace = "DepthToSpace";
export declare const depthToSpace: typeof depthToSpace_;
/**
* Rearranges data from depth into blocks of spatial data. More specifically,
* this op outputs a copy of the input tensor where values from the `depth`
* dimension are moved in spatial blocks to the `height` and `width` dimensions.
* The attr `blockSize` indicates the input block size and how the data is
* moved.
*
* - Chunks of data of size `blockSize * blockSize` from depth are rearranged
* into non-overlapping blocks of size `blockSize x blockSize`
*
* - The width the output tensor is `inputWidth * blockSize`, whereas the
* height is `inputHeight * blockSize`
*
* - The Y, X coordinates within each block of the output image are determined
* by the high order component of the input channel index
*
* - The depth of the input tensor must be divisible by `blockSize *
* blockSize`
*
* The `dataFormat` attr specifies the layout of the input and output tensors
* with the following options: "NHWC": [ `batch, height, width, channels` ]
* "NCHW": [ `batch, channels, height, width` ]
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [1, 1, 1, 4]);
* const blockSize = 2;
* const dataFormat = "NHWC";
*
* tf.depthToSpace(x, blockSize, dataFormat).print();
* ```
*
* @param x The input tensor of rank 4
* @param blockSIze An `int` that is `>= 2`. The size of the spatial block
* @param dataFormat An optional string from: "NHWC", "NCHW". Defaults to "NHWC"
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
declare function depthToSpace_(x: Tensor4D | TensorLike4D, blockSize: number, dataFormat?: 'NHWC' | 'NCHW'): Tensor4D;
export declare interface DepthToSpaceAttrs {
blockSize: number;
dataFormat: 'NHWC' | 'NCHW';
}
export declare type DepthToSpaceInputs = Pick;
export declare const depthwiseConv2d: typeof depthwiseConv2d_;
/**
* Depthwise 2D convolution.
*
* Given a 4D `input` array and a `filter` array of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing
* `inChannels` convolutional filters of depth 1, this op applies a
* different filter to each input channel (expanding from 1 channel to
* `channelMultiplier` channels for each), then concatenates the results
* together. The output has `inChannels * channelMultiplier` channels.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)
* for more details.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
declare function depthwiseConv2d_(x: T | TensorLike, filter: Tensor4D | TensorLike, strides: [number, number] | number, pad: 'valid' | 'same' | number | conv_util.ExplicitPadding, dataFormat?: 'NHWC' | 'NCHW', dilations?: [number, number] | number, dimRoundingMode?: 'floor' | 'round' | 'ceil'): T;
declare const depthwiseConv2d_2: typeof fusedDepthwiseConv2d_;
export declare const DepthwiseConv2dNative = "DepthwiseConv2dNative";
export declare interface DepthwiseConv2dNativeAttrs {
strides: [number, number] | number;
pad: 'valid' | 'same' | number | ExplicitPadding;
dataFormat: 'NHWC' | 'NCHW';
dilations: [number, number] | number;
dimRoundingMode?: 'floor' | 'round' | 'ceil';
}
export declare const DepthwiseConv2dNativeBackpropFilter = "DepthwiseConv2dNativeBackpropFilter";
export declare interface DepthwiseConv2dNativeBackpropFilterAttrs {
strides: [number, number] | number;
dilations: [number, number] | number;
pad: 'valid' | 'same' | number | ExplicitPadding;
dimRoundingMode?: 'floor' | 'round' | 'ceil';
filterShape: [number, number, number, number];
}
export declare type DepthwiseConv2dNativeBackpropFilterInputs = Pick;
export declare const DepthwiseConv2dNativeBackpropInput = "DepthwiseConv2dNativeBackpropInput";
export declare interface DepthwiseConv2dNativeBackpropInputAttrs {
strides: [number, number] | number;
dilations: [number, number] | number;
pad: 'valid' | 'same' | number | ExplicitPadding;
dimRoundingMode?: 'floor' | 'round' | 'ceil';
inputShape: [number, number, number, number];
}
export declare type DepthwiseConv2dNativeBackpropInputInputs = Pick;
export declare type DepthwiseConv2dNativeInputs = Pick;
declare namespace device_util {
export {
mockIsMobile,
isMobile,
isBrowser
}
}
export { device_util }
export declare const Diag = "Diag";
export declare const diag: typeof diag_;
/**
* Returns a diagonal tensor with given diagonal values.
*
* Given a diagonal, this operation returns a tensor with the diagonal and
* everything else padded with zeros.
*
* Assume the input has dimensions `[D1,..., Dk]`, then the output is a tensor
* of rank 2k with dimensions `[D1,..., Dk, D1,..., Dk]`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* tf.diag(x).print()
* ```
* ```js
* const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [4, 2])
*
* tf.diag(x).print()
* ```
* @param x The input tensor.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
declare function diag_(x: Tensor): Tensor;
export declare type DiagInputs = Pick;
export declare const Dilation2D = "Dilation2D";
export declare const dilation2d: typeof dilation2d_;
/**
* Computes the grayscale dilation over the input `x`.
*
* @param x The input tensor, rank 3 or rank 4 of shape
* `[batch, height, width, depth]`. If rank 3, batch of 1 is assumed.
* @param filter The filter tensor, rank 3, of shape
* `[filterHeight, filterWidth, depth]`.
* @param strides The strides of the sliding window for each dimension of the
* input tensor: `[strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat Specify the data format of the input and output data.
* Defaults to 'NHWC'. Only 'NHWC' is currently supported. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* for atrous morphological dilation. Defaults to `[1, 1]`. If `dilations`
* is a single number, then `dilationHeight == dilationWidth`. If it is
* greater than 1, then all values of `strides` must be 1.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
declare function dilation2d_(x: T | TensorLike, filter: Tensor3D | TensorLike, strides: [number, number] | number, pad: 'valid' | 'same', dilations?: [number, number] | number, dataFormat?: 'NHWC'): T;
export declare interface Dilation2DAttrs {
strides: [number, number] | number;
pad: 'valid' | 'same' | number;
dilations: [number, number] | number;
}
export declare const Dilation2DBackpropFilter = "Dilation2DBackpropFilter";
export declare type Dilation2DBackpropFilterInputs = Pick;
export declare const Dilation2DBackpropInput = "Dilation2DBackpropInput";
export declare type Dilation2DBackpropInputInputs = Pick;
export declare type Dilation2DInputs = Pick;
/** Globally disables deprecation warnings */
export declare function disableDeprecationWarnings(): void;
/**
* Disposes any `tf.Tensor`s found within the provided object.
*
* @param container an object that may be a `tf.Tensor` or may directly
* contain `tf.Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. If
* the object is not a `tf.Tensor` or does not contain `Tensors`, nothing
* happens. In general it is safe to pass any object here, except that
* `Promise`s are not supported.
*
* @doc {heading: 'Performance', subheading: 'Memory'}
*/
export declare function dispose(container: TensorContainer): void;
/**
* Dispose all variables kept in backend engine.
*
* @doc {heading: 'Environment'}
*/
export declare function disposeVariables(): void;
/** Returns the squared Euclidean distance between two vectors. */
declare function distSquared(a: FlatVector, b: FlatVector): number;
export declare const div: typeof div_;
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.div(b).print(); // or tf.div(a, b)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
*
* a.div(b).print(); // or tf.div(a, b)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
declare function div_(a: Tensor | TensorLike, b: Tensor | TensorLike): T;
export declare const divNoNan: typeof divNoNan_;
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting. Return 0
* if denominator is 0.
*
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
* const c = tf.tensor1d([0, 0, 0, 0]);
*
* a.divNoNan(b).print(); // or tf.divNoNan(a, b)
* a.divNoNan(c).print(); // or tf.divNoNan(a, c)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
* const c = tf.scalar(0);
*
* a.divNoNan(b).print(); // or tf.divNoNan(a, b)
* a.divNoNan(c).print(); // or tf.divNoNan(a, c)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
declare function divNoNan_(a: Tensor | TensorLike, b: Tensor | TensorLike): T;
declare interface DoneFn_2 {
(): void;
fail: (message?: Error | string) => void;
}
export declare const dot: typeof dot_;
/**
* Computes the dot product of two matrices and/or vectors, `t1` and `t2`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor2d([[1, 2], [3, 4]]);
* const c = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
*
* a.dot(b).print(); // or tf.dot(a, b)
* b.dot(a).print();
* b.dot(c).print();
* ```
* @param t1 The first tensor in the dot operation.
* @param t2 The second tensor in the dot operation.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
declare function dot_(t1: Tensor | TensorLike, t2: Tensor | TensorLike): Tensor;
export declare const Draw = "Draw";
/**
* Draws a `tf.Tensor` to a canvas.
*
* When the dtype of the input is 'float32', we assume values in the range
* [0-1]. Otherwise, when input is 'int32', we assume values in the range
* [0-255].
*
* @param image The tensor to draw on the canvas. Must match one of
* these shapes:
* - Rank-2 with shape `[height, width`]: Drawn as grayscale.
* - Rank-3 with shape `[height, width, 1]`: Drawn as grayscale.
* - Rank-3 with shape `[height, width, 3]`: Drawn as RGB with alpha set in
* `imageOptions` (defaults to 1, which is opaque).
* - Rank-3 with shape `[height, width, 4]`: Drawn as RGBA.
* @param canvas The canvas to draw to.
* @param options The configuration arguments for image to be drawn and the
* canvas to draw to.
*
* @doc {heading: 'Browser', namespace: 'browser'}
*/
declare function draw(image: Tensor2D | Tensor3D | TensorLike, canvas: HTMLCanvasElement, options?: DrawOptions): void;
export declare interface DrawAttrs {
canvas: HTMLCanvasElement;
options?: DrawOptions;
}
export declare type DrawInputs = Pick;
declare interface DrawOptions {
/**
* Optional. An object of options to customize the values of image tensor.
*/
imageOptions?: ImageOptions;
/**
* Optional. An object to configure the context of the canvas to draw to.
*/
contextOptions?: ContextOptions;
}
export declare const dropout: typeof dropout_;
/**
* Computes dropout.
*
* ```js
* const x = tf.tensor1d([1, 2, 2, 1]);
* const rate = 0.75;
* const output = tf.dropout(x, rate);
* output.print();
* ```
*
* @param x A floating point Tensor or TensorLike.
* @param rate A float in the range [0, 1). The probability that each element
* of x is discarded.
* @param noiseShape An array of numbers of type int32, representing the
* shape for randomly generated keep/drop flags. If the noiseShape has null
* value, it will be automatically replaced with the x's relative dimension
* size. Optional.
* @param seed Used to create random seeds. Optional.
* @returns A Tensor of the same shape of x.
*
* @doc {heading: 'Operations', subheading: 'Dropout'}
*/
declare function dropout_(x: Tensor | TensorLike, rate: number, noiseShape?: number[], seed?: number | string): Tensor;
export declare const Einsum = "Einsum";
export declare const einsum: typeof einsum_;
/**
* Tensor contraction over specified indices and outer product.
*
* `einsum` allows defining Tensors by defining their element-wise computation.
* This computation is based on
* [Einstein summation](https://en.wikipedia.org/wiki/Einstein_notation).
*
* Some special cases include:
*
* Matrix multiplication:
* ```js
* const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
* const y = tf.tensor2d([[0, 1], [2, 3], [4, 5]]);
* x.print();
* y.print();
* tf.einsum('ij,jk->ik', x, y).print();
* ```
*
* Dot product:
* ```js
* const x = tf.tensor1d([1, 2, 3]);
* const y = tf.tensor1d([0, 1, 2]);
* x.print();
* y.print();
* tf.einsum('i,i->', x, y).print();
* ```
*
* Batch dot product:
* ```js
* const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
* const y = tf.tensor2d([[0, 1, 2], [3, 4, 5]]);
* x.print();
* y.print();
* tf.einsum('bi,bi->b', x, y).print();
* ```
*
* Outer prouduct:
* ```js
* const x = tf.tensor1d([1, 3, 5]);
* const y = tf.tensor1d([2, 4, 6]);
* x.print();
* y.print();
* tf.einsum('i,j->ij', x, y).print();
* ```
*
* Matrix transpose:
* ```js
* const x = tf.tensor2d([[1, 2], [3, 4]]);
* x.print();
* tf.einsum('ij->ji', x).print();
* ```
*
* Batch matrix transpose:
* ```js
* const x = tf.tensor3d([[[1, 2], [3, 4]], [[-1, -2], [-3, -4]]]);
* x.print();
* tf.einsum('bij->bji', x).print();
* ```
*
* Limitations:
*
* This implementation of einsum has the following limitations:
*
* - Does not support >2 input tensors.
* - Does not support duplicate axes for any given input tensor. E.g., equation
* 'ii->' is not supported.
* - The `...` notation is not supported.
*
* @param equation a string describing the contraction, in the same format as
* [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html).
* @param tensors the input(s) to contract (each one a Tensor), whose shapes
* should be consistent with equation.
* @returns The output tensor.
*
* @doc {heading: 'Tensors', subheading: 'Matrices'}
*/
declare function einsum_(equation: string, ...tensors: Tensor[]): Tensor;
export declare interface EinsumAttrs {
equation: string;
}
export declare type EinsumInputs = TensorInfo[];
declare function eitherStridesOrDilationsAreOne(strides: number | number[], dilations: number | number[]): boolean;
export declare const Elu = "Elu";
export declare const elu: typeof elu_;
/**
* Computes exponential linear element-wise: `x > 0 ? x : (e ^ x) - 1`.
*
* ```js
* const x = tf.tensor1d([-1, 1, -3, 2]);
*
* x.elu().print(); // or tf.elu(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
declare function elu_(x: T | TensorLike): T;
export declare const EluGrad = "EluGrad";
export declare type EluGradInputs = Pick;
export declare type EluInputs = Pick;
/**
* Enables debug mode which will log information about all executed kernels:
* the elapsed time of the kernel execution, as well as the rank, shape, and
* size of the output tensor.
*
* Debug mode will significantly slow down your application as it will
* download the result of every operation to the CPU. This should not be used in
* production. Debug mode does not affect the timing information of the kernel
* execution as we do not measure download time in the kernel execution time.
*
* See also: `tf.profile`, `tf.memory`.
*
* @doc {heading: 'Environment'}
*/
export declare function enableDebugMode(): void;
/**
* Enables production mode which disables correctness checks in favor of
* performance.
*
* @doc {heading: 'Environment'}
*/
export declare function enableProdMode(): void;
export declare function enclosingPowerOfTwo(value: number): number;
/**
* Encodes the provided string into bytes using the provided encoding scheme.
*
* @param s The string to encode.
* @param encoding The encoding scheme. Defaults to utf-8.
*
* @doc {heading: 'Util'}
*/
declare function encodeString(s: string, encoding?: string): Uint8Array;
/** Encodes strings into utf-8 bytes. */
declare function encodeStrings(a: RecursiveArray<{}>): RecursiveArray;
/**
* Encode a map from names to weight values as an ArrayBuffer, along with an
* `Array` of `WeightsManifestEntry` as specification of the encoded weights.
*
* This function does not perform sharding.
*
* This function is the reverse of `decodeWeights`.
*
* @param tensors A map ("dict") from names to tensors.
* @param group Group to which the weights belong (optional).
* @returns A `Promise` of
* - A flat `ArrayBuffer` with all the binary values of the `Tensor`s
* concatenated.
* - An `Array` of `WeightManifestEntry`s, carrying information including
* tensor names, `dtype`s and shapes.
* @throws Error: on unsupported tensor `dtype`.
*/
declare function encodeWeights(tensors: NamedTensorMap | NamedTensor[], group?: WeightGroup): Promise<{
data: ArrayBuffer;
specs: WeightsManifestEntry[];
}>;
declare class Engine implements TensorTracker, DataMover {
ENV: Environment;
state: EngineState;
backendName: string;
registry: {
[id: string]: KernelBackend;
};
registryFactory: {
[id: string]: {
factory: () => KernelBackend | Promise;
priority: number;
};
};
private profiler;
private backendInstance;
private pendingBackendInit;
private pendingBackendInitId;
constructor(ENV: Environment);
ready(): Promise;
get backend(): KernelBackend;
backendNames(): string[];
findBackend(backendName: string): KernelBackend;
findBackendFactory(backendName: string): () => KernelBackend | Promise;
registerBackend(backendName: string, factory: () => KernelBackend | Promise, priority?: number): boolean;
setBackend(backendName: string): Promise;
private setupRegisteredKernels;
private disposeRegisteredKernels;
/**
* Initializes a backend by looking up the backend name in the factory
* registry and calling the factory method. Returns a boolean representing
* whether the initialization of the backend suceeded. Throws an error if
* there is no backend in the factory registry.
*/
private initializeBackend;
removeBackend(backendName: string): void;
private getSortedBackends;
private initializeBackendsAndReturnBest;
moveData(backend: KernelBackend, dataId: DataId): void;
tidy(nameOrFn: string | ScopeFn, fn?: ScopeFn): T;
private scopedRun;
private static nextTensorId;
private nextTensorId;
private static nextVariableId;
private nextVariableId;
/**
* This method is called instead of the public-facing tensor.clone() when
* saving a tensor for backwards pass. It makes sure to add the clone
* operation to the tape regardless of being called inside a kernel
* execution.
*/
private clone;
/**
* Execute a kernel with the given name and return the output tensor.
*
* @param kernelName The name of the kernel to execute.
* @param inputs A map of input names to tensors.
* @param attrs A map of attribute names to their values. An attribute is a
* primitive (non-tensor) input to the kernel.
* @param inputsToSave A list of tensors, inputs to save for the backprop
* computation.
* @param outputsToSave A list of booleans, specifying which output to save
* for the backprop computation. These are booleans since the output
* tensors are not visible to the user.
*/
runKernel(kernelName: string, inputs: NamedTensorMap, attrs?: NamedAttrMap): T;
private shouldCheckForMemLeaks;
private checkKernelForMemLeak;
/**
* Internal helper method to execute a kernel Func
*
* Use `runKernel` to execute kernels from outside of engine.
*/
private runKernelFunc;
/**
* Saves tensors used in forward mode for use in backward mode.
*
* @param tensors the list of tensors to save.
*/
private saveTensorsForBackwardMode;
/**
* Returns a list of tensors to save for a given gradient calculation.
*
* @param kernelName name of kernel to look up gradient for.
* @param inputs a map of input tensors.
* @param outputs an array of output tensors from forward mode of kernel.
*/
private getTensorsForGradient;
/**
* Internal method used by public APIs for tensor creation. Makes a new
* tensor with the provided shape, dtype and values. It always
* creates a new data id and writes the values to the underlying backend.
*/
makeTensor(values: DataValues, shape: number[], dtype: DataType, backend?: KernelBackend): Tensor;
/**
* Internal method used by backends. Makes a new tensor
* that is a wrapper around an existing data id. It doesn't create
* a new data id, only increments the ref count used in memory tracking.
* @deprecated
*/
makeTensorFromDataId(dataId: DataId, shape: number[], dtype: DataType, backend?: KernelBackend): Tensor;
/**
* Internal method used by backends. Makes a new tensor that is a wrapper
* around an existing data id in TensorInfo. It doesn't create a new data id,
* only increments the ref count used in memory tracking.
*/
makeTensorFromTensorInfo(tensorInfo: TensorInfo, backend?: KernelBackend): Tensor;
makeVariable(initialValue: Tensor, trainable?: boolean, name?: string, dtype?: DataType): Variable;
trackTensor(a: Tensor, backend: KernelBackend): void;
incRef(a: Tensor, backend: KernelBackend): void;
removeDataId(dataId: DataId, backend: KernelBackend): void;
disposeTensor(a: Tensor): void;
disposeVariables(): void;
disposeVariable(v: Variable): void;
memory(): MemoryInfo;
profile(query: () => (TensorContainer | Promise)): Promise;
isTapeOn(): boolean;
private addTapeNode;
keep(result: T): T;
private startTape;
private endTape;
/**
* Start a scope. Use this with endScope() to achieve the same functionality
* as scope() without the need for a function closure.
*/
startScope(name?: string): void;
/**
* End a scope. Use this with startScope() to achieve the same functionality
* as scope() without the need for a function closure.
*/
endScope(result?: TensorContainer): void;
/**
* Returns gradients of `f` with respect to each of the `xs`. The gradients
* returned are of the same length as `xs`, but some might be null if `f`
* was not a function of that `x`. It also takes optional dy to multiply the
* gradient, which defaults to `1`.
*/
gradients(f: () => T, xs: Tensor[], dy?: T, allowNoGradients?: boolean): {
value: T;
grads: Tensor[];
};
customGrad(f: CustomGradientFunc): (...args: Array) => T;
readSync(dataId: DataId): BackendValues;
read(dataId: DataId): Promise;
readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData;
time(query: () => void): Promise;
/**
* Tracks a Tensor in the current scope to be automatically cleaned up
* when the current scope ends, and returns the value.
*
* @param result The Tensor to track in the current scope.
*/
private track;
get registeredVariables(): NamedVariableMap;
/**
* Resets the engine state. Removes all backends but does not remove
* registered backend factories.
*/
reset(): void;
}
/**
* It returns the global engine that keeps track of all tensors and backends.
*
* @doc {heading: 'Environment'}
*/
export declare function engine(): Engine;
declare class EngineState {
registeredVariables: NamedVariableMap;
nextTapeNodeId: number;
numBytes: number;
numTensors: number;
numStringTensors: number;
numDataBuffers: number;
activeTape: TapeNode[];
gradientDepth: number;
kernelDepth: number;
activeScope: ScopeState;
scopeStack: ScopeState[];
/**
* Keeps track of the number of data moves during a kernel execution. We
* maintain a stack since kernels can call other kernels, recursively.
*/
numDataMovesStack: number[];
nextScopeId: number;
tensorInfo: WeakMap