Revert "TensorFlow Source"

This reverts commit 12d53f218e.
This commit is contained in:
B Harrell committed 2021-05-25 11:04:10 -05:00
1 parent bc9d981422
commit c4269bbd3a
215 files changed
+51 -45638

No files matched your search

@@ -31,15 +31,13 @@ export interface BackendTimingInfo {
export interface TensorStorage {
read(dataId: DataId): Promise<BackendValues>;
readSync(dataId: DataId): BackendValues;
disposeData(dataId: DataId, force?: boolean): boolean;
disposeData(dataId: DataId): void;
write(values: BackendValues, shape: number[], dtype: DataType): DataId;
move(
dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,
refCount: number): void;
move(dataId: DataId, values: BackendValues, shape: number[], dtype: DataType):
void;
memory(): {unreliable: boolean;}; // Backend-specific information.
/** Returns number of data ids currently in the storage. */
numDataIds(): number;
refCount(dataId: DataId): number;
}
/** Convenient class for storing tensor-related data. */
@@ -85,8 +83,6 @@ export interface DataMover {
}
export interface BackendTimer {
// check if backend timer is available
timerAvailable(): boolean;
time(f: () => void): Promise<BackendTimingInfo>;
}
@@ -97,14 +93,15 @@ export interface BackendTimer {
* methods).
*/
export class KernelBackend implements TensorStorage, Backend, BackendTimer {
refCount(dataId: DataId): number {
return notYetImplemented('refCount');
}
incRef(dataId: DataId): void {
return notYetImplemented('incRef');
}
timerAvailable(): boolean {
return true;
/**
* Decrease the complex ref count for the dataId, this is useful for WebGL
* backend to keep the real and imag components of the complex tensor in sync
* with the engine. WASM and node do not have internal ref count, they will
* use on the default implementation.
* @param dataId
*/
decComplexRef(dataId: DataId): void {
return;
}
time(f: () => void): Promise<BackendTimingInfo> {
return notYetImplemented('time');
@@ -118,15 +115,14 @@ export class KernelBackend implements TensorStorage, Backend, BackendTimer {
numDataIds(): number {
return notYetImplemented('numDataIds');
}
disposeData(dataId: object, force?: boolean): boolean {
disposeData(dataId: object): void {
return notYetImplemented('disposeData');
}
write(values: BackendValues, shape: number[], dtype: DataType): DataId {
return notYetImplemented('write');
}
move(
dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,
refCount: number): void {
move(dataId: DataId, values: BackendValues, shape: number[], dtype: DataType):
void {
return notYetImplemented('move');
}
memory(): {unreliable: boolean; reasons?: string[]} {
@@ -1,220 +0,0 @@
/**
* @license
* Copyright 2021 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.
* =============================================================================
*/
/**
* Utility functions for computing einsum (tensor contraction and summation
* based on Einstein summation.)
*/
import {Tensor} from '../tensor';
import {assert} from '../util_base';
const ARROW = '->';
const ARROW_REGEX = /->/g;
const COMMA = ',';
const ELLIPSIS = '...';
/**
* 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.
*/
export function decodeEinsumEquation(equation: string, numTensors: number): {
allDims: string[],
summedDims: number[],
idDims: number[][],
} {
equation = equation.replace(/\s/g, ''); // Remove witespace in equation.
const numArrows =
(equation.length - equation.replace(ARROW_REGEX, '').length) /
ARROW.length;
if (numArrows < 1) {
throw new Error('Equations without an arrow are not supported.');
} else if (numArrows > 1) {
throw new Error(`Equation must contain exactly one arrow ("${ARROW}").`);
}
const [inputString, outputString] = equation.split(ARROW);
assert(
inputString.indexOf(ELLIPSIS) === -1,
() => `The ellipsis notation ("${ELLIPSIS}") is not supported yet.`);
const inputTerms = inputString.split(COMMA);
const numInputs = inputTerms.length;
if (numTensors !== numInputs) {
throw new Error(
`Expected ${numInputs} input tensors, received ${numTensors}`);
}
if (numInputs > 2) {
throw new Error(
'Support for more than 2 input tensors is not implemented yet.');
}
const allDims: string[] = [];
for (let i = 0; i < outputString.length; ++i) {
const dimName = outputString[i];
if (!inputTerms.some(inputTerm => inputTerm.indexOf(dimName) !== -1)) {
throw new Error(
`Output subscripts contain the label ${dimName} ` +
`not present in the input subscripts.`);
}
if (allDims.indexOf(dimName) === -1) {
allDims.push(dimName);
}
}
for (let i = 0; i < inputString.length; ++i) {
const dimName = inputString[i];
if (allDims.indexOf(dimName) === -1 && dimName !== COMMA) {
allDims.push(dimName);
}
}
const idDims: number[][] = new Array<number[]>(inputTerms.length);
for (let i = 0; i < numInputs; ++i) {
if (new Set(inputTerms[i].split('')).size !== inputTerms[i].length) {
throw new Error(
`Found duplicate axes in input component ${inputTerms[i]}. ` +
`Support for duplicate axes in input is not implemented yet.`);
}
idDims[i] = [];
for (let j = 0; j < inputTerms[i].length; ++j) {
idDims[i].push(allDims.indexOf(inputTerms[i][j]));
}
}
const numDims = allDims.length; // Number of unique dimensions.
const numOutDims = outputString.length; // Number of output dimensions.
const summedDims: number[] = []; // Dimensions being summed over.
for (let i = numOutDims; i < numDims; ++i) {
summedDims.push(i);
}
return {allDims, summedDims, idDims};
}
/**
* Get the permutation for a given input tensor.
*
* @param nDims Total number of dimension of all tensors involved in the einsum
* operation.
* @param idDims Dimension indices involve in the tensor in question.
* @returns An object consisting of the following fields:
* - permutationIndices: Indices to permute the axes of the tensor with.
* - expandDims: Indices to the dimension that need to be expanded from the
* tensor after permutation.
*/
export function getEinsumPermutation(nDims: number, idDims: number[]):
{permutationIndices: number[], expandDims: number[]} {
let permutationIndices: number[] = new Array<number>(nDims);
permutationIndices.fill(-1);
for (let i = 0; i < idDims.length; ++i) {
permutationIndices[idDims[i]] = i;
}
const expandDims: number[] = [];
for (let i = 0; i < nDims; ++i) {
if (permutationIndices[i] === -1) {
expandDims.push(i);
}
}
permutationIndices = permutationIndices.filter(d => d !== -1);
return {permutationIndices, expandDims};
}
/**
* Checks that the dimension sizes from different input tensors match the
* equation.
*/
export function checkEinsumDimSizes(
nDims: number, idDims: number[][], tensors: Tensor[]) {
const dimSizes: number[] = new Array<number>(nDims);
for (let i = 0; i < tensors.length; ++i) {
const shape: number[] = tensors[i].shape;
for (let j = 0; j < idDims[i].length; ++j) {
if (dimSizes[idDims[i][j]] === undefined) {
dimSizes[idDims[i][j]] = shape[j];
} else {
assert(
dimSizes[idDims[i][j]] === shape[j],
() => `Expected dimension ${dimSizes[idDims[i][j]]} at axis ${j} ` +
`of input shaped ${JSON.stringify(shape)}, ` +
`but got dimension ${shape[j]}`);
}
}
}
}
/**
* Gets path of computation for einsum.
*
* @param summedDims indices to the dimensions being summed over.
* @param idDims A look up table for the dimensions present in each input
* tensor. Each consituent array contains indices for the dimensions in the
* corresponding input tensor.
*
* @return A map with two fields:
* - path: The path of computation, with each element indicating the dimension
* being summed over after the element-wise multiplication in that step.
* - steps: With the same length as `path`. Each element contains the indices
* to the input tensors being used for element-wise multiplication in the
* corresponding step.
*/
export function getEinsumComputePath(summedDims: number[], idDims: number[][]):
{path: number[], steps: number[][]} {
const path: number[] = summedDims;
const steps: number[][] = [];
let nSteps = 0;
if (summedDims.length === 0) {
// Einsum that involes no summing: e.g., transpose and outer product.
path.push(-1);
}
nSteps = summedDims.length + 1;
for (let i = 0; i < nSteps; ++i) {
steps.push([]);
}
const computedTermIndices: number[] = [];
for (let i = 0; i < path.length; ++i) {
const summedDim = path[i];
const termIndices = findTermsWithDim(idDims, summedDim);
for (const termIndex of termIndices) {
if (computedTermIndices.indexOf(termIndex) === -1) {
steps[i].push(termIndex);
computedTermIndices.push(termIndex);
}
}
}
return {path, steps};
}
/** Determines if an axes permutation is the identity permutation. */
export function isIdentityPermutation(perm: number[]): boolean {
return perm.every((dim: number, index: number) => dim === index);
}
function findTermsWithDim(idDims: number[][], dim: number): number[] {
const termIndices: number[] = [];
for (let i = 0; i < idDims.length; ++i) {
if (idDims[i].length === 0 || idDims[i].indexOf(dim) !== -1 || dim === -1) {
termIndices.push(i);
}
}
return termIndices;
}
@@ -16,7 +16,6 @@
*/
import {ENGINE} from '../engine';
import {env} from '../environment';
import {FromPixels, FromPixelsAttrs, FromPixelsInputs} from '../kernel_names';
import {getKernel, NamedAttrMap} from '../kernel_registry';
import {Tensor, Tensor2D, Tensor3D} from '../tensor';
@@ -51,8 +50,6 @@ let fromPixels2DContext: CanvasRenderingContext2D;
* numChannels value less than 4 allows you to ignore channels. Defaults to
* 3 (ignores alpha channel of input image).
*
* @returns A Tensor3D with the shape `[height, width, numChannels]`.
*
* @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}
*/
function fromPixels_(
@@ -90,7 +87,8 @@ function fromPixels_(
} else if ((pixels as any).getContext != null) {
isCanvasLike = true;
} else if (
typeof (ImageBitmap) !== 'undefined' && pixels instanceof ImageBitmap) {
typeof (ImageBitmap) !== 'undefined' &&
pixels instanceof ImageBitmap) {
isImageBitmap = true;
} else {
throw new Error(
@@ -161,103 +159,6 @@ function fromPixels_(
return tensor3d(values, outShape, 'int32');
}
// Helper functions for |fromPixelsAsync| to check whether the input can
// be wrapped into imageBitmap.
function isPixelData(pixels: PixelData|ImageData|HTMLImageElement|
HTMLCanvasElement|HTMLVideoElement|
ImageBitmap): pixels is PixelData {
return (pixels != null) && ((pixels as PixelData).data instanceof Uint8Array);
}
function isImageBitmapFullySupported() {
return typeof window !== 'undefined' &&
typeof (ImageBitmap) !== 'undefined' &&
window.hasOwnProperty('createImageBitmap');
}
function isNonEmptyPixels(pixels: PixelData|ImageData|HTMLImageElement|
HTMLCanvasElement|HTMLVideoElement|ImageBitmap) {
return pixels != null && pixels.width !== 0 && pixels.height !== 0;
}
function canWrapPixelsToImageBitmap(pixels: PixelData|ImageData|
HTMLImageElement|HTMLCanvasElement|
HTMLVideoElement|ImageBitmap) {
return isImageBitmapFullySupported() && !(pixels instanceof ImageBitmap) &&
isNonEmptyPixels(pixels) && !isPixelData(pixels);
}
/**
* Creates a `tf.Tensor` from an image in async way.
*
* ```js
* const image = new ImageData(1, 1);
* image.data[0] = 100;
* image.data[1] = 150;
* image.data[2] = 200;
* image.data[3] = 255;
*
* (await tf.browser.fromPixelsAsync(image)).print();
* ```
* This API is the async version of fromPixels. The API will first
* check |WRAP_TO_IMAGEBITMAP| flag, and try to wrap the input to
* imageBitmap if the flag is set to true.
*
* @param pixels The input image to construct the tensor from. The
* supported image types are all 4-channel. You can also pass in an image
* object with following attributes:
* `{data: Uint8Array; width: number; height: number}`
* @param numChannels The number of channels of the output tensor. A
* numChannels value less than 4 allows you to ignore channels. Defaults to
* 3 (ignores alpha channel of input image).
*
* @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}
*/
export async function fromPixelsAsync(
pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|
HTMLVideoElement|ImageBitmap,
numChannels = 3) {
let inputs: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|
HTMLVideoElement|ImageBitmap = null;
// Check whether the backend needs to wrap |pixels| to imageBitmap and
// whether |pixels| can be wrapped to imageBitmap.
if (env().getBool('WRAP_TO_IMAGEBITMAP') &&
canWrapPixelsToImageBitmap(pixels)) {
// Force the imageBitmap creation to not do any premultiply alpha
// ops.
let imageBitmap;
try {
// wrap in try-catch block, because createImageBitmap may not work
// properly in some browsers, e.g.
// https://bugzilla.mozilla.org/show_bug.cgi?id=1335594
// tslint:disable-next-line: no-any
imageBitmap = await (createImageBitmap as any)(
pixels as ImageBitmapSource, {premultiplyAlpha: 'none'});
} catch (e) {
imageBitmap = null;
}
// createImageBitmap will clip the source size.
// In some cases, the input will have larger size than its content.
// E.g. new Image(10, 10) but with 1 x 1 content. Using
// createImageBitmap will clip the size from 10 x 10 to 1 x 1, which
// is not correct. We should avoid wrapping such resouce to
// imageBitmap.
if (imageBitmap != null && imageBitmap.width === pixels.width &&
imageBitmap.height === pixels.height) {
inputs = imageBitmap;
} else {
inputs = pixels;
}
} else {
inputs = pixels;
}
return fromPixels_(inputs, numChannels);
}
/**
* Draws a `tf.Tensor` of pixel values to a byte array or optionally a
* canvas.
@@ -268,9 +169,8 @@ export async function fromPixelsAsync(
*
* Returns a promise that resolves when the canvas has been drawn to.
*
* @param img A rank-2 tensor with shape `[height, width]`, or a rank-3 tensor
* of shape `[height, width, numChannels]`. If rank-2, draws grayscale. If
* rank-3, must have depth of 1, 3 or 4. When depth of 1, draws
* @param img A rank-2 or rank-3 tensor. If rank-2, draws grayscale. If
* rank-3, must have depth of 1, 3 or 4. When depth of 1, draws
* grayscale. When depth of 3, we draw with the first three components of
* the depth dimension corresponding to r, g, b and alpha = 1. When depth of
* 4, all four components of the depth dimension correspond to r, g, b, a.
@@ -23,7 +23,6 @@ import {convertToTensor} from '../tensor_util_env';
import {TensorLike} from '../types';
import * as util from '../util';
import {ExplicitPadding} from './conv_util';
import {op} from './operation';
import {reshape} from './reshape';
@@ -74,8 +73,7 @@ import {reshape} from './reshape';
*/
function depthwiseConv2d_<T extends Tensor3D|Tensor4D>(
x: T|TensorLike, filter: Tensor4D|TensorLike,
strides: [number, number]|number,
pad: 'valid'|'same'|number|ExplicitPadding,
strides: [number, number]|number, pad: 'valid'|'same'|number,
dataFormat: 'NHWC'|'NCHW' = 'NHWC',
dilations: [number, number]|number = [1, 1],
dimRoundingMode?: 'floor'|'round'|'ceil'): T {
@@ -20,14 +20,12 @@ import {NamedAttrMap} from '../kernel_registry';
import {Tensor3D, Tensor4D} from '../tensor';
import {NamedTensorMap} from '../tensor_types';
import {ExplicitPadding} from './conv_util';
import {op} from './operation';
import {reshape} from './reshape';
function depthwiseConv2dNativeBackpropFilter_<T extends Tensor3D|Tensor4D>(
x: T, dy: T, filterShape: [number, number, number, number],
strides: [number, number]|number,
pad: 'valid'|'same'|number|ExplicitPadding,
strides: [number, number]|number, pad: 'valid'|'same'|number,
dilations: [number, number]|number = [1, 1],
dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {
let x4D = x as Tensor4D;
@@ -20,14 +20,12 @@ import {NamedAttrMap} from '../kernel_registry';
import {Tensor3D, Tensor4D} from '../tensor';
import {NamedTensorMap} from '../tensor_types';
import {ExplicitPadding} from './conv_util';
import {op} from './operation';
import {reshape} from './reshape';
function depthwiseConv2dNativeBackpropInput_<T extends Tensor3D|Tensor4D>(
xShape: [number, number, number, number], dy: T, filter: Tensor4D,
strides: [number, number]|number,
pad: 'valid'|'same'|number|ExplicitPadding,
strides: [number, number]|number, pad: 'valid'|'same'|number,
dilations: [number, number]|number = [1, 1],
dimRoundingMode?: 'floor'|'round'|'ceil'): T {
let dy4D = dy as Tensor4D;
@@ -43,8 +43,6 @@ import {op} from './operation';
* tf.diag(x).print()
* ```
* @param x The input tensor.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function diag_(x: Tensor): Tensor {
const $x = convertToTensor(x, 'x', 'diag');
@@ -1,111 +0,0 @@
/**
* @license
* Copyright 2021 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.
* =============================================================================
*/
import {ENGINE} from '../engine';
import {Einsum, EinsumAttrs} from '../kernel_names';
import {NamedAttrMap} from '../kernel_registry';
import {Tensor} from '../tensor';
import {NamedTensorMap} from '../tensor_types';
import {convertToTensor} from '../tensor_util_env';
import {op} from './operation';
/**
* 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 suppoted.
* - 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'}
*/
export function einsum_(equation: string, ...tensors: Tensor[]): Tensor {
const $tensors =
tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'einsum'));
const attrs: EinsumAttrs = {equation};
return ENGINE.runKernel(
Einsum, $tensors as {} as NamedTensorMap, attrs as {} as NamedAttrMap);
}
export const einsum = op({einsum_});
@@ -39,5 +39,4 @@ export type FusedBatchMatMulConfig = {
leakyreluAlpha?: number
};
export type Activation =
'linear'|'relu'|'prelu'|'elu'|'relu6'|'leakyrelu'|'sigmoid';
export type Activation = 'linear'|'relu'|'prelu'|'elu'|'relu6'|'leakyrelu';
@@ -26,7 +26,6 @@ import {prelu} from './prelu';
import {relu} from './relu';
import {relu6} from './relu6';
import {reshape} from './reshape';
import {sigmoid} from './sigmoid';
import {step} from './step';
import {sum} from './sum';
@@ -70,8 +69,6 @@ export function applyActivation(
return prelu(x, preluActivationWeights);
} else if (activation === 'leakyrelu') {
return leakyRelu(x, leakyreluAlpha);
} else if (activation === 'sigmoid') {
return sigmoid(x);
}
throw new Error(`Unknown fused activation ${activation}.`);
}
@@ -1,163 +0,0 @@
/**
* @license
* Copyright 2021 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
*
* https://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.
* =============================================================================
*/
import { Tensor1D, Tensor3D } from '../../tensor';
import { tensor1d } from '../tensor1d';
import { TensorLike } from '../../types';
import { op } from '../operation';
import { cast } from '../cast';
import { split } from '../split';
import { bincount } from '../bincount';
import { lessEqual } from '../less_equal';
import { greater } from '../greater';
import { sum } from '../sum';
import { add } from '../add';
import { mul } from '../mul';
import { div } from '../div';
import { sub } from '../sub';
import { round } from '../round';
import { where } from '../where';
import { fill } from '../fill';
import {slice} from '../slice';
import { range } from '../range';
import { tensor } from '../tensor';
import * as util from '../../util';
import { convertToTensor } from '../../tensor_util_env';
/**
* Performs image binarization with corresponding threshold
* (depends on the method)value, which creates a binary image from a grayscale.
* @param image 3d tensor of shape [imageHeight,imageWidth, depth],
* where imageHeight and imageWidth must be positive.The image color
* range should be [0, 255].
* @param method Optional string from `'binary' | 'otsu'`
* which specifies the method for thresholding. Defaults to 'binary'.
* @param inverted Optional boolean whichspecifies
* if colours should be inverted. Defaults to false.
* @param threshValue Optional number which defines threshold value from 0 to 1.
* Defaults to 0.5.
* @return A 3d tensor of shape [imageHeight,imageWidth, depth], which
* contains binarized image.
*/
function threshold_(
image: Tensor3D | TensorLike,
method = 'binary',
inverted = false,
threshValue = 0.5
): Tensor3D {
const $image = convertToTensor(image, 'image', 'threshold');
/* 0.2989, 0.5870, 0.1140 are represent luma coefficients in CCIR601.
Reference for converting between RGB and grayscale: https://en.wikipedia.org/wiki/Luma_%28video%29 */
const RED_INTENCITY_COEF = 0.2989;
const GREEN_INTENCITY_COEF = 0.5870;
const BLUE_INTENCITY_COEF = 0.1140;
const totalPixelsInImage = $image.shape[0] * $image.shape[1];
let $threshold = mul(tensor1d([threshValue]), 255);
let r, g, b, grayscale;
util.assert(
$image.rank === 3,
() => 'Error in threshold: image must be rank 3,' +
`but got rank ${$image.rank}.`);
util.assert(
$image.shape[2] === 3 || $image.shape[2]=== 1,
() => 'Error in threshold: ' +
'image color channel must be equal to 3 or 1' +
`but got ${$image.shape[2]}.`);
util.assert(
$image.dtype === 'int32' || $image.dtype === 'float32',
() => 'Error in dtype: image dtype must be int32 or float32,' +
`but got dtype ${$image.dtype}.`);
util.assert(
method === 'otsu' || method === 'binary',
() => `Method must be binary or otsu, but was ${method}`);
if ($image.shape[2] === 3) {
[r, g, b] = split($image, [1, 1, 1], -1);
const $r = mul(r,RED_INTENCITY_COEF);
const $g = mul(g,GREEN_INTENCITY_COEF);
const $b = mul(b,BLUE_INTENCITY_COEF);
grayscale = add(add($r, $g), $b);
} else {
grayscale = image;
}
if (method === 'otsu') {
const $histogram = bincount(cast(round(grayscale), 'int32') as Tensor1D,
tensor([]),
256);
$threshold = otsu($histogram, totalPixelsInImage);
}
const invCondition = inverted ?
lessEqual(grayscale, $threshold) : greater(grayscale, $threshold);
const result = cast(mul(invCondition,255), 'int32');
return result as Tensor3D;
}
function otsu(histogram: Tensor1D, total: number):Tensor1D {
let bestThresh = tensor1d([-1]);
let bestInBetVar = tensor1d([0]);
let cInBetVar = tensor1d([0]);
let classFirst, classSecond, meanFirst,
meanSec, weightForeground, weightBack;
for (let index = 0; index < histogram.size-1; index++) {
classFirst = slice(histogram, 0, index + 1);
classSecond = slice(histogram,index + 1);
weightForeground = div(sum(classFirst),total);
weightBack = div(sum(classSecond),total);
const meanFirstDivA = sum(mul(classFirst, range(0, classFirst.size)));
meanFirst = div(meanFirstDivA, sum(classFirst) );
const meanSecFill = fill(classSecond.shape, classFirst.size);
const meanSecAdd = add(range(0,classSecond.size),meanSecFill);
const meanSecMul = mul(classSecond, (meanSecAdd));
meanSec = div(sum(meanSecMul), sum(classSecond));
const cInBetVarSubA = sub(meanFirst, meanSec);
const cInBetVarSubB = sub(meanFirst, meanSec);
const cInBetVarMul = mul(weightForeground, weightBack);
cInBetVar = mul(mul(cInBetVarMul,cInBetVarSubA), cInBetVarSubB);
const condition = greater(cInBetVar, bestInBetVar);
bestInBetVar = where(condition, cInBetVar, bestInBetVar);
bestThresh = where(condition, tensor1d([index]), bestThresh);
}
return bestThresh;
}
export const threshold = op({ threshold_ });
@@ -1,93 +0,0 @@
/**
* @license
* Copyright 2021 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.
* =============================================================================
*/
import {ENGINE} from '../../engine';
import {Transform, TransformAttrs, TransformInputs} from '../../kernel_names';
import {NamedAttrMap} from '../../kernel_registry';
import {Tensor2D, Tensor4D} from '../../tensor';
import {NamedTensorMap} from '../../tensor_types';
import {convertToTensor} from '../../tensor_util_env';
import {TensorLike} from '../../types';
import * as util from '../../util';
import {op} from '../operation';
/**
* Applies the given transform(s) to the image(s).
*
* @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.
* @param transforms Projective transform matrix/matrices. A tensor1d of length
* 8 or tensor of size N x 8. If one row of transforms is [a0, a1, a2, b0
* b1, b2, c0, c1], then it maps the output point (x, y) to a transformed
* input point (x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k),
* where k = c0 x + c1 y + 1. The transforms are inverted compared to the
* transform mapping input points to output points.
* @param interpolation Interpolation mode.
* Supported values: 'nearest', 'bilinear'. Default to 'nearest'.
* @param fillMode Points outside the boundaries of the input are filled
* according to the given mode, one of 'constant', 'reflect', 'wrap',
* 'nearest'. Default to 'constant'.
* 'reflect': (d c b a | a b c d | d c b a ) The input is extended by
* reflecting about the edge of the last pixel.
* 'constant': (k k k k | a b c d | k k k k) The input is extended by
* filling all values beyond the edge with the same constant value k.
* 'wrap': (a b c d | a b c d | a b c d) The input is extended by
* wrapping around to the opposite edge.
* 'nearest': (a a a a | a b c d | d d d d) The input is extended by
* the nearest pixel.
* @param fillValue A float represents the value to be filled outside the
* boundaries when fillMode is 'constant'.
* @param Output dimension after the transform, [height, width]. If undefined,
* output is the same size as input image.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function transform_(
image: Tensor4D|TensorLike, transforms: Tensor2D|TensorLike,
interpolation: 'nearest'|'bilinear' = 'nearest',
fillMode: 'constant'|'reflect'|'wrap'|'nearest' = 'constant', fillValue = 0,
outputShape?: [number, number]): Tensor4D {
const $image = convertToTensor(image, 'image', 'transform', 'float32');
const $transforms =
convertToTensor(transforms, 'transforms', 'transform', 'float32');
util.assert(
$image.rank === 4,
() => 'Error in transform: image must be rank 4,' +
`but got rank ${$image.rank}.`);
util.assert(
$transforms.rank === 2 &&
($transforms.shape[0] === $image.shape[0] ||
$transforms.shape[0] === 1) &&
$transforms.shape[1] === 8,
() => `Error in transform: Input transform should be batch x 8 or 1 x 8`);
util.assert(
outputShape == null || outputShape.length === 2,
() =>
'Error in transform: outputShape must be [height, width] or null, ' +
`but got ${outputShape}.`);
const inputs: TransformInputs = {image: $image, transforms: $transforms};
const attrs:
TransformAttrs = {interpolation, fillMode, fillValue, outputShape};
return ENGINE.runKernel(
Transform, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);
}
export const transform = op({transform_});
@@ -1,93 +0,0 @@
/**
* @license
* Copyright 2021 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.
* =============================================================================
*/
import {matMul} from './mat_mul';
import {ones} from './ones';
import {reshape} from './reshape';
import {Tensor} from '../tensor';
import {convertToTensor} from '../tensor_util_env';
import {TensorLike} from '../types';
import {sizeFromShape} from '../util_base';
/**
* Broadcasts parameters for evaluation on an N-D grid.
*
* Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`
* of N-D coordinate arrays for evaluating expressions on an N-D grid.
*
* Notes:
* `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.
* When the `indexing` argument is set to 'xy' (the default), the broadcasting
* instructions for the first two dimensions are swapped.
* Examples:
* Calling `const [X, Y] = meshgrid(x, y)` with the tensors
*
* ```javascript
* const x = [1, 2, 3];
* const y = [4, 5, 6];
* const [X, Y] = tf.meshgrid(x, y);
* // X = [[1, 2, 3],
* // [1, 2, 3],
* // [1, 2, 3]]
* // Y = [[4, 4, 4],
* // [5, 5, 5],
* // [6, 6, 6]]
* ```
*
* @param x Tensor with rank geq 1.
* @param y Tensor with rank geq 1.
* @param indexing
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
export function meshgrid<T extends Tensor>(
x?: T|TensorLike, y?: T|TensorLike, {indexing = 'xy'} = {}): T[] {
if (indexing !== 'xy' && indexing !== 'ij') {
throw new TypeError(
`${indexing} is not a valid third argument to meshgrid`);
}
if (x === undefined) {
return [];
}
let $x = convertToTensor(
x, 'x', 'meshgrid', x instanceof Tensor ? x.dtype : 'float32');
if (y === undefined) {
return [$x];
}
let $y = convertToTensor(
y, 'y', 'meshgrid', y instanceof Tensor ? y.dtype : 'float32');
const w = sizeFromShape($x.shape);
const h = sizeFromShape($y.shape);
if (indexing === 'xy') {
$x = reshape($x, [1, -1]) as T;
$y = reshape($y, [-1, 1]) as T;
return [
matMul(ones([h, 1], $x.dtype), $x),
matMul($y, ones([1, w], $y.dtype)),
];
}
$x = reshape($x, [-1, 1]) as T;
$y = reshape($y, [1, -1]) as T;
return [
matMul($x, ones([1, h], $x.dtype)),
matMul(ones([w, 1], $y.dtype), $y),
];
}
@@ -67,7 +67,6 @@ export {dilation2d} from './dilation2d';
export {div} from './div';
export {divNoNan} from './div_no_nan';
export {dot} from './dot';
export {einsum} from './einsum';
export {elu} from './elu';
export {equal} from './equal';
export {erf} from './erf';
@@ -106,7 +105,6 @@ export {maxPool3d} from './max_pool_3d';
export {maxPoolWithArgmax} from './max_pool_with_argmax';
export {maximum} from './maximum';
export {mean} from './mean';
export {meshgrid} from './meshgrid';
export {min} from './min';
export {minimum} from './minimum';
export {mirrorPad} from './mirror_pad';
@@ -248,8 +246,6 @@ import {nonMaxSuppressionPadded} from './image/non_max_suppression_padded';
import {nonMaxSuppressionPaddedAsync} from './image/non_max_suppression_padded_async';
import {resizeBilinear} from './image/resize_bilinear';
import {resizeNearestNeighbor} from './image/resize_nearest_neighbor';
import {threshold} from './image/threshold';
import {transform} from './image/transform';
const image = {
flipLeftRight,
resizeNearestNeighbor,
@@ -261,9 +257,7 @@ const image = {
nonMaxSuppressionWithScore,
nonMaxSuppressionWithScoreAsync,
nonMaxSuppressionPadded,
nonMaxSuppressionPaddedAsync,
threshold,
transform
nonMaxSuppressionPaddedAsync
};
// linalg namespace
@@ -298,12 +292,5 @@ const losses = {
softmaxCrossEntropy
};
import {sparseFillEmptyRows} from './sparse/sparse_fill_empty_rows';
import {sparseReshape} from './sparse/sparse_reshape';
const sparse = {
sparseFillEmptyRows,
sparseReshape
};
// Second level exports.
export {image, linalg, losses, spectral, fused, signal, sparse};
export {image, linalg, losses, spectral, fused, signal};
@@ -30,8 +30,6 @@ import {op} from './operation';
* @param randFunction A random number generator function which is called
* for each element in the output tensor.
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function rand_<R extends Rank>(
shape: ShapeMap[R], randFunction: () => number,
@@ -16,9 +16,11 @@
*/
import {Tensor, Tensor1D} from '../../tensor';
import {concat} from '../concat';
import {mul} from '../mul';
import {op} from '../operation';
import {enclosingPowerOfTwo} from '../signal_ops_util';
import {slice} from '../slice';
import {rfft} from '../spectral/rfft';
import {frame} from './frame';
@@ -49,6 +51,11 @@ function stft_(
}
const framedSignal = frame(signal, frameLength, frameStep);
const windowedSignal = mul(framedSignal, windowFn(frameLength));
return rfft(windowedSignal, fftLength);
const output: Tensor[] = [];
for (let i = 0; i < framedSignal.shape[0]; i++) {
output.push(
rfft(slice(windowedSignal, [i, 0], [1, frameLength]), fftLength));
}
return concat(output);
}
export const stft = op({stft_});
@@ -1,126 +0,0 @@
/**
* @license
* Copyright 2021 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.
* =============================================================================
*/
import {ENGINE} from '../../engine';
import {SparseFillEmptyRows, SparseFillEmptyRowsInputs} from '../../kernel_names';
import {Scalar, Tensor, Tensor1D, Tensor2D} from '../../tensor';
import {NamedTensorMap} from '../../tensor_types';
import {convertToTensor} from '../../tensor_util_env';
import {ScalarLike, TensorLike} from '../../types';
import {op} from '../operation';
/**
* The input SparseTensor is represented via the map of inputs {`indices`,
* `values`, `denseShape`}. The output SparseTensor has the same `denseShape`
* but with indices `outputIndices` and values `outputValues`. This op inserts a
* single entry for every row that doesn't have any values. The index is created
* as `[row, 0, ..., 0]` and the inserted value is `defaultValue`.
*
* For example, suppose `spInput` has shape [5, 6] and non-empty values:
* [0, 1]: a
* [0, 3]: b
* [2, 0]: c
* [3, 1]: d
*
* Rows 1 and 4 are empty, so the output will be of shape [5, 6] with values:
* [0, 1]: a
* [0, 3]: b
* [1, 0]: `defaultValue`
* [2, 0]: c
* [3, 1]: d
* [4, 0]: `defaultValue`
*
* The output SparseTensor will be in row-major order and will have the same
* shape as the input.
*
* This op also returns an indicator vector shaped [dense_shape[0]] such that
* emptyRowIndicator[i] = True iff row i was an empty row.
*
* And a reverse index map vector shaped [indices.shape[0]] that is used during
* backpropagation, reverseIndexMap[i] = outi s.t. indices[i, j] ==
* outputIndices[outi, j] for all j
*
* ```js
* const result = tf.sparse.sparseFillEmptyRows(
* [[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]],
* [0, 10, 13, 14, 32, 33], [5, 6], -1);
* console.log(result);
* result['outputIndices'].print(); // [[0, 0], [1, 0], [1, 3], [1, 4],
* // [2, 0], [3, 2], [3, 3], [4, 0]]
* result['outputValues'].print(); // [0, 10, 13, 14,-1, 32, 33, -1]
* result['emptyRowIndicator'].print(); // [0, 0, 1, 0, 1]
* result['reverseIndexMap'].print(); // [0, 1, 2, 3, 5, 6]
* ```
* @param indices: 2-D. the indices of the sparse tensor.
* @param values: 1-D. the values of the sparse tensor.
* @param denseShape: 1-D. the shape of the sparse tensor.
* @param defaultValue: 0-D. default value to insert into location [row, 0, ...,
* 0] for rows missing from the input sparse tensor.
* @return A map with the following properties:
* - outputIndices
* - outputValues: 1-D. the values of the filled sparse tensor.
* - emptyRowIndicator: 1-D. whether the dense row was missing in the input
* sparse tensor.
* - reverseIndexMap: 1-D. a map from the input indices to the output
* indices.
* @doc {heading: 'Operations', subheading: 'Sparse'}
*/
function sparseFillEmptyRows_(
indices: Tensor2D|TensorLike, values: Tensor1D|TensorLike,
denseShape: Tensor1D|TensorLike,
defaultValue: Scalar|ScalarLike): NamedTensorMap {
const $indices = convertToTensor(indices, 'indices', 'sparseFillEmptyRows');
const $values = convertToTensor(values, 'values', 'sparseFillEmptyRows');
const $denseShape =
convertToTensor(denseShape, 'denseShape', 'sparseFillEmptyRows');
const $defaultValue = convertToTensor(
defaultValue, 'defaultValue', 'sparseFillEmptyRows', $values.dtype);
if ($indices.rank !== 2) {
throw new Error(`Indices should be Tensor2D but received shape
${$indices.shape}`);
}
if ($values.rank !== 1) {
throw new Error(
`Values should be Tensor1D but received shape ${$values.shape}`);
}
if ($denseShape.rank !== 1) {
throw new Error(`Dense shape should be Tensor1D but received shape ${
$denseShape.shape}`);
}
if ($defaultValue.rank !== 0) {
throw new Error(`Default value should be a scalar but received shape ${
$defaultValue.shape}`);
}
const inputs: SparseFillEmptyRowsInputs = {
indices: $indices,
values: $values,
denseShape: $denseShape,
defaultValue: $defaultValue
};
const result: Tensor[] = ENGINE.runKernel(SparseFillEmptyRows, inputs as {});
return {
outputIndices: result[0],
outputValues: result[1],
emptyRowIndicator: result[2],
reverseIndexMap: result[3]
};
}
export const sparseFillEmptyRows = op({sparseFillEmptyRows_});
@@ -1,91 +0,0 @@
/**
* @license
* Copyright 2021 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.
* =============================================================================
*/
import {ENGINE} from '../../engine';
import {SparseReshape, SparseReshapeInputs} from '../../kernel_names';
import {Tensor, Tensor1D, Tensor2D} from '../../tensor';
import {NamedTensorMap} from '../../tensor_types';
import {convertToTensor} from '../../tensor_util_env';
import {TensorLike} from '../../types';
import {op} from '../operation';
/**
* This operation has the same semantics as reshape on the represented dense
* tensor. The `inputIndices` are recomputed based on the requested `newShape`.
* If one component of `newShape` is the special value -1, the size of that
* dimension is computed so that the total dense size remains constant. At most
* one component of `newShape` can be -1. The number of dense elements implied
* by `newShape` must be the same as the number of dense elements originally
* implied by `inputShape`. Reshaping does not affect the order of values in the
* SparseTensor. If the input tensor has rank R_in and N non-empty values, and
* `newShape` has length R_out, then `inputIndices` has shape [N, R_in],
* `inputShape` has length R_in, `outputIndices` has shape [N, R_out], and
* `outputShape` has length R_out.
*
* ```js
* const result = tf.sparse.sparseReshape(
* [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 2, 3]],
* [2, 3, 6], [9, -1]);
* console.log(result);
* result['outputIndices'].print(); //[[0, 0], [0, 1], [1, 2], [4, 2], [8, 1]]
* result['outputShape'].print(); // [9, 4]
* ```
* @param inputIndices: 2-D. N x R_in matrix with the indices of non-empty
* values in a SparseTensor.
* @param inputShape: 1-D. R_in Tensor1D with the input SparseTensor's dense
* shape.
* @param newShape: 1-D. R_out Tensor1D with the requested new dense shape.
* @return A map with the following properties:
* - outputIndices: 2-D. N x R_out matrix with the updated indices of
* non-empty values in the output SparseTensor.
* - outputShape: 1-D. R_out vector with the full dense shape of the output
* SparseTensor. This is the same as newShape but with any -1 dimensions
* filled in.
* @doc {heading: 'Operations', subheading: 'Sparse'}
*/
function sparseReshape_(
inputIndices: Tensor2D|TensorLike, inputShape: Tensor1D|TensorLike,
newShape: Tensor1D|TensorLike): NamedTensorMap {
const $inputIndices =
convertToTensor(inputIndices, 'inputIndices', 'sparseReshape');
const $inputShape =
convertToTensor(inputShape, 'inputShape', 'sparseReshape');
const $newShape = convertToTensor(newShape, 'newShape', 'sparseReshape');
if ($inputIndices.rank !== 2) {
throw new Error(`Input indices should be Tensor2D but received shape
${$inputIndices.shape}`);
}
if ($inputShape.rank !== 1) {
throw new Error(`Input shape should be Tensor1D but received shape ${
$inputShape.shape}`);
}
if ($newShape.rank !== 1) {
throw new Error(
`New shape should be Tensor1D but received shape ${$newShape.shape}`);
}
const inputs: SparseReshapeInputs = {
inputIndices: $inputIndices,
inputShape: $inputShape,
newShape: $newShape
};
const result: Tensor[] = ENGINE.runKernel(SparseReshape, inputs as {});
return {outputIndices: result[0], outputShape: result[1]};
}
export const sparseReshape = op({sparseReshape_});
@@ -21,6 +21,7 @@ import {Tensor} from '../tensor';
import {NamedTensorMap} from '../tensor_types';
import {convertToTensor} from '../tensor_util_env';
import {TensorLike} from '../types';
import {assert, assertShapesMatch} from '../util';
import {broadcastTo} from './broadcast_to';
import {assertAndGetBroadcastShape} from './broadcast_util';
@@ -56,19 +57,30 @@ function where_<T extends Tensor>(
const $condition = convertToTensor(condition, 'condition', 'where', 'bool');
// TODO: move this logic to forward function when the broadcastTo op is
// implemented in WASM.
// Find the broadcastable shape for $condition, $a, and $b.
const broadcastShape = assertAndGetBroadcastShape(
assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);
const $broadcastedCondition = broadcastTo($condition, broadcastShape);
// Find the broadcastable shape for $a and $b.
const broadcastShape = assertAndGetBroadcastShape($a.shape, $b.shape);
const $broadcastedA = broadcastTo($a, broadcastShape);
const $broadcastedB = broadcastTo($b, broadcastShape);
if ($condition.rank === 1) {
// If condition rank is 1, then the first dimension must match the size of
// condition.
assert(
$condition.shape[0] === $a.shape[0],
() => 'The first dimension of `a` must match the size of `condition`.');
}
if ($condition.rank !== 1) {
// A must have the same shape as condition.
assertShapesMatch(
$condition.shape, $broadcastedB.shape, 'Error in where: ');
}
const inputs: SelectInputs = {
condition: $broadcastedCondition,
condition: $condition,
t: $broadcastedA,
e: $broadcastedB
};
return ENGINE.runKernel(Select, inputs as {} as NamedTensorMap);
return ENGINE.runKernel(Select, inputs as unknown as NamedTensorMap);
}
export const where = op({where_});
@@ -1,150 +0,0 @@
/**
* @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.
* =============================================================================
*/
import {ENGINE} from '../engine';
import {dispose, tidy} from '../globals';
import {add} from '../ops/add';
import {div} from '../ops/div';
import {mul} from '../ops/mul';
import {sqrt} from '../ops/ops';
import {square} from '../ops/square';
import {zerosLike} from '../ops/zeros_like';
import {ConfigDict, registerClass, Serializable, SerializableConstructor} from '../serialization';
import {NamedTensor, NamedVariableMap} from '../tensor_types';
import {Optimizer, OptimizerVariable} from './optimizer';
/** @doclink Optimizer */
export class AdadeltaOptimizer extends Optimizer {
/** @nocollapse */
static className = 'Adadelta'; // Name matters for Python compatibility.
private accumulatedGrads: OptimizerVariable[] = [];
private accumulatedUpdates: OptimizerVariable[] = [];
constructor(
protected learningRate: number, protected rho: number,
protected epsilon: number = null) {
super();
if (epsilon == null) {
this.epsilon = ENGINE.backend.epsilon();
}
}
applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {
const variableNames = Array.isArray(variableGradients) ?
variableGradients.map(item => item.name) :
Object.keys(variableGradients);
variableNames.forEach((name, i) => {
const value = ENGINE.registeredVariables[name];
const trainable = false;
if (this.accumulatedGrads[i] == null) {
this.accumulatedGrads[i] = {
originalName: `${name}/accum_grad`,
variable: tidy(() => zerosLike(value).variable(trainable))
};
}
if (this.accumulatedUpdates[i] == null) {
this.accumulatedUpdates[i] = {
originalName: `${name}/accum_var`,
variable: tidy(() => zerosLike(value).variable(trainable))
};
}
const gradient = Array.isArray(variableGradients) ?
variableGradients[i].tensor :
variableGradients[name];
if (gradient == null) {
return;
}
const accumulatedGrad = this.accumulatedGrads[i].variable;
const accumulatedUpdate = this.accumulatedUpdates[i].variable;
tidy(() => {
const newAccumulatedGrad =
add(mul(accumulatedGrad, this.rho),
mul(square(gradient), 1 - this.rho));
const updates =
mul(div(sqrt(add(accumulatedUpdate, this.epsilon)),
sqrt(add(accumulatedGrad, this.epsilon))),
gradient);
const newAccumulatedUpdate =
add(mul(accumulatedUpdate, this.rho),
mul(square(updates), 1 - this.rho));
accumulatedGrad.assign(newAccumulatedGrad);
accumulatedUpdate.assign(newAccumulatedUpdate);
const newValue = add(mul(updates, -this.learningRate), value);
value.assign(newValue);
});
});
this.incrementIterations();
}
dispose(): void {
if (this.accumulatedUpdates != null) {
dispose(this.accumulatedGrads.map(v => v.variable));
dispose(this.accumulatedUpdates.map(v => v.variable));
}
}
async getWeights(): Promise<NamedTensor[]> {
// Order matters for Python compatibility.
const variables: OptimizerVariable[] =
[...this.accumulatedGrads, ...this.accumulatedUpdates];
return [await this.saveIterations()].concat(
variables.map(v => ({name: v.originalName, tensor: v.variable})));
}
async setWeights(weightValues: NamedTensor[]): Promise<void> {
weightValues = await this.extractIterations(weightValues);
const variableCount = weightValues.length / 2;
const trainable = false;
this.accumulatedGrads =
weightValues.slice(0, variableCount).map(v => ({
originalName: v.name,
variable: v.tensor.variable(
trainable)
}));
this.accumulatedUpdates =
weightValues.slice(variableCount, variableCount * 2)
.map(v => ({
originalName: v.name,
variable: v.tensor.variable(trainable)
}));
}
getConfig(): ConfigDict {
return {
'learningRate': this.learningRate,
'rho': this.rho,
'epsilon': this.epsilon
};
}
/** @nocollapse */
static fromConfig<T extends Serializable>(
cls: SerializableConstructor<T>, config: ConfigDict): T {
return new cls(config['learningRate'], config['rho'], config['epsilon']);
}
}
registerClass(AdadeltaOptimizer);
@@ -1,116 +0,0 @@
/**
* @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.
* =============================================================================
*/
import {ENGINE} from '../engine';
import {dispose, tidy} from '../globals';
import {add} from '../ops/add';
import {div} from '../ops/div';
import {fill} from '../ops/fill';
import {mul} from '../ops/mul';
import {sqrt} from '../ops/sqrt';
import {square} from '../ops/square';
import {ConfigDict, registerClass, Serializable, SerializableConstructor} from '../serialization';
import {NamedTensor, NamedVariableMap} from '../tensor_types';
import {Optimizer, OptimizerVariable} from './optimizer';
/** @doclink Optimizer */
export class AdagradOptimizer extends Optimizer {
/** @nocollapse */
static className = 'Adagrad'; // Note: Name matters for Python compatibility.
private accumulatedGrads: OptimizerVariable[] = [];
constructor(
protected learningRate: number, private initialAccumulatorValue = 0.1) {
super();
}
applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {
const variableNames = Array.isArray(variableGradients) ?
variableGradients.map(item => item.name) :
Object.keys(variableGradients);
variableNames.forEach((name, i) => {
const value = ENGINE.registeredVariables[name];
if (this.accumulatedGrads[i] == null) {
const trainable = false;
this.accumulatedGrads[i] = {
originalName: `${name}/accumulator`,
variable: tidy(
() => fill(value.shape, this.initialAccumulatorValue)
.variable(trainable))
};
}
const gradient = Array.isArray(variableGradients) ?
variableGradients[i].tensor :
variableGradients[name];
if (gradient == null) {
return;
}
const accumulatedGrad = this.accumulatedGrads[i].variable;
tidy(() => {
const newAccumulatedGrad = add(accumulatedGrad, square(gradient));
accumulatedGrad.assign(newAccumulatedGrad);
const newValue = add(
mul(div(gradient,
sqrt(add(newAccumulatedGrad, ENGINE.backend.epsilon()))),
-this.learningRate),
value);
value.assign(newValue);
});
});
this.incrementIterations();
}
dispose(): void {
if (this.accumulatedGrads != null) {
dispose(this.accumulatedGrads.map(v => v.variable));
}
}
async getWeights(): Promise<NamedTensor[]> {
// Order matters for Python compatibility.
return [await this.saveIterations()].concat(this.accumulatedGrads.map(
v => ({name: v.originalName, tensor: v.variable})));
}
async setWeights(weightValues: NamedTensor[]): Promise<void> {
weightValues = await this.extractIterations(weightValues);
const trainable = false;
this.accumulatedGrads = weightValues.map(
v => ({originalName: v.name, variable: v.tensor.variable(trainable)}));
}
getConfig(): ConfigDict {
return {
'learningRate': this.learningRate,
'initialAccumulatorValue': this.initialAccumulatorValue,
};
}
/** @nocollapse */
static fromConfig<T extends Serializable>(
cls: SerializableConstructor<T>, config: ConfigDict): T {
return new cls(config['learningRate'], config['initialAccumulatorValue']);
}
}
registerClass(AdagradOptimizer);
@@ -1,180 +0,0 @@
/**
* @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.
* =============================================================================
*/
import {ENGINE} from '../engine';
import {dispose, tidy} from '../globals';
import {add} from '../ops/add';
import {div} from '../ops/div';
import {mul} from '../ops/mul';
import {pow} from '../ops/pow';
import {scalar} from '../ops/scalar';
import {sqrt} from '../ops/sqrt';
import {square} from '../ops/square';
import {sub} from '../ops/sub';
import {zerosLike} from '../ops/zeros_like';
import {ConfigDict, registerClass, Serializable, SerializableConstructor} from '../serialization';
import {Variable} from '../tensor';
import {NamedTensor, NamedVariableMap} from '../tensor_types';
import {Optimizer, OptimizerVariable} from './optimizer';
export class AdamOptimizer extends Optimizer {
/** @nocollapse */
static className = 'Adam'; // Note: Name matters for Python compatibility.
private accBeta1: Variable;
private accBeta2: Variable;
private accumulatedFirstMoment: OptimizerVariable[] = [];
private accumulatedSecondMoment: OptimizerVariable[] = [];
constructor(
protected learningRate: number, protected beta1: number,
protected beta2: number, protected epsilon: number = null) {
super();
tidy(() => {
// accB* will be updated by batch.
this.accBeta1 = scalar(beta1).variable();
this.accBeta2 = scalar(beta2).variable();
});
if (epsilon == null) {
this.epsilon = ENGINE.backend.epsilon();
}
}
applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {
const varNames = Array.isArray(variableGradients) ?
variableGradients.map(v => v.name) :
Object.keys(variableGradients);
tidy(() => {
const oneMinusAccBeta1 = sub(1, this.accBeta1);
const oneMinusAccBeta2 = sub(1, this.accBeta2);
varNames.forEach((name, i) => {
const value = ENGINE.registeredVariables[name];
const trainable = false;
if (this.accumulatedFirstMoment[i] == null) {
this.accumulatedFirstMoment[i] = {
originalName: `${name}/m`,
variable: tidy(() => zerosLike(value).variable(trainable))
};
}
if (this.accumulatedSecondMoment[i] == null) {
this.accumulatedSecondMoment[i] = {
originalName: `${name}/v`,
variable: tidy(() => zerosLike(value).variable(trainable))
};
}
const gradient = Array.isArray(variableGradients) ?
variableGradients[i].tensor :
variableGradients[name];
if (gradient == null) {
return;
}
const firstMoment = this.accumulatedFirstMoment[i].variable;
const secondMoment = this.accumulatedSecondMoment[i].variable;
const newFirstMoment =
add(mul(firstMoment, this.beta1), mul(gradient, 1 - this.beta1));
const newSecondMoment =
add(mul(secondMoment, this.beta2),
mul(square(gradient), 1 - this.beta2));
const biasCorrectedFirstMoment = div(newFirstMoment, oneMinusAccBeta1);
const biasCorrectedSecondMoment =
div(newSecondMoment, oneMinusAccBeta2);
firstMoment.assign(newFirstMoment);
secondMoment.assign(newSecondMoment);
const newValue =
add(mul(div(biasCorrectedFirstMoment,
add(sqrt(biasCorrectedSecondMoment), this.epsilon)),
-this.learningRate),
value);
value.assign(newValue);
});
this.accBeta1.assign(mul(this.accBeta1, this.beta1));
this.accBeta2.assign(mul(this.accBeta2, this.beta2));
});
this.incrementIterations();
}
dispose(): void {
this.accBeta1.dispose();
this.accBeta2.dispose();
if (this.accumulatedFirstMoment != null) {
dispose(this.accumulatedFirstMoment.map(v => v.variable));
}
if (this.accumulatedSecondMoment != null) {
dispose(this.accumulatedSecondMoment.map(v => v.variable));
}
}
async getWeights(): Promise<NamedTensor[]> {
// Order matters for Python compatibility.
const variables: OptimizerVariable[] =
[...this.accumulatedFirstMoment, ...this.accumulatedSecondMoment];
return [await this.saveIterations()].concat(
variables.map(v => ({name: v.originalName, tensor: v.variable})));
}
async setWeights(weightValues: NamedTensor[]): Promise<void> {
weightValues = await this.extractIterations(weightValues);
tidy(() => {
this.accBeta1.assign(pow(this.beta1, this.iterations_ + 1));
this.accBeta2.assign(pow(this.beta2, this.iterations_ + 1));
});
const variableCount = weightValues.length / 2;
const trainable = false;
this.accumulatedFirstMoment =
weightValues.slice(0, variableCount).map(v => ({
originalName: v.name,
variable: v.tensor.variable(
trainable)
}));
this.accumulatedSecondMoment =
weightValues.slice(variableCount, variableCount * 2)
.map(v => ({
originalName: v.name,
variable: v.tensor.variable(trainable)
}));
}
getConfig(): ConfigDict {
return {
'learningRate': this.learningRate,
'beta1': this.beta1,
'beta2': this.beta2,
'epsilon': this.epsilon,
};
}
/** @nocollapse */
static fromConfig<T extends Serializable>(
cls: SerializableConstructor<T>, config: ConfigDict): T {
return new cls(
config['learningRate'], config['beta1'], config['beta2'],
config['epsilon']);
}
}
registerClass(AdamOptimizer);
@@ -1,158 +0,0 @@
/**
* @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.
* =============================================================================
*/
import {ENGINE} from '../engine';
import {dispose, tidy} from '../globals';
import {abs} from '../ops/abs';
import {add} from '../ops/add';
import {div} from '../ops/div';
import {maximum} from '../ops/maximum';
import {mul} from '../ops/mul';
import {scalar} from '../ops/scalar';
import {sub} from '../ops/sub';
import {zerosLike} from '../ops/zeros_like';
import {ConfigDict, registerClass, Serializable, SerializableConstructor} from '../serialization';
import {Variable} from '../tensor';
import {NamedTensor, NamedVariableMap} from '../tensor_types';
import {Optimizer, OptimizerVariable} from './optimizer';
export class AdamaxOptimizer extends Optimizer {
/** @nocollapse */
static className = 'Adamax'; // Note: Name matters for Python compatbility.
private accBeta1: Variable;
private iteration: Variable;
private accumulatedFirstMoment: OptimizerVariable[] = [];
private accumulatedWeightedInfNorm: OptimizerVariable[] = [];
constructor(
protected learningRate: number, protected beta1: number,
protected beta2: number, protected epsilon: number = null,
protected decay = 0.0) {
super();
tidy(() => {
this.iteration = scalar(0).variable();
this.accBeta1 = scalar(beta1).variable();
});
if (epsilon == null) {
this.epsilon = ENGINE.backend.epsilon();
}
}
applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {
const variableNames = Array.isArray(variableGradients) ?
variableGradients.map(item => item.name) :
Object.keys(variableGradients);
tidy(() => {
const oneMinusAccBeta1 = sub(1, this.accBeta1);
const lr =
div(-this.learningRate, add(mul(this.iteration, this.decay), 1));
variableNames.forEach((name, i) => {
const value = ENGINE.registeredVariables[name];
const trainable = false;
if (this.accumulatedFirstMoment[i] == null) {
this.accumulatedFirstMoment[i] = {
originalName: `${name}/m`,
variable: zerosLike(value).variable(trainable)
};
}
if (this.accumulatedWeightedInfNorm[i] == null) {
this.accumulatedWeightedInfNorm[i] = {
originalName: `${name}/v`,
variable: zerosLike(value).variable(trainable)
};
}
const gradient = Array.isArray(variableGradients) ?
variableGradients[i].tensor :
variableGradients[name];
if (gradient == null) {
return;
}
const firstMoment = this.accumulatedFirstMoment[i].variable;
const weightedInfNorm = this.accumulatedWeightedInfNorm[i].variable;
const newFirstMoment =
add(mul(firstMoment, this.beta1), mul(gradient, 1 - this.beta1));
const ut0 = mul(weightedInfNorm, this.beta2);
const ut1 = abs(gradient);
const newWeightedInfNorm = maximum(ut0, ut1);
firstMoment.assign(newFirstMoment);
weightedInfNorm.assign(newWeightedInfNorm);
const newValue =
add(mul(div(lr, oneMinusAccBeta1),
div(newFirstMoment, add(newWeightedInfNorm, this.epsilon))),
value);
value.assign(newValue);
});
this.iteration.assign(add(this.iteration, 1));
this.accBeta1.assign(mul(this.accBeta1, this.beta1));
});
this.incrementIterations();
}
dispose(): void {
this.accBeta1.dispose();
this.iteration.dispose();
if (this.accumulatedFirstMoment != null) {
dispose(this.accumulatedFirstMoment.map(v => v.variable));
}
if (this.accumulatedWeightedInfNorm != null) {
dispose(this.accumulatedWeightedInfNorm.map(v => v.variable));
}
}
async getWeights(): Promise<NamedTensor[]> {
throw new Error('getWeights() is not implemented for Adamax yet.');
}
async setWeights(weightValues: NamedTensor[]): Promise<void> {
throw new Error('setWeights() is not implemented for Adamax yet.');
}
getConfig(): ConfigDict {
return {
'learningRate': this.learningRate,
'beta1': this.beta1,
'beta2': this.beta2,
'epsilon': this.epsilon,
'decay': this.decay
};
}
/** @nocollapse */
static fromConfig<T extends Serializable>(
cls: SerializableConstructor<T>, config: ConfigDict): T {
return new cls(
config['learningRate'], config['beta1'], config['beta2'],
config['epsilon'], config['decay']);
}
}
registerClass(AdamaxOptimizer);
@@ -1,128 +0,0 @@
/**
* @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.
* =============================================================================
*/
import {ENGINE} from '../engine';
import {dispose, tidy} from '../globals';
import {add} from '../ops/add';
import {mul} from '../ops/mul';
import {scalar} from '../ops/scalar';
import {zerosLike} from '../ops/zeros_like';
import {ConfigDict, registerClass, Serializable, SerializableConstructor} from '../serialization';
import {Scalar, Tensor} from '../tensor';
import {NamedTensor, NamedVariableMap} from '../tensor_types';
import {OptimizerVariable} from './optimizer';
import {SGDOptimizer} from './sgd_optimizer';
/** @doclink Optimizer */
export class MomentumOptimizer extends SGDOptimizer {
/** @nocollapse */
static className = 'Momentum'; // Name matters for Python compatibility.
private m: Scalar;
private accumulations: OptimizerVariable[] = [];
constructor(
protected learningRate: number, private momentum: number,
private useNesterov = false) {
super(learningRate);
this.m = scalar(this.momentum);
}
applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {
const variableNames = Array.isArray(variableGradients) ?
variableGradients.map(item => item.name) :
Object.keys(variableGradients);
variableNames.forEach((name, i) => {
const value = ENGINE.registeredVariables[name];
if (this.accumulations[i] == null) {
const trainable = false;
this.accumulations[i] = {
originalName: `${name}/momentum`,
variable: tidy(() => zerosLike(value).variable(trainable))
};
}
const accumulation = this.accumulations[i].variable;
const gradient = Array.isArray(variableGradients) ?
variableGradients[i].tensor :
variableGradients[name];
if (gradient == null) {
return;
}
tidy(() => {
let newValue: Tensor;
const newAccumulation = add(mul(this.m, accumulation), gradient);
if (this.useNesterov) {
newValue = add(
mul(this.c, add(gradient, mul(newAccumulation, this.m))), value);
} else {
newValue = add(mul(this.c, newAccumulation), value);
}
accumulation.assign(newAccumulation);
value.assign(newValue);
});
});
this.incrementIterations();
}
dispose(): void {
this.m.dispose();
if (this.accumulations != null) {
dispose(this.accumulations.map(v => v.variable));
}
}
/**
* Sets the momentum of the optimizer.
*
* @param momentum
*/
setMomentum(momentum: number) {
this.momentum = momentum;
}
async getWeights(): Promise<NamedTensor[]> {
// Order matters for Python compatibility.
return [await this.saveIterations()].concat(this.accumulations.map(
v => ({name: v.originalName, tensor: v.variable})));
}
async setWeights(weightValues: NamedTensor[]): Promise<void> {
weightValues = await this.extractIterations(weightValues);
const trainable = false;
this.accumulations = weightValues.map(
v => ({originalName: v.name, variable: v.tensor.variable(trainable)}));
}
getConfig(): ConfigDict {
return {
'learningRate': this.learningRate,
'momentum': this.momentum,
'useNesterov': this.useNesterov
};
}
/** @nocollapse */
static fromConfig<T extends Serializable>(
cls: SerializableConstructor<T>, config: ConfigDict): T {
return new cls(
config['learningRate'], config['momentum'], config['useNesterov']);
}
}
registerClass(MomentumOptimizer);
@@ -1,173 +0,0 @@
/**
* @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.
* =============================================================================
*/
import {dispose} from '../globals';
import {variableGrads} from '../gradients';
import {scalar} from '../ops/ops';
import {Serializable} from '../serialization';
import {Scalar, Variable} from '../tensor';
import {NamedTensor, NamedTensorMap} from '../tensor_types';
/**
* A variable that belongs to an optimizer.
*
* The `originalName` field is required for keeping track of the canonical
* name of the variable, which is usually the name of the model weight that
* the variable is related to plus a suffix, e.g., 'dense1/kernel/momentum'.
* The name of the `Variable` object itself cannot be used directly due to
* possible deduplication: Every `Variable` must have a unique name but more
* than one optimizer objects of the same type may be created for the same model
* or the same `Variable`.
*/
export interface OptimizerVariable {
originalName: string;
variable: Variable;
}
/** @doc {heading: 'Training', subheading: 'Classes', namespace: 'train'} */
export abstract class Optimizer extends Serializable {
protected iterations_: number;
/**
* Executes `f()` and minimizes the scalar output of `f()` by computing
* gradients of y with respect to the list of trainable variables provided by
* `varList`. If no list is provided, it defaults to all trainable variables.
*
* @param f The function to execute and whose output to minimize.
* @param returnCost Whether to return the scalar cost value produced by
* executing `f()`.
* @param varList An optional list of variables to update. If specified, only
* the trainable variables in varList will be updated by minimize. Defaults to
* all trainable variables.
*
* @doc {heading: 'Training', subheading: 'Optimizers'}
*/
minimize(f: () => Scalar, returnCost = false, varList?: Variable[]): Scalar
|null {
const {value, grads} = this.computeGradients(f, varList);
if (varList != null) {
const gradArray: NamedTensor[] =
varList.map(v => ({name: v.name, tensor: grads[v.name]}));
this.applyGradients(gradArray);
} else {
this.applyGradients(grads);
}
// Dispose gradients.
dispose(grads);
if (returnCost) {
return value;
} else {
value.dispose();
return null;
}
}
/**
* The number of iterations that this optimizer instance has been invoked for.
*/
get iterations(): number {
if (this.iterations_ == null) {
this.iterations_ = 0;
}
return this.iterations_;
}
protected incrementIterations() {
this.iterations_ = this.iterations + 1;
}
/**
* Executes f() and computes the gradient of the scalar output of f() with
* respect to the list of trainable variables provided by `varList`. If no
* list is provided, it defaults to all trainable variables.
*
* @param f The function to execute and whose output to use for computing
* gradients with respect to variables.
* @param varList An optional list of variables to compute gradients with
* respect to. If specified, only the trainable variables in varList will have
* gradients computed with respect to. Defaults to all trainable variables.
*
* @doc {heading: 'Training', subheading: 'Optimizers'}
*/
computeGradients(f: () => Scalar, varList?: Variable[]):
{value: Scalar, grads: NamedTensorMap} {
return variableGrads(f, varList);
}
/**
* Updates variables by using the computed gradients.
*
* @param variableGradients A mapping of variable name to its gradient value.
*
* @doc {heading: 'Training', subheading: 'Optimizers'}
*/
abstract applyGradients(variableGradients: NamedTensorMap|
NamedTensor[]): void;
/**
* Dispose the variables (if any) owned by this optimizer instance.
*/
dispose(): void {
if (this.iterations_ != null) {
dispose(this.iterations_);
}
}
async saveIterations(): Promise<NamedTensor> {
if (this.iterations_ == null) {
this.iterations_ = 0;
}
return {
name: 'iter', // Named for Python compatibility.
// TODO(cais): Use 'int64' type when available.
tensor: scalar(this.iterations_, 'int32')
};
}
async getWeights(): Promise<NamedTensor[]> {
throw new Error('getWeights() is not implemented for this optimizer yet.');
}
async setWeights(weightValues: NamedTensor[]): Promise<void> {
throw new Error(
`setWeights() is not implemented for this optimizer class ` +
`${this.getClassName()}`);
}
/**
* Extract the first element of the weight values and set it
* as the iterations counter variable of this instance of optimizer.
*
* @param weightValues
* @returns Weight values with the first element consumed and excluded.
*/
protected async extractIterations(weightValues: NamedTensor[]):
Promise<NamedTensor[]> {
this.iterations_ = (await weightValues[0].tensor.data())[0];
return weightValues.slice(1);
}
}
Object.defineProperty(Optimizer, Symbol.hasInstance, {
value: (instance: Optimizer) => {
return instance.minimize != null && instance.computeGradients != null &&
instance.applyGradients != null;
}
});
@@ -1,189 +0,0 @@
/**
* @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.
* =============================================================================
*/
import {AdadeltaOptimizer} from './adadelta_optimizer';
import {AdagradOptimizer} from './adagrad_optimizer';
import {AdamOptimizer} from './adam_optimizer';
import {AdamaxOptimizer} from './adamax_optimizer';
import {MomentumOptimizer} from './momentum_optimizer';
import {RMSPropOptimizer} from './rmsprop_optimizer';
import {SGDOptimizer} from './sgd_optimizer';
export class OptimizerConstructors {
/**
* Constructs a `tf.SGDOptimizer` that uses stochastic gradient descent.
*
* ```js
* // Fit a quadratic function by learning the coefficients a, b, c.
* const xs = tf.tensor1d([0, 1, 2, 3]);
* const ys = tf.tensor1d([1.1, 5.9, 16.8, 33.9]);
*
* const a = tf.scalar(Math.random()).variable();
* const b = tf.scalar(Math.random()).variable();
* const c = tf.scalar(Math.random()).variable();
*
* // y = a * x^2 + b * x + c.
* const f = x => a.mul(x.square()).add(b.mul(x)).add(c);
* const loss = (pred, label) => pred.sub(label).square().mean();
*
* const learningRate = 0.01;
* const optimizer = tf.train.sgd(learningRate);
*
* // Train the model.
* for (let i = 0; i < 10; i++) {
* optimizer.minimize(() => loss(f(xs), ys));
* }
*
* // Make predictions.
* console.log(
* `a: ${a.dataSync()}, b: ${b.dataSync()}, c: ${c.dataSync()}`);
* const preds = f(xs).dataSync();
* preds.forEach((pred, i) => {
* console.log(`x: ${i}, pred: ${pred}`);
* });
* ```
*
* @param learningRate The learning rate to use for the SGD algorithm.
*
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static sgd(learningRate: number): SGDOptimizer {
return new SGDOptimizer(learningRate);
}
/**
* Constructs a `tf.MomentumOptimizer` that uses momentum gradient
* descent.
*
* See
* [http://proceedings.mlr.press/v28/sutskever13.pdf](
* http://proceedings.mlr.press/v28/sutskever13.pdf)
*
* @param learningRate The learning rate to use for the Momentum gradient
* descent algorithm.
* @param momentum The momentum to use for the momentum gradient descent
* algorithm.
*
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static momentum(learningRate: number, momentum: number, useNesterov = false):
MomentumOptimizer {
return new MomentumOptimizer(learningRate, momentum, useNesterov);
}
/**
* Constructs a `tf.RMSPropOptimizer` that uses RMSProp gradient
* descent. This implementation uses plain momentum and is not centered
* version of RMSProp.
*
* See
* [http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf](
* http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
*
* @param learningRate The learning rate to use for the RMSProp gradient
* descent algorithm.
* @param decay The discounting factor for the history/coming gradient.
* @param momentum The momentum to use for the RMSProp gradient descent
* algorithm.
* @param epsilon Small value to avoid zero denominator.
* @param centered If true, gradients are normalized by the estimated
* variance of the gradient.
*
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static rmsprop(
learningRate: number, decay = .9, momentum = 0.0, epsilon: number = null,
centered = false): RMSPropOptimizer {
return new RMSPropOptimizer(
learningRate, decay, momentum, epsilon, centered);
}
/**
* Constructs a `tf.AdamOptimizer` that uses the Adam algorithm.
* See [https://arxiv.org/abs/1412.6980](https://arxiv.org/abs/1412.6980)
*
* @param learningRate The learning rate to use for the Adam gradient
* descent algorithm.
* @param beta1 The exponential decay rate for the 1st moment estimates.
* @param beta2 The exponential decay rate for the 2nd moment estimates.
* @param epsilon A small constant for numerical stability.
*
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static adam(
learningRate = 0.001, beta1 = 0.9, beta2 = 0.999,
epsilon: number = null): AdamOptimizer {
return new AdamOptimizer(learningRate, beta1, beta2, epsilon);
}
/**
* Constructs a `tf.AdadeltaOptimizer` that uses the Adadelta algorithm.
* See [https://arxiv.org/abs/1212.5701](https://arxiv.org/abs/1212.5701)
*
* @param learningRate The learning rate to use for the Adadelta gradient
* descent algorithm.
* @param rho The learning rate decay over each update.
* @param epsilon A constant epsilon used to better condition the grad
* update.
*
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static adadelta(learningRate = .001, rho = .95, epsilon: number = null):
AdadeltaOptimizer {
return new AdadeltaOptimizer(learningRate, rho, epsilon);
}
/**
* Constructs a `tf.AdamaxOptimizer` that uses the Adamax algorithm.
* See [https://arxiv.org/abs/1412.6980](https://arxiv.org/abs/1412.6980)
*
* @param learningRate The learning rate to use for the Adamax gradient
* descent algorithm.
* @param beta1 The exponential decay rate for the 1st moment estimates.
* @param beta2 The exponential decay rate for the 2nd moment estimates.
* @param epsilon A small constant for numerical stability.
* @param decay The learning rate decay over each update.
*
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static adamax(
learningRate = 0.002, beta1 = 0.9, beta2 = 0.999, epsilon: number = null,
decay = 0.0): AdamaxOptimizer {
return new AdamaxOptimizer(learningRate, beta1, beta2, epsilon, decay);
}
/**
* Constructs a `tf.AdagradOptimizer` that uses the Adagrad algorithm.
* See
* [http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf](
* http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)
* or
* [http://ruder.io/optimizing-gradient-descent/index.html#adagrad](
* http://ruder.io/optimizing-gradient-descent/index.html#adagrad)
*
* @param learningRate The learning rate to use for the Adagrad gradient
* descent algorithm.
* @param initialAccumulatorValue Starting value for the accumulators, must be
* positive.
*
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/
static adagrad(learningRate: number, initialAccumulatorValue = 0.1):
AdagradOptimizer {
return new AdagradOptimizer(learningRate, initialAccumulatorValue);
}
}
@@ -1,210 +0,0 @@
/**
* @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.
* =============================================================================
*/
import {ENGINE} from '../engine';
import {dispose, tidy} from '../globals';
import {add} from '../ops/add';
import {div} from '../ops/div';
import {mul} from '../ops/mul';
import {sqrt} from '../ops/sqrt';
import {square} from '../ops/square';
import {sub} from '../ops/sub';
import {zerosLike} from '../ops/zeros_like';
import {ConfigDict, registerClass, Serializable, SerializableConstructor} from '../serialization';
import {NamedTensor, NamedTensorMap} from '../tensor_types';
import {Optimizer, OptimizerVariable} from './optimizer';
/** @doclink Optimizer */
export class RMSPropOptimizer extends Optimizer {
/** @nocollapse */
static className = 'RMSProp'; // Note: Name matters for Python compatibility.
private centered: boolean;
private accumulatedMeanSquares: OptimizerVariable[] = [];
private accumulatedMoments: OptimizerVariable[] = [];
private accumulatedMeanGrads: OptimizerVariable[] = [];
constructor(
protected learningRate: number, protected decay = 0.9,
protected momentum = 0.0, protected epsilon: number = null,
centered = false) {
super();
this.centered = centered;
if (epsilon == null) {
this.epsilon = ENGINE.backend.epsilon();
}
if (learningRate == null) {
throw new Error(`learningRate for RMSPropOptimizer must be defined.`);
}
}
applyGradients(variableGradients: NamedTensorMap|NamedTensor[]) {
const variableNames = Array.isArray(variableGradients) ?
variableGradients.map(item => item.name) :
Object.keys(variableGradients);
variableNames.forEach((name, i) => {
const value = ENGINE.registeredVariables[name];
const trainable = false;
if (this.accumulatedMeanSquares[i] == null) {
this.accumulatedMeanSquares[i] = {
originalName: `${name}/rms`,
variable: tidy(() => zerosLike(value).variable(trainable))
};
}
if (this.accumulatedMoments[i] == null) {
this.accumulatedMoments[i] = {
originalName: `${name}/momentum`,
variable: tidy(() => zerosLike(value).variable(trainable))
};
}
if (this.accumulatedMeanGrads[i] == null && this.centered) {
this.accumulatedMeanGrads[i] = {
originalName: `${name}/mg`,
variable: tidy(() => zerosLike(value).variable(trainable))
};
}
const gradient = Array.isArray(variableGradients) ?
variableGradients[i].tensor :
variableGradients[name];
if (gradient == null) {
return;
}
const accumulatedMeanSquare = this.accumulatedMeanSquares[i].variable;
const accumulatedMoments = this.accumulatedMoments[i].variable;
tidy(() => {
const newAccumulatedMeanSquare =
add(mul(accumulatedMeanSquare, this.decay),
mul(square(gradient), 1 - this.decay));
if (this.centered) {
const accumulatedMeanGrad = this.accumulatedMeanGrads[i].variable;
// Centered gradient
const newAccumulatedMeanGrad =
add(mul(accumulatedMeanGrad, this.decay),
mul(gradient, 1 - this.decay));
const gradContribution =
div(mul(gradient, this.learningRate),
sqrt(
sub(newAccumulatedMeanSquare,
add(square(newAccumulatedMeanGrad), this.epsilon))));
const newAccumulatedMoments =
add(mul(accumulatedMoments, this.momentum), gradContribution);
accumulatedMeanSquare.assign(newAccumulatedMeanSquare);
accumulatedMeanGrad.assign(newAccumulatedMeanGrad);
accumulatedMoments.assign(newAccumulatedMoments);
const newValue = sub(value, newAccumulatedMoments);
value.assign(newValue);
} else {
// Plain gradient
const newAccumulatedMeanSquare =
add(mul(accumulatedMeanSquare, this.decay),
mul(square(gradient), 1 - this.decay));
const newAccumulatedMoments =
add(mul(accumulatedMoments, this.momentum),
div(mul(gradient, this.learningRate),
sqrt(add(newAccumulatedMeanSquare, this.epsilon))));
accumulatedMeanSquare.assign(newAccumulatedMeanSquare);
accumulatedMoments.assign(newAccumulatedMoments);
const newValue = sub(value, newAccumulatedMoments);
value.assign(newValue);
}
});
});
this.incrementIterations();
}
dispose(): void {
if (this.accumulatedMeanSquares != null) {
dispose(this.accumulatedMeanSquares.map(v => v.variable));
}
if (this.accumulatedMeanGrads != null && this.centered) {
dispose(this.accumulatedMeanGrads.map(v => v.variable));
}
if (this.accumulatedMoments != null) {
dispose(this.accumulatedMoments.map(v => v.variable));
}
}
async getWeights(): Promise<NamedTensor[]> {
// Order matters for Python compatibility.
const variables: OptimizerVariable[] =
[...this.accumulatedMeanSquares, ...this.accumulatedMoments];
if (this.centered) {
variables.push(...this.accumulatedMeanGrads);
}
return [await this.saveIterations()].concat(
variables.map(v => ({name: v.originalName, tensor: v.variable})));
}
async setWeights(weightValues: NamedTensor[]): Promise<void> {
weightValues = await this.extractIterations(weightValues);
const variableCount =
this.centered ? weightValues.length / 3 : weightValues.length / 2;
const trainable = false;
this.accumulatedMeanSquares =
weightValues.slice(0, variableCount).map(v => ({
originalName: v.name,
variable: v.tensor.variable(
trainable)
}));
this.accumulatedMoments =
weightValues.slice(variableCount, variableCount * 2)
.map(v => ({
originalName: v.name,
variable: v.tensor.variable(trainable)
}));
if (this.centered) {
this.accumulatedMeanGrads =
weightValues.slice(variableCount * 2, variableCount * 3)
.map(v => ({
originalName: v.name,
variable: v.tensor.variable(trainable)
}));
}
}
getConfig(): ConfigDict {
return {
'learningRate': this.learningRate,
'decay': this.decay,
'momentum': this.momentum,
'epsilon': this.epsilon,
'centered': this.centered
};
}
/** @nocollapse */
static fromConfig<T extends Serializable>(
cls: SerializableConstructor<T>, config: ConfigDict): T {
return new cls(
config['learningRate'], config['decay'], config['momentum'],
config['epsilon'], config['centered']);
}
}
registerClass(RMSPropOptimizer);
@@ -1,96 +0,0 @@
/**
* @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.
* =============================================================================
*/
import {ENGINE} from '../engine';
import {keep, tidy} from '../globals';
import {add} from '../ops/add';
import {mul} from '../ops/mul';
import {scalar} from '../ops/scalar';
import {ConfigDict, registerClass, Serializable, SerializableConstructor} from '../serialization';
import {Scalar} from '../tensor';
import {NamedTensor, NamedTensorMap} from '../tensor_types';
import {Optimizer} from './optimizer';
/** @doclink Optimizer */
export class SGDOptimizer extends Optimizer {
/** @nocollapse */
static className = 'SGD'; // Note: Name matters for Python compatibility.
protected c: Scalar;
constructor(protected learningRate: number) {
super();
this.setLearningRate(learningRate);
}
applyGradients(variableGradients: NamedTensorMap|NamedTensor[]) {
const varNames = Array.isArray(variableGradients) ?
variableGradients.map(v => v.name) :
Object.keys(variableGradients);
varNames.forEach((name, i) => {
const gradient = Array.isArray(variableGradients) ?
variableGradients[i].tensor :
variableGradients[name];
if (gradient == null) {
return;
}
const value = ENGINE.registeredVariables[name];
tidy(() => {
const newValue = add(mul(this.c, gradient), value);
value.assign(newValue);
});
});
this.incrementIterations();
}
/**
* Sets the learning rate of the optimizer.
*/
setLearningRate(learningRate: number) {
this.learningRate = learningRate;
if (this.c != null) {
this.c.dispose();
}
this.c = keep(scalar(-learningRate));
}
dispose() {
this.c.dispose();
}
async getWeights(): Promise<NamedTensor[]> {
return [await this.saveIterations()];
}
async setWeights(weightValues: NamedTensor[]): Promise<void> {
weightValues = await this.extractIterations(weightValues);
if (weightValues.length !== 0) {
throw new Error('SGD optimizer does not have settable weights.');
}
}
getConfig(): ConfigDict {
return {'learningRate': this.learningRate};
}
/** @nocollapse */
static fromConfig<T extends Serializable>(
cls: SerializableConstructor<T>, config: ConfigDict): T {
return new cls(config['learningRate']);
}
}
registerClass(SGDOptimizer);
@@ -1,49 +0,0 @@
/**
* @license
* Copyright 2019 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.
* =============================================================================
*/
import {RequestDetails} from '../io/types';
/**
* At any given time a single platform is active and represents and
* implementation of this interface. In practice, a platform is an environment
* where TensorFlow.js can be executed, e.g. the browser or Node.js.
*/
export interface Platform {
/**
* Makes an HTTP request.
* @param path The URL path to make a request to
* @param init The request init. See init here:
* https://developer.mozilla.org/en-US/docs/Web/API/Request/Request
*/
fetch(path: string, requestInits?: RequestInit, options?: RequestDetails):
Promise<Response>;
/**
* Returns the current high-resolution time in milliseconds relative to an
* arbitrary time in the past. It works across different platforms (node.js,
* browsers).
*/
now(): number;
/**
* Encode the provided string into an array of bytes using the provided
* encoding.
*/
encode(text: string, encoding: string): Uint8Array;
/** Decode the provided bytes into a string using the provided encoding. */
decode(bytes: Uint8Array, encoding: string): string;
}
@@ -1,71 +0,0 @@
/**
* @license
* Copyright 2019 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.
* =============================================================================
*/
import '../flags';
import {env} from '../environment';
import {BrowserIndexedDB, BrowserIndexedDBManager} from '../io/indexed_db';
import {BrowserLocalStorage, BrowserLocalStorageManager} from '../io/local_storage';
import {ModelStoreManagerRegistry} from '../io/model_management';
import {Platform} from './platform';
export class PlatformBrowser implements Platform {
// According to the spec, the built-in encoder can do only UTF-8 encoding.
// https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder
private textEncoder: TextEncoder;
fetch(path: string, init?: RequestInit): Promise<Response> {
return fetch(path, init);
}
now(): number {
return performance.now();
}
encode(text: string, encoding: string): Uint8Array {
if (encoding !== 'utf-8' && encoding !== 'utf8') {
throw new Error(
`Browser's encoder only supports utf-8, but got ${encoding}`);
}
if (this.textEncoder == null) {
this.textEncoder = new TextEncoder();
}
return this.textEncoder.encode(text);
}
decode(bytes: Uint8Array, encoding: string): string {
return new TextDecoder(encoding).decode(bytes);
}
}
if (env().get('IS_BROWSER')) {
env().setPlatform('browser', new PlatformBrowser());
// Register LocalStorage IOHandler
try {
ModelStoreManagerRegistry.registerManager(
BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());
} catch (err) {
}
// Register IndexedDB IOHandler
try {
ModelStoreManagerRegistry.registerManager(
BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());
} catch (err) {
}
}
@@ -1,87 +0,0 @@
/**
* @license
* Copyright 2019 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.
* =============================================================================
*/
import {env} from '../environment';
import {Platform} from './platform';
// We are wrapping this within an object so it can be stubbed by Jasmine.
export const getNodeFetch = {
// tslint:disable-next-line:no-require-imports
importFetch: () => require('node-fetch')
};
type FetchFn = (url: string, init?: RequestInit) => Promise<Response>;
let systemFetch: FetchFn;
// These getters and setters are for testing so we don't export a mutable
// variable.
export function resetSystemFetch() {
systemFetch = null;
}
export function setSystemFetch(fetchFn: FetchFn) {
systemFetch = fetchFn;
}
export function getSystemFetch(): FetchFn {
return systemFetch;
}
export class PlatformNode implements Platform {
private textEncoder: TextEncoder;
// tslint:disable-next-line:no-any
util: any;
constructor() {
// tslint:disable-next-line:no-require-imports
this.util = require('util');
// According to the spec, the built-in encoder can do only UTF-8 encoding.
// https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder
this.textEncoder = new this.util.TextEncoder();
}
fetch(path: string, requestInits?: RequestInit): Promise<Response> {
if (env().global.fetch != null) {
return env().global.fetch(path, requestInits);
}
if (systemFetch == null) {
systemFetch = getNodeFetch.importFetch();
}
return systemFetch(path, requestInits);
}
now(): number {
const time = process.hrtime();
return time[0] * 1000 + time[1] / 1000000;
}
encode(text: string, encoding: string): Uint8Array {
if (encoding !== 'utf-8' && encoding !== 'utf8') {
throw new Error(
`Node built-in encoder only supports utf-8, but got ${encoding}`);
}
return this.textEncoder.encode(text);
}
decode(bytes: Uint8Array, encoding: string): string {
if (bytes.length === 0) {
return '';
}
return new this.util.TextDecoder(encoding).decode(bytes);
}
}
if (env().get('IS_NODE')) {
env().setPlatform('node', new PlatformNode());
}
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {abs} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
abs<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.abs = function<T extends Tensor>(this: T) {
this.throwIfDisposed();
return abs(this);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {acos} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
acos<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.acos = function<T extends Tensor>(this: T) {
this.throwIfDisposed();
return acos(this);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {acosh} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
acosh<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.acosh = function<T extends Tensor>(this: T) {
this.throwIfDisposed();
return acosh(this);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {add} from '../../ops/add';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
add<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.add = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return add(this, b);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {all} from '../../ops/all';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
all<T extends Tensor>(this: T, axis?: number|number[], keepDims?: boolean):
T;
}
}
getGlobalTensorClass().prototype.all = function<T extends Tensor>(
this: T, axis?: number|number[], keepDims?: boolean): T {
this.throwIfDisposed();
return all(this, axis, keepDims);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {any} from '../../ops/any';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
any<T extends Tensor>(this: T, axis?: number|number[], keepDims?: boolean):
T;
}
}
getGlobalTensorClass().prototype.any = function<T extends Tensor>(
this: T, axis?: number|number[], keepDims?: boolean): T {
this.throwIfDisposed();
return any(this, axis, keepDims);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {argMax} from '../../ops/arg_max';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
argMax<T extends Tensor>(axis?: number): T;
}
}
getGlobalTensorClass().prototype.argMax = function<T extends Tensor>(
axis?: number): T {
this.throwIfDisposed();
return argMax(this, axis);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {argMin} from '../../ops/arg_min';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
argMin<T extends Tensor>(axis?: number): T;
}
}
getGlobalTensorClass().prototype.argMin = function<T extends Tensor>(
axis: number): T {
this.throwIfDisposed();
return argMin(this, axis);
};
@@ -1,35 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {reshape} from '../../ops/reshape';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
as1D<T extends Tensor>(): Tensor1D;
}
}
/**
* Converts a `tf.Tensor` to a `tf.Tensor1D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as1D = function<T extends Tensor>(): T {
this.throwIfDisposed();
return reshape(this, [this.size]) as T;
};
@@ -1,39 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {reshape} from '../../ops/reshape';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
as2D<T extends Tensor>(rows: number, columns: number): Tensor2D;
}
}
/**
* Converts a `tf.Tensor` to a `tf.Tensor2D`.
*
* @param rows Number of rows in `tf.Tensor2D`.
* @param columns Number of columns in `tf.Tensor2D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as2D = function<T extends Tensor>(
rows: number, columns: number): T {
this.throwIfDisposed();
return reshape(this, [rows, columns]) as T;
};
@@ -1,41 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {reshape} from '../../ops/reshape';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
as3D<T extends Tensor>(rows: number, columns: number, depth: number):
Tensor3D;
}
}
/**
* Converts a `tf.Tensor` to a `tf.Tensor3D`.
*
* @param rows Number of rows in `tf.Tensor3D`.
* @param columns Number of columns in `tf.Tensor3D`.
* @param depth Depth of `tf.Tensor3D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as3D = function<T extends Tensor>(
rows: number, columns: number, depth: number): T {
this.throwIfDisposed();
return reshape(this, [rows, columns, depth]) as T;
};
@@ -1,42 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {reshape} from '../../ops/reshape';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
as4D<T extends Tensor>(
rows: number, columns: number, depth: number, depth2: number): Tensor4D;
}
}
/**
* Converts a `tf.Tensor` to a `tf.Tensor4D`.
*
* @param rows Number of rows in `tf.Tensor4D`.
* @param columns Number of columns in `tf.Tensor4D`.
* @param depth Depth of `tf.Tensor4D`.
* @param depth2 4th dimension of `tf.Tensor4D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as4D = function<T extends Tensor>(
rows: number, columns: number, depth: number, depth2: number): T {
this.throwIfDisposed();
return reshape(this, [rows, columns, depth, depth2]) as T;
};
@@ -1,46 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {reshape} from '../../ops/reshape';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
as5D<T extends Tensor>(
rows: number, columns: number, depth: number, depth2: number,
depth3: number): Tensor5D;
}
}
/**
* Converts a `tf.Tensor` to a `tf.Tensor5D`.
*
* @param rows Number of rows in `tf.Tensor5D`.
* @param columns Number of columns in `tf.Tensor5D`.
* @param depth Depth of `tf.Tensor5D`.
* @param depth2 4th dimension of `tf.Tensor5D`.
* @param depth3 5th dimension of 'tf.Tensor5D'
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as5D = function<T extends Tensor>(
rows: number, columns: number, depth: number, depth2: number,
depth3: number): T {
this.throwIfDisposed();
return reshape(this, [rows, columns, depth, depth2, depth3]) as T;
};
@@ -1,38 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {reshape} from '../../ops/reshape';
import {getGlobalTensorClass, Scalar, Tensor} from '../../tensor';
import {Rank} from '../../types';
import {assert} from '../../util';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
asScalar<T extends Tensor>(): Scalar;
}
}
/**
* Converts a size-1 `tf.Tensor` to a `tf.Scalar`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.asScalar = function<T extends Tensor>(this: T):
Scalar {
this.throwIfDisposed();
assert(this.size === 1, () => 'The array must have only 1 element.');
return reshape(this, []);
};
@@ -1,40 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {cast} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {DataType, Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
asType<T extends Tensor>(this: T, dtype: DataType): T;
}
}
/**
* Casts a `tf.Tensor` to a specified dtype.
*
* @param dtype Data-type to cast the tensor to.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.asType = function<T extends Tensor>(
this: T, dtype: DataType): T {
this.throwIfDisposed();
return cast<T>(this, dtype);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {asin} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
asin<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.asin = function<T extends Tensor>(this: T): T {
this.throwIfDisposed();
return asin(this);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {asinh} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
asinh<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.asinh = function<T extends Tensor>(this: T):
T {
this.throwIfDisposed();
return asinh(this);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {atan} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
atan<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.atan = function<T extends Tensor>(this: T): T {
this.throwIfDisposed();
return atan(this);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {atan2} from '../../ops/atan2';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
atan2<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.atan2 = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return atan2(this, b);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {atanh} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
atanh<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.atanh = function<T extends Tensor>(this: T):
T {
this.throwIfDisposed();
return atanh(this);
};
@@ -1,37 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {avgPool} from '../../ops/avg_pool';
import {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
avgPool<T extends Tensor3D|Tensor4D>(
filterSize: [number, number]|number, strides: [number, number]|number,
pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T;
}
}
getGlobalTensorClass().prototype.avgPool =
function<T extends Tensor3D|Tensor4D>(
this: T, filterSize: [number, number]|number,
strides: [number, number]|number, pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T {
this.throwIfDisposed();
return avgPool(this, filterSize, strides, pad, dimRoundingMode);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {batchToSpaceND} from '../../ops/batch_to_space_nd';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
batchToSpaceND<R extends Rank>(blockShape: number[], crops: number[][]):
Tensor<R>;
}
}
getGlobalTensorClass().prototype.batchToSpaceND = function<R extends Rank>(
blockShape: number[], crops: number[][]): Tensor<R> {
this.throwIfDisposed();
return batchToSpaceND(this, blockShape, crops);
};
@@ -1,40 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {batchNorm} from '../../ops/batchnorm';
import {getGlobalTensorClass, Tensor, Tensor1D} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
batchNorm<T extends Tensor>(
mean: Tensor<R>|Tensor1D|TensorLike,
variance: Tensor<R>|Tensor1D|TensorLike,
offset?: Tensor<R>|Tensor1D|TensorLike,
scale?: Tensor<R>|Tensor1D|TensorLike,
varianceEpsilon?: number): Tensor<R>;
}
}
getGlobalTensorClass().prototype.batchNorm = function<R extends Rank>(
mean: Tensor<R>|Tensor1D|TensorLike,
variance: Tensor<R>|Tensor1D|TensorLike,
offset?: Tensor<R>|Tensor1D|TensorLike,
scale?: Tensor<R>|Tensor1D|TensorLike,
varianceEpsilon?: number): Tensor<R> {
this.throwIfDisposed();
return batchNorm(this, mean, variance, offset, scale, varianceEpsilon);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {broadcastTo} from '../../ops/broadcast_to';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, ShapeMap} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
broadcastTo<R extends Rank>(shape: ShapeMap[R]): Tensor<R>;
}
}
getGlobalTensorClass().prototype.broadcastTo = function<R extends Rank>(
shape: ShapeMap[R]): Tensor<R> {
this.throwIfDisposed();
return broadcastTo(this, shape);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {cast} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {DataType, Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
cast<T extends Tensor>(dtype: DataType): T;
}
}
getGlobalTensorClass().prototype.cast = function<T extends Tensor>(
dtype: DataType): T {
this.throwIfDisposed();
return cast(this, dtype) as T;
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {ceil} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
ceil<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.ceil = function<T extends Tensor>(this: T): T {
this.throwIfDisposed();
return ceil(this);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {clipByValue} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
clipByValue<T extends Tensor>(min: number, max: number): Tensor;
}
}
getGlobalTensorClass().prototype.clipByValue = function<T extends Tensor>(
min: number, max: number): T {
this.throwIfDisposed();
return clipByValue(this, min, max) as T;
};
@@ -1,34 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {concat} from '../../ops/concat';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
concat<T extends Tensor>(tensors: T|Array<T|TensorLike>, axis?: number): T;
}
}
getGlobalTensorClass().prototype.concat = function<T extends Tensor>(
x: T|Array<T|TensorLike>, axis?: number): T {
this.throwIfDisposed();
if (x instanceof Tensor) {
x = [x];
}
return concat([this, ...x], axis) as T;
};
@@ -1,39 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {conv1d} from '../../ops/conv1d';
import {ExplicitPadding} from '../../ops/conv_util';
import {getGlobalTensorClass, Tensor2D, Tensor3D} from '../../tensor';
import {Rank, TensorLike3D} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
conv1d<T extends Tensor2D|Tensor3D>(
filter: Tensor3D|TensorLike3D, stride: number,
pad: 'valid'|'same'|number|ExplicitPadding, dataFormat?: 'NWC'|'NCW',
dilation?: number, dimRoundingMode?: 'floor'|'round'|'ceil'): T;
}
}
getGlobalTensorClass().prototype.conv1d = function<T extends Tensor2D|Tensor3D>(
filter: Tensor3D|TensorLike3D, stride: number,
pad: 'valid'|'same'|number|ExplicitPadding, dataFormat?: 'NWC'|'NCW',
dilation?: number, dimRoundingMode?: 'floor'|'round'|'ceil'): T {
this.throwIfDisposed();
return conv1d(
this, filter, stride, pad, dataFormat, dilation,
dimRoundingMode) as T;
};
@@ -1,40 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {conv2d} from '../../ops/conv2d';
import {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';
import {Rank, TensorLike4D} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
conv2d<T extends Tensor3D|Tensor4D>(
filter: Tensor4D|TensorLike4D, strides: [number, number]|number,
pad: 'valid'|'same'|number, dataFormat?: 'NHWC'|'NCHW',
dilations?: [number, number]|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T;
}
}
getGlobalTensorClass().prototype.conv2d = function<T extends Tensor3D|Tensor4D>(
filter: Tensor4D|TensorLike4D, strides: [number, number]|number,
pad: 'valid'|'same'|number, dataFormat?: 'NHWC'|'NCHW',
dilations?: [number, number]|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T {
this.throwIfDisposed();
return conv2d(
this, filter, strides, pad, dataFormat, dilations,
dimRoundingMode) as T;
};
@@ -1,40 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {conv2dTranspose} from '../../ops/conv2d_transpose';
import {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';
import {Rank, TensorLike4D} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
conv2dTranspose<T extends Tensor3D|Tensor4D>(
filter: Tensor4D|TensorLike4D,
outputShape: [number, number, number, number]|[number, number, number],
strides: [number, number]|number, pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T;
}
}
getGlobalTensorClass().prototype.conv2dTranspose =
function<T extends Tensor3D|Tensor4D>(
filter: Tensor4D|TensorLike4D,
outputShape: [number, number, number, number]|[number, number, number],
strides: [number, number]|number, pad: 'valid'|'same'|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T {
this.throwIfDisposed();
return conv2dTranspose(
this, filter, outputShape, strides, pad, dimRoundingMode) as T;
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {cos} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
cos<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.cos = function<T extends Tensor>(this: T): T {
this.throwIfDisposed();
return cos(this);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {cosh} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
cosh<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.cosh = function<T extends Tensor>(this: T): T {
this.throwIfDisposed();
return cosh(this);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {cumsum} from '../../ops/cumsum';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
cumsum<R extends Rank>(
axis?: number, exclusive?: boolean, reverse?: boolean): Tensor<R>;
}
}
getGlobalTensorClass().prototype.cumsum = function<R extends Rank>(
axis?: number, exclusive?: boolean, reverse?: boolean): Tensor<R> {
this.throwIfDisposed();
return cumsum(this, axis, exclusive, reverse);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {depthToSpace} from '../../ops/depth_to_space';
import {getGlobalTensorClass, Tensor4D} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
depthToSpace<T extends Tensor4D>(
blockSize: number, dataFormat: 'NHWC'|'NCHW'): T;
}
}
getGlobalTensorClass().prototype.depthToSpace = function<T extends Tensor4D>(
blockSize: number, dataFormat: 'NHWC'|'NCHW'): T {
this.throwIfDisposed();
return depthToSpace(this, blockSize, dataFormat) as T;
};
@@ -1,41 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {depthwiseConv2d} from '../../ops/depthwise_conv2d';
import {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';
import {Rank, TensorLike4D} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
depthwiseConv2d<T extends Tensor3D|Tensor4D>(
filter: Tensor4D|TensorLike4D, strides: [number, number]|number,
pad: 'valid'|'same'|number, dataFormat?: 'NHWC'|'NCHW',
dilations?: [number, number]|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T;
}
}
getGlobalTensorClass().prototype.depthwiseConv2d =
function<T extends Tensor3D|Tensor4D>(
filter: Tensor4D|TensorLike4D, strides: [number, number]|number,
pad: 'valid'|'same'|number, dataFormat?: 'NHWC'|'NCHW',
dilations?: [number, number]|number,
dimRoundingMode?: 'floor'|'round'|'ceil'): T {
this.throwIfDisposed();
return depthwiseConv2d(
this, filter, strides, pad, dataFormat, dilations,
dimRoundingMode) as T;
};
@@ -1,37 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {dilation2d} from '../../ops/dilation2d';
import {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';
import {Rank, TensorLike3D} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
dilation2d<T extends Tensor3D|Tensor4D>(
filter: Tensor3D|TensorLike3D, strides: [number, number]|number,
pad: 'valid'|'same', dilations?: [number, number]|number,
dataFormat?: 'NHWC'): T;
}
}
getGlobalTensorClass().prototype.dilation2d =
function<T extends Tensor3D|Tensor4D>(
filter: Tensor3D|TensorLike3D, strides: [number, number]|number,
pad: 'valid'|'same', dilations?: [number, number]|number,
dataFormat?: 'NHWC'): T {
this.throwIfDisposed();
return dilation2d(this, filter, strides, pad, dilations, dataFormat) as T;
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {div} from '../../ops/div';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
div<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.div = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return div(this, b);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {divNoNan} from '../../ops/div_no_nan';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
divNoNan<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.divNoNan = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return divNoNan(this, b);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {dot} from '../../ops/dot';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
dot<T extends Tensor>(b: Tensor|TensorLike): Tensor;
}
}
getGlobalTensorClass().prototype.dot = function<T extends Tensor>(
b: T|TensorLike): Tensor {
this.throwIfDisposed();
return dot(this, b);
};
@@ -1,30 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {elu} from '../../ops/elu';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
elu<T extends Tensor>(): T;
}
}
getGlobalTensorClass().prototype.elu = function<T extends Tensor>(this: T): T {
this.throwIfDisposed();
return elu(this);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {equal} from '../../ops/equal';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
equal<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.equal = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return equal(this, b);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {erf} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
erf<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.erf = function<T extends Tensor>(this: T): T {
this.throwIfDisposed();
return erf(this);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {exp} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
exp<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.exp = function<T extends Tensor>(this: T): T {
this.throwIfDisposed();
return exp(this);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {expandDims} from '../../ops/expand_dims';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
expandDims<T extends Tensor>(axis?: number): T;
}
}
getGlobalTensorClass().prototype.expandDims = function<T extends Tensor>(
axis?: number): T {
this.throwIfDisposed();
return expandDims(this, axis);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {expm1} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
expm1<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.expm1 = function<T extends Tensor>(this: T):
T {
this.throwIfDisposed();
return expm1(this);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {fft} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
fft<T extends Tensor>(this: Tensor): Tensor;
}
}
getGlobalTensorClass().prototype.fft = function<T extends Tensor>(this: Tensor):
T {
this.throwIfDisposed();
return fft(this) as T;
};
@@ -1,35 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {reshape} from '../../ops/reshape';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
flatten<T extends Tensor>(): Tensor1D;
}
}
/**
* Flatten a Tensor to a 1D array.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.flatten = function<T extends Tensor>(): T {
this.throwIfDisposed();
return reshape(this, [this.size]) as T;
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {floor} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
floor<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.floor = function<T extends Tensor>(this: T):
T {
this.throwIfDisposed();
return floor(this);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {floorDiv} from '../../ops/floorDiv';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
floorDiv<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.floorDiv = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return floorDiv(this, b);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {gather} from '../../ops/gather';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
gather<T extends Tensor>(
this: T, indices: Tensor|TensorLike, axis?: number): T;
}
}
getGlobalTensorClass().prototype.gather = function<T extends Tensor>(
this: T, indices: Tensor|TensorLike, axis?: number): T {
this.throwIfDisposed();
return gather(this, indices, axis);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {greater} from '../../ops/greater';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
greater<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.greater = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return greater(this, b);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {greaterEqual} from '../../ops/greater_equal';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
greaterEqual<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.greaterEqual = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return greaterEqual(this, b);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {ifft} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
ifft<T extends Tensor>(this: Tensor): Tensor;
}
}
getGlobalTensorClass().prototype.ifft = function<T extends Tensor>(
this: Tensor): T {
this.throwIfDisposed();
return ifft(this) as T;
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {irfft} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
irfft<T extends Tensor>(this: Tensor): Tensor;
}
}
getGlobalTensorClass().prototype.irfft = function<T extends Tensor>(
this: Tensor): T {
this.throwIfDisposed();
return irfft(this) as T;
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {isFinite} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
isFinite<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.isFinite = function<T extends Tensor>(this: T):
T {
this.throwIfDisposed();
return isFinite(this);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {isInf} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
isInf<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.isInf = function<T extends Tensor>(this: T):
T {
this.throwIfDisposed();
return isInf(this);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {isNaN} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
isNaN<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.isNaN = function<T extends Tensor>(this: T):
T {
this.throwIfDisposed();
return isNaN(this);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {leakyRelu} from '../../ops/leaky_relu';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
leakyRelu<T extends Tensor>(alpha: number): T;
}
}
getGlobalTensorClass().prototype.leakyRelu = function<T extends Tensor>(
this: T, alpha: number): T {
this.throwIfDisposed();
return leakyRelu(this, alpha);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {less} from '../../ops/less';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
less<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.less = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return less(this, b);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {lessEqual} from '../../ops/less_equal';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
lessEqual<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.lessEqual = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return lessEqual(this, b);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {localResponseNormalization} from '../../ops/local_response_normalization';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
localResponseNormalization<T extends Tensor>(
depthRadius?: number, bias?: number, alpha?: number, beta?: number): T;
}
}
getGlobalTensorClass().prototype.localResponseNormalization =
function<T extends Tensor>(
depthRadius?: number, bias?: number, alpha?: number, beta?: number): T {
this.throwIfDisposed();
return localResponseNormalization(this, depthRadius, bias, alpha, beta) as T;
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {log} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
log<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.log = function<T extends Tensor>(this: T): T {
this.throwIfDisposed();
return log(this);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {log1p} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
log1p<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.log1p = function<T extends Tensor>(this: T):
T {
this.throwIfDisposed();
return log1p(this);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {logSigmoid} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
logSigmoid<T extends Tensor>(this: T): T;
}
}
getGlobalTensorClass().prototype.logSigmoid = function<T extends Tensor>(
this: T): T {
this.throwIfDisposed();
return logSigmoid(this);
};
@@ -1,33 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
// TODO update import path once op is modularized.
import {logSoftmax} from '../../ops/ops';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
logSoftmax<T extends Tensor>(this: T, axis?: number): T;
}
}
getGlobalTensorClass().prototype.logSoftmax = function<T extends Tensor>(
this: T, axis?: number): T {
this.throwIfDisposed();
return logSoftmax(this, axis);
};
@@ -1,32 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {logSumExp} from '../../ops/log_sum_exp';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
logSumExp<T extends Tensor>(
this: T, axis?: number|number[], keepDims?: boolean): T;
}
}
getGlobalTensorClass().prototype.logSumExp = function<T extends Tensor>(
this: T, axis?: number|number[], keepDims?: boolean): T {
this.throwIfDisposed();
return logSumExp(this, axis, keepDims);
};
@@ -1,31 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {logicalAnd} from '../../ops/logical_and';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank, TensorLike} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
logicalAnd<T extends Tensor>(b: Tensor|TensorLike): T;
}
}
getGlobalTensorClass().prototype.logicalAnd = function<T extends Tensor>(
b: Tensor|TensorLike): T {
this.throwIfDisposed();
return logicalAnd(this, b);
};
@@ -1,30 +0,0 @@
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
import {logicalNot} from '../../ops/logical_not';
import {getGlobalTensorClass, Tensor} from '../../tensor';
import {Rank} from '../../types';
declare module '../../tensor' {
interface Tensor<R extends Rank = Rank> {
logicalNot<T extends Tensor>(): T;
}
}
getGlobalTensorClass().prototype.logicalNot = function<T extends Tensor>(): T {
this.throwIfDisposed();
return logicalNot(this) as T;
};
Loaded 100 of 215 files, more files were not shown because too many files have changed in this diff. Show more