### tf.backend Source: https://js.tensorflow.org/api/latest/index Gets the current backend. If no backends have been initialized, this will attempt to initialize the best backend. ```APIDOC ## tf.backend () ### Description Gets the current backend. If no backends have been initialized, this will attempt to initialize the best backend. Will throw an error if the highest priority backend has async initialization, in which case you should call 'await tf.ready()' before running other code. ### Method N/A (Backend function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript try { const currentBackend = tf.backend(); console.log(`Current backend: ${currentBackend.binding().name}`); } catch (e) { console.error('Backend initialization failed or is asynchronous.'); } ``` ### Response #### Success Response (N/A) - **KernelBackend** - An instance of the current backend. #### Response Example ```json // Example: An object representing the WebGL backend ``` ``` -------------------------------- ### tf.layers.convLstm2d Example - JavaScript Source: https://js.tensorflow.org/api/latest/index This example demonstrates how to create and apply a tf.layers.convLstm2d layer in TensorFlow.js. It initializes the layer with specified filters and kernel size, then applies it to a sample input tensor. ```javascript const filters = 3; const kernelSize = 3; const batchSize = 4; const sequenceLength = 2; const size = 5; const channels = 3; const inputShape = [batchSize, sequenceLength, size, size, channels]; const input = tf.ones(inputShape); const layer = tf.layers.convLstm2d({filters, kernelSize}); const output = layer.apply(input); ``` -------------------------------- ### List, Remove, and Move Models Source: https://js.tensorflow.org/api/latest/index This section covers listing, removing, and moving models using TensorFlow.js I/O functions. It includes examples for saving a model, listing available models, removing a model, and moving a model between storage mediums. ```APIDOC ## tf.io.listModels ### Description Lists all the models that have been saved to the browser's local storage or IndexedDB. ### Method `GET` ### Endpoint `/tfjs/io/listModels` ### Parameters None ### Response #### Success Response (200) - **Promise<{[url: string]: ModelArtifactsInfo]}>** - A promise that resolves to an object where keys are model URLs and values are model artifact information. #### Response Example ```json { "localstorage://demo/management/model1": { "modelTopology": {}, "dateSaved": "2023-01-01T12:00:00.000Z", " وقد-Saved": "2023-01-01T12:00:00.000Z" } } ``` ## tf.io.removeModel ### Description Removes a model specified by URL from a registered storage medium. ### Method `DELETE` ### Endpoint `/tfjs/io/removeModel` ### Parameters #### Query Parameters - **url** (string) - Required - A URL to a stored model, with a scheme prefix, e.g., 'localstorage://my-model-1', 'indexeddb://my/model/2'. ### Response #### Success Response (200) - **Promise** - A promise that resolves to the model artifacts information of the removed model. #### Response Example ```json { "modelTopology": {}, "dateSaved": "2023-01-01T12:00:00.000Z", " وقد-Saved": "2023-01-01T12:00:00.000Z" } ``` ## tf.io.moveModel ### Description Moves a model from one URL to another. This function supports moving within a storage medium or between different storage mediums. ### Method `POST` ### Endpoint `/tfjs/io/moveModel` ### Parameters #### Request Body - **sourceURL** (string) - Required - Source URL of the model to move. - **destURL** (string) - Required - Destination URL for the moved model. ### Request Example ```json { "sourceURL": "localstorage://demo/management/model1", "destURL": "indexeddb://demo/management/model1" } ``` ### Response #### Success Response (200) - **Promise** - A promise that resolves to the model artifacts information of the moved model. #### Response Example ```json { "modelTopology": {}, "dateSaved": "2023-01-01T12:00:00.000Z", " وقد-Saved": "2023-01-01T12:00:00.000Z" } ``` ``` -------------------------------- ### Wait for Backend Initialization with tf.ready Source: https://js.tensorflow.org/api/latest/index Returns a Promise that resolves when the currently selected or highest-priority backend has finished initializing. Use `await tf.ready()` before executing code that depends on backend initialization, especially for backends with asynchronous setup. ```javascript async function initializeAndRun() { await tf.ready(); console.log('Backend is ready.'); // Proceed with TensorFlow.js operations } initializeAndRun(); ``` -------------------------------- ### Mapping a Dataset Transformation in JavaScript Source: https://js.tensorflow.org/api/latest/index Maps this dataset through a 1-to-1 transform. This example squares each element in the dataset. ```javascript const a = tf.data.array([1, 2, 3]).map(x => x*x); await a.forEachAsync(e => console.log(e)); ``` -------------------------------- ### Compile and Evaluate a Sequential Model in JavaScript Source: https://js.tensorflow.org/api/latest/index This example shows how to create a simple sequential TensorFlow.js model, compile it with a specified optimizer and loss function, and then evaluate its performance on test data. The model.evaluate() method returns the loss value and metrics, which are then printed to the console. This is a standard workflow for assessing model accuracy. ```javascript const model = tf.sequential({ layers: [tf.layers.dense({units: 1, inputShape: [10]})] }); model.compile({optimizer: 'sgd', loss: 'meanSquaredError'}); const result = model.evaluate( tf.ones([8, 10]), tf.ones([8, 1]), {batchSize: 4}); result.print(); ``` -------------------------------- ### Create and Summarize a Multi-Input Model in JavaScript Source: https://js.tensorflow.org/api/latest/index This example demonstrates how to create a TensorFlow.js model with multiple inputs using tf.input and tf.model. It then calls the model.summary() method to print a text summary of the model's layers, including their shapes, parameters, and connectivity. This is useful for debugging and understanding model architecture. ```javascript const input1 = tf.input({shape: [10]}); const input2 = tf.input({shape: [20]}); const dense1 = tf.layers.dense({units: 4}).apply(input1); const dense2 = tf.layers.dense({units: 8}).apply(input2); const concat = tf.layers.concatenate().apply([dense1, dense2]); const output = tf.layers.dense({units: 3, activation: 'softmax'}).apply(concat); const model = tf.model({inputs: [input1, input2], outputs: output}); model.summary(); ``` -------------------------------- ### Create Tensor from WebGPU Buffer Data in JavaScript Source: https://js.tensorflow.org/api/latest/index Creates a tensor directly from WebGPU buffer data, enabling efficient GPU-to-GPU data transfer. This example shows how to create a GPU buffer from provided data, transfer it to a read-accessible buffer, and then use it to create a TensorFlow.js tensor. It highlights the `zeroCopy` option for potential performance gains, explaining its implications for buffer management. ```javascript // Pass a `WebGPUData` object and specify a shape yourself. // This makes it possible for TF.js applications to avoid GPU / CPU sync. // For example, if your application includes a preprocessing step on the GPU, // you could upload the GPU output directly to TF.js, rather than first // downloading the values. Unlike WebGL, this optionally supports zero copy // by WebGPUData.zeroCopy. When zeroCopy is false or undefined(default), this // passing GPUBuffer can be destroyed after tensor is created. When zeroCopy // is true, this GPUBuffer is bound directly by the tensor, so do not destroy // this GPUBuffer until all access is done. // Example for WebGPU: function createGPUBufferFromData(device, data, dtype) { const bytesPerElement = 4; const sizeInBytes = data.length * bytesPerElement; const gpuWriteBuffer = device.createBuffer({ mappedAtCreation: true, size: sizeInBytes, usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC }); const arrayBuffer = gpuWriteBuffer.getMappedRange(); if (dtype === 'float32') { new Float32Array(arrayBuffer).set(data); } else if (dtype === 'int32') { new Int32Array(arrayBuffer).set(data); } else { throw new Error( `Creating tensor from GPUBuffer only supports` + `'float32'|'int32' dtype, while the dtype is ${dtype}.`); } gpuWriteBuffer.unmap(); const gpuReadBuffer = device.createBuffer({ mappedAtCreation: false, size: sizeInBytes, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC }); const copyEncoder = device.createCommandEncoder(); copyEncoder.copyBufferToBuffer( gpuWriteBuffer, 0, gpuReadBuffer, 0, sizeInBytes); const copyCommands = copyEncoder.finish(); device.queue.submit([copyCommands]); gpuWriteBuffer.destroy(); return gpuReadBuffer; } const savedBackend = tf.getBackend(); await tf.setBackend('webgpu').catch( () => {throw new Error( // The rest of the code for WebGPU tensor creation would follow here, // including getting the WebGPU device and calling tf.tensor with // WebGPUData. }); ``` -------------------------------- ### Get TensorFlow.js Environment Source: https://js.tensorflow.org/api/latest/index Returns the current TensorFlow.js environment, which is a global singleton. The environment object provides access to evaluated feature values and the active platform. ```javascript const env = tf.env (); ``` -------------------------------- ### Get TensorFlow.js Engine Source: https://js.tensorflow.org/api/latest/index Retrieves the global engine instance responsible for managing tensors and backends within TensorFlow.js. This engine is a singleton. ```javascript const engine = tf.engine (); ``` -------------------------------- ### Send Model to an HTTP Server Source: https://js.tensorflow.org/api/latest/index This example illustrates how to send a model's topology and weights to a remote HTTP server using the 'http://' URL shortcut. This requires a server-side implementation to handle the incoming model artifacts, suitable for centralized model management. ```javascript const model = tf.sequential( {layers: [tf.layers.dense({units: 1, inputShape: [3]})}]}); const saveResults = await model.save('http://my-server/model/upload'); ``` -------------------------------- ### Construct RNN Layer with Stacked GRUCells - JavaScript Source: https://js.tensorflow.org/api/latest/index Shows how to construct an `RNN` layer using a list of `GRUCell` instances, forming a stacked RNN cell. This example creates an input with 10 time steps and a 20-dimensional vector at each step, and the output shape reflects the sequence length and the units of the last `GRUCell` when `returnSequences` is true. ```javascript const cells = [ tf.layers.gruCell({units: 4}), tf.layers.gruCell({units: 8}), ]; const rnn = tf.layers.rnn({cell: cells, returnSequences: true}); // Create an input with 10 time steps and a length-20 vector at each step. const input = tf.input({shape: [10, 20]}); const output = rnn.apply(input); console.log(JSON.stringify(output.shape)); // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the // same as the sequence length of `input`, due to `returnSequences`: `true`; // 3rd dimension is the last `gruCell`'s number of units. ``` -------------------------------- ### Batching a Dataset of Numbers in JavaScript Source: https://js.tensorflow.org/api/latest/index Groups elements of a dataset into batches. This example demonstrates batching a dataset of numbers. It assumes each incoming element has the same structure. Primitives are grouped into a 1-D Tensor. ```javascript const a = tf.data.array([1, 2, 3, 4, 5, 6, 7, 8]).batch(4); await a.forEachAsync(e => e.print()); ``` -------------------------------- ### Batching a Dataset of Objects in JavaScript Source: https://js.tensorflow.org/api/latest/index Groups elements of a dataset into batches. This example demonstrates batching a dataset where elements are objects. For each key, the resulting Dataset provides a batched element collecting all incoming values for that key. ```javascript const c = tf.data.array([{a: 1, b: 11}, {a: 2, b: 12}, {a: 3, b: 13}, {a: 4, b: 14}, {a: 5, b: 15}, {a: 6, b: 16}, {a: 7, b: 17}, {a: 8, b: 18}]).batch(4); await c.forEachAsync(e => { console.log('{'); for(var key in e) { console.log(key+':'); e[key].print(); } console.log('}'); }) ``` -------------------------------- ### Create Tensor from Pixels Asynchronously (Browser JavaScript) Source: https://js.tensorflow.org/api/latest/index Asynchronously creates a `tf.Tensor` from pixel data, similar to `tf.browser.fromPixels`. This API checks for a `WRAP_TO_IMAGEBITMAP` flag and may wrap the input to `ImageBitmap` for efficiency. The example shows async creation and printing of a tensor from `ImageData`. ```javascript tf.browser.fromPixelsAsync (pixels, numChannels?) function Source Creates a tf.Tensor from an image in async way. ``` 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(); ``` EditRun * webgpu * webgl * wasm * cpu 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. Parameters: * pixels (PixelData|ImageData|HTMLImageElement|HTMLCanvasElement| HTMLVideoElement|ImageBitmap) 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}` * numChannels (number) 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). Optional Returns: Promise ``` -------------------------------- ### Stacked LSTM Cells with RNN Layer - TensorFlow.js Source: https://js.tensorflow.org/api/latest/index Illustrates how to construct an RNN layer using multiple LSTMCell instances. This example demonstrates stacking LSTM cells to create a more complex recurrent network and processing sequential data. The output shape is explained in the context of stacked cells and the returnSequences parameter. ```javascript const cells = [ tf.layers.lstmCell({units: 4}), tf.layers.lstmCell({units: 8}), ]; const rnn = tf.layers.rnn({cell: cells, returnSequences: true}); // Create an input with 10 time steps and a length-20 vector at each step. const input = tf.input({shape: [10, 20]}); const output = rnn.apply(input); console.log(JSON.stringify(output.shape)); // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the // same as the sequence length of `input`, due to `returnSequences`: `true`; // 3rd dimension is the last `lstmCell`'s number of units. ``` -------------------------------- ### Handling Input Shape and Batch Size for RNN Layers in TensorFlow.js Source: https://js.tensorflow.org/api/latest/index This example demonstrates how to specify input dimensions and batch sizes for RNN layers in TensorFlow.js. It covers `inputDim`, `inputLength`, `inputShape`, `batchInputShape`, and `batchSize` parameters, which are crucial for defining the expected shape of input data, especially for the first layer in a model. ```javascript const layer1 = tf.layers.simpleRNN({ units: 32, inputDim: 10, inputLength: 5 }); const layer2 = tf.layers.simpleRNN({ units: 32, inputShape: [5, 10] // [timesteps, inputDim] }); const layer3 = tf.layers.simpleRNN({ units: 32, batchInputShape: [64, 5, 10] // [batchSize, timesteps, inputDim] }); const layer4 = tf.layers.simpleRNN({ units: 32, batchSize: 64, inputShape: [5, 10] }); ``` -------------------------------- ### Get Current Backend with tf.backend Source: https://js.tensorflow.org/api/latest/index Retrieves the currently active backend for TensorFlow.js. If no backend is initialized, it attempts to initialize the best available one. This function may throw an error if the chosen backend requires asynchronous initialization. ```javascript // Assuming tf.ready() has been awaited if necessary const currentBackend = tf.backend(); console.log(currentBackend); ``` -------------------------------- ### Add Layers to a Sequential Model in JavaScript Source: https://js.tensorflow.org/api/latest/index Illustrates how to build a multi-layer sequential model by progressively adding dense layers with specified units, input shapes, and activation functions. The example shows adding three dense layers and then performing prediction on random input data. ```javascript const model = tf.sequential(); model.add(tf.layers.dense({units: 8, inputShape: [1]})); model.add(tf.layers.dense({units: 4, activation: 'relu6'})); model.add(tf.layers.dense({units: 1, activation: 'relu6'})); // Note that the untrained model is random at this point. model.predict(tf.randomNormal([10, 1])).print(); ``` -------------------------------- ### tf.layers.gru Example: Applying a GRU layer to sequential input Source: https://js.tensorflow.org/api/latest/index This JavaScript code snippet demonstrates how to create and apply a GRU layer using TensorFlow.js. It defines a GRU layer with 8 units and configures it to return sequences. An input tensor with a shape of [10, 20] is then created, and the GRU layer is applied to it. The output shape is logged to the console, showing the result of processing sequential data. ```javascript const rnn = tf.layers.gru({units: 8, returnSequences: true}); // Create an input with 10 time steps. const input = tf.input({shape: [10, 20]}); const output = rnn.apply(input); console.log(JSON.stringify(output.shape)); // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the // same as the sequence length of `input`, due to `returnSequences`: `true`; // 3rd dimension is the `GRUCell`'s number of units. ``` -------------------------------- ### Construct RNN Layer with Stacked SimpleRNNCells in TensorFlow.js Source: https://js.tensorflow.org/api/latest/index Illustrates the construction of an RNN layer using stacked SimpleRNNCells in TensorFlow.js. This example shows how to combine multiple cells and configure the RNN layer to return sequences. The output shape reflects the batch size, sequence length, and the units of the last cell. ```javascript const cells = [ tf.layers.simpleRNNCell({units: 4}), tf.layers.simpleRNNCell({units: 8}), ]; const rnn = tf.layers.rnn({cell: cells, returnSequences: true}); // Create an input with 10 time steps and a length-20 vector at each step. const input = tf.input({shape: [10, 20]}); const output = rnn.apply(input); console.log(JSON.stringify(output.shape)); // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the // same as the sequence length of `input`, due to `returnSequences`: `true`; ``` -------------------------------- ### Get Value from tf.TensorBuffer (JavaScript) Source: https://js.tensorflow.org/api/latest/index The `get()` method of a tf.TensorBuffer retrieves the value stored at a given location within the buffer. ```javascript const value = buffer.get(loc1, loc2, ...); ``` -------------------------------- ### Save Model as Browser Downloadable Files Source: https://js.tensorflow.org/api/latest/index This snippet demonstrates saving a model's topology and weights as two separate files (`.json` for topology and `.weights.bin` for weights) that are automatically downloaded by the browser using the 'downloads://' URL shortcut. This is convenient for manual distribution or backup. ```javascript const model = tf.sequential( {layers: [tf.layers.dense({units: 1, inputShape: [3]})}]}); const saveResults = await model.save('downloads://my-model-1'); ``` -------------------------------- ### tf.ready Source: https://js.tensorflow.org/api/latest/index Returns a promise that resolves when the currently selected backend has initialized. ```APIDOC ## tf.ready () ### Description Returns a promise that resolves when the currently selected backend (or the highest priority one) has initialized. Await this promise when you are using a backend that has async initialization. ### Method N/A (Backend function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript async function runWithBackend() { await tf.ready(); console.log('Backend is ready.'); // Perform TensorFlow.js operations } runWithBackend(); ``` ### Response #### Success Response (N/A) - **Promise** - A promise that resolves when the backend is initialized. #### Response Example ```json // No direct JSON response, the promise resolves. ``` ``` -------------------------------- ### Create and Train Sequential Model in JavaScript Source: https://js.tensorflow.org/api/latest/index Demonstrates how to create a sequential model, add a dense layer for linear regression, compile it with a loss function and optimizer, train it with synthetic data, and perform inference. This involves using `tf.sequential()`, `model.add()`, `model.compile()`, `tf.tensor2d()`, `model.fit()`, and `model.predict()`. ```javascript // Define a model for linear regression. const model = tf.sequential(); model.add(tf.layers.dense({units: 1, inputShape: [1]})); // Prepare the model for training: Specify the loss and the optimizer. model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); // Generate some synthetic data for training. const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]); const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]); // Train the model using the data then do inference on a data point the // model hasn't seen: await model.fit(xs, ys); model.predict(tf.tensor2d([5], [1, 1])).print(); ``` -------------------------------- ### Instantiate and Use ConvLSTM2DCell - JavaScript Source: https://js.tensorflow.org/api/latest/index This snippet demonstrates how to instantiate a ConvLSTM2DCell, build it with an input shape, and then call it with sample input data and initial states. It highlights the cell's input and output structure for a single time step. ```javascript const filters = 3; const kernelSize = 3; const sequenceLength = 1; const size = 5; const channels = 3; const inputShape = [sequenceLength, size, size, channels]; const input = tf.ones(inputShape); const cell = tf.layers.convLstm2dCell({ filters, kernelSize }); cell.build(input.shape); const outputSize = size - kernelSize + 1; const outShape = [sequenceLength, outputSize, outputSize, filters]; const initialH = tf.zeros(outShape); const initialC = tf.zeros(outShape); const [o, h, c] = cell.call([input, initialH, initialC], {}); ``` -------------------------------- ### Concatenating Datasets in JavaScript Source: https://js.tensorflow.org/api/latest/index Concatenates this `Dataset` with another. This example shows how to combine two datasets sequentially. ```javascript const a = tf.data.array([1, 2, 3]); const b = tf.data.array([4, 5, 6]); const c = a.concatenate(b); await c.forEachAsync(e => console.log(e)); ``` -------------------------------- ### Filtering a Dataset in JavaScript Source: https://js.tensorflow.org/api/latest/index Filters this dataset according to a predicate function. This example filters a dataset to keep only even numbers. ```javascript const a = tf.data.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) .filter(x => x%2 === 0); await a.forEachAsync(e => console.log(e)); ``` -------------------------------- ### Create and Use InputLayer in TensorFlow.js Source: https://js.tensorflow.org/api/latest/index Demonstrates how to create an `InputLayer` in TensorFlow.js, which serves as an entry point for models. This is particularly useful when constructing sequential models from existing layers or subsets of other models, ensuring compatibility by explicitly defining the input shape. ```javascript const model1 = tf.sequential(); model1.add(tf.layers.dense({inputShape: [4], units: 3, activation: 'relu'})); model1.add(tf.layers.dense({units: 1, activation: 'sigmoid'})); model1.summary(); model1.predict(tf.zeros([1, 4])).print(); const model2 = tf.sequential(); // Use an inputShape that matches the input shape of `model1`'s second // layer. model2.add(tf.layers.inputLayer({inputShape: [3]})); model2.add(model1.layers[1]); model2.summary(); model2.predict(tf.zeros([1, 3])).print(); ``` -------------------------------- ### Get Current Backend Name with tf.getBackend Source: https://js.tensorflow.org/api/latest/index Returns the name of the currently active backend (e.g., 'cpu', 'webgl'). The backend is responsible for tensor creation and operation execution. ```javascript const backendName = tf.getBackend(); console.log(backendName); ``` -------------------------------- ### Batching a Dataset of Arrays in JavaScript Source: https://js.tensorflow.org/api/latest/index Groups elements of a dataset into batches. This example shows batching a dataset where elements are arrays. Incoming arrays are converted to Tensors and then batched. ```javascript const b = tf.data.array([[1], [2], [3], [4], [5], [6], [7], [8]]).batch(4); await b.forEachAsync(e => e.print()); ``` -------------------------------- ### Build Model with Symbolic Tensors Source: https://js.tensorflow.org/api/latest/index Illustrates building a model using `tf.layers.Layer` with `tf.SymbolicTensor` inputs. This is typically used for defining the structure of non-Sequential models. It shows how to obtain a `SymbolicTensor` using `tf.input`, apply layers sequentially to it, and infer output shapes, finally constructing a `tf.model`. ```javascript const flattenLayer = tf.layers.flatten(); const denseLayer = tf.layers.dense({units: 1}); // Use tf.layers.input() to obtain a SymbolicTensor as input to apply(). const input = tf.input({shape: [2, 2]}); const output1 = flattenLayer.apply(input); // output1.shape is [null, 4]. The first dimension is the undetermined // batch size. The second dimension comes from flattening the [2, 2] // shape. console.log(JSON.stringify(output1.shape)); // The output SymbolicTensor of the flatten layer can be used to call // the apply() of the dense layer: const output2 = denseLayer.apply(output1); // output2.shape is [null, 1]. The first dimension is the undetermined // batch size. The second dimension matches the number of units of the // dense layer. console.log(JSON.stringify(output2.shape)); // The input and output can be used to construct a model that consists // of the flatten and dense layers. const model = tf.model({inputs: input, outputs: output2}); ``` -------------------------------- ### Mirror Pad Tensor in JavaScript ('reflect') Source: https://js.tensorflow.org/api/latest/index Pads a tensor using mirror padding. This example uses the 'reflect' mode, where values are reflected across the edges of the tensor. ```javascript const x = tf.range(0, 9).reshape([1, 1, 3, 3]); x.mirrorPad([[0, 0], [0, 0], [2, 2], [2, 2]], 'reflect').print(); ``` -------------------------------- ### Export Model to Browser Downloads with TensorFlow.js Source: https://js.tensorflow.org/api/latest/index This snippet demonstrates how to export a TensorFlow.js model and trigger a download in the browser. It uses the `tf.io.browserDownloads` function, which creates an IOHandler that initiates file downloads. The downloaded files include the model's topology ('model.json') and weights ('model.weights.bin'), with an optional prefix for file naming. This is useful for saving trained models directly from the browser. ```javascript const model = tf.sequential(); model.add(tf.layers.dense({units: 1, inputShape: [10], activation: 'sigmoid'})); const saveResult = await model.save('downloads://mymodel'); // This will trigger downloading of two files: // 'mymodel.json' and 'mymodel.weights.bin'. console.log(saveResult); ``` -------------------------------- ### Convert Depth to Space in JavaScript (NHWC) Source: https://js.tensorflow.org/api/latest/index Rearranges data from the depth dimension into spatial blocks for a rank 4 tensor. This example uses the 'NHWC' data format. ```javascript const x = tf.tensor4d([1, 2, 3, 4], [1, 1, 1, 4]); const blockSize = 2; const dataFormat = "NHWC"; tf.depthToSpace(x, blockSize, dataFormat).print(); ``` -------------------------------- ### Initialize Tensors with Zeros in TensorFlow.js Source: https://js.tensorflow.org/api/latest/index The tf.initializers.zeros() function creates an initializer that generates tensors filled with zeros. This is a common way to start model weights or tensor values. ```javascript tf.initializers.zeros () ``` -------------------------------- ### Get Current High-Resolution Time with tf.util.now Source: https://js.tensorflow.org/api/latest/index Returns the current high-resolution time in milliseconds relative to an arbitrary past time. This function is cross-platform, working in both Node.js and browser environments. ```javascript console.log(tf.util.now()); ``` -------------------------------- ### Load Model from Browser Files with TensorFlow.js Source: https://js.tensorflow.org/api/latest/index This snippet illustrates how to load model artifacts from user-selected files in the browser using `tf.io.browserFiles`. This IOHandler is suitable for loading models when the model's topology (JSON) and weights (binary) are provided as files. When used with `tf.loadLayersModel`, it allows constructing a Keras-style `tf.LayersModel` from these loaded artifacts. Note that this code requires corresponding HTML file input elements. ```javascript // Note: This code snippet won't run properly without the actual file input // elements in the HTML DOM. // Suppose there are two HTML file input (``) // elements. const uploadJSONInput = document.getElementById('upload-json'); const uploadWeightsInput = document.getElementById('upload-weights'); const model = await tf.loadLayersModel(tf.io.browserFiles([ uploadJSONInput, uploadWeightsInput ])); ``` -------------------------------- ### Get Memory Information with tf.memory Source: https://js.tensorflow.org/api/latest/index Returns memory info at the current time in the program. The result is an object with properties like numBytes, numTensors, and numDataBuffers. For WebGL, it also includes numBytesInGPU. ```javascript // Example usage for tf.memory() would involve calling it directly: // const memInfo = tf.memory(); // console.log(memInfo); // The actual code example is conceptual and demonstrates the return object structure. ``` -------------------------------- ### Backend Management API Source: https://js.tensorflow.org/api/latest/index APIs for managing TensorFlow.js backends, including removing and setting the active backend. ```APIDOC ## tf.removeBackend ### Description Removes a backend and its registered factory. ### Method `tf.removeBackend(name)` ### Parameters #### Path Parameters - **name** (string) - The name of the backend to remove. ### Returns void ## tf.setBackend ### Description Sets the backend responsible for creating tensors and executing operations. This operation disposes of the current backend and its associated tensors. A new backend is initialized, even if it's of the same type. ### Method `tf.setBackend(backendName)` ### Parameters #### Path Parameters - **backendName** (string) - The name of the backend to set. Supported values include `'webgl'`, `'cpu'`, `'wasm'`, and `'tensorflow'` (for Node.js). ### Returns Promise - A promise that resolves to `true` if the backend initialization was successful, `false` otherwise. ``` -------------------------------- ### Get Tensor as Human-Readable String (JavaScript) Source: https://js.tensorflow.org/api/latest/index The `toString()` method provides a human-readable string representation of the tensor, which is helpful for debugging and logging. An optional verbose parameter can be provided for more detailed output. ```javascript const tensorString = tensor.toString(); const verboseString = tensor.toString(true); ``` -------------------------------- ### prefetch (bufferSize) Source: https://js.tensorflow.org/api/latest/index Creates a `Dataset` that prefetches elements from this dataset. ```APIDOC ## prefetch (bufferSize) ### Description Creates a `Dataset` that prefetches elements from this dataset. ### Method prefetch ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **bufferSize** (number) - An integer specifying the number of elements to be prefetched. ### Request Example ```javascript // Example not provided in source, but conceptually: // const dataset = tf.data.array([1, 2, 3]).prefetch(2); ``` ### Response #### Success Response (200) - **tf.data.Dataset** - The dataset with prefetched elements. #### Response Example ```json { "example": "Dataset object" } ``` ``` -------------------------------- ### Apply Activation Layer and Create Model in TensorFlow.js Source: https://js.tensorflow.org/api/latest/index This snippet demonstrates applying an activation layer to a dense layer's output and then creating a TensorFlow.js model with both the dense output and the activated output. It also shows how to predict using the model and print the results. ```javascript const activationOutput = activationLayer.apply(denseOutput); // Create the model based on the inputs. const model = tf.model({ inputs: input, outputs: [denseOutput, activationOutput] }); // Collect both outputs and print separately. const [denseOut, activationOut] = model.predict(tf.randomNormal([6, 5])); denseOut.print(); activationOut.print(); ``` -------------------------------- ### Iterating Over a Dataset Asynchronously in JavaScript Source: https://js.tensorflow.org/api/latest/index Applies a function to every element of the dataset asynchronously. After the function is applied, any Tensors contained within the element are disposed. This example prints each element of the dataset. ```javascript const a = tf.data.array([1, 2, 3]); await a.forEachAsync(e => console.log(e)); ``` -------------------------------- ### Manage TensorFlow Backends (JavaScript) Source: https://js.tensorflow.org/api/latest/index Functions to manage the backend responsible for tensor operations. `setBackend` initializes or switches the backend (e.g., 'webgl', 'cpu', 'wasm'), potentially disposing of the current one. `removeBackend` unregisters a backend factory. ```javascript tf.removeBackend (name) function Source Removes a backend and the registered factory. Parameters: * name (string) ``` ```javascript tf.setBackend (backendName) function Source Sets the backend (cpu, webgl, wasm, etc) responsible for creating tensors and executing operations on those tensors. Returns a promise that resolves to a boolean if the backend initialization was successful. Note this disposes the current backend, if any, as well as any tensors associated with it. A new backend is initialized, even if it is of the same type as the previous one. Parameters: * backendName (string) The name of the backend. Currently supports 'webgl'|'cpu' in the browser, 'tensorflow' under node.js (requires tfjs-node), and 'wasm' (requires tfjs-backend-wasm). Returns: Promise ``` -------------------------------- ### tf.signal.hannWindow Source: https://js.tensorflow.org/api/latest/index Generate a Hann window. ```APIDOC ## POST /tf.signal.hannWindow ### Description Generate a Hann window. See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows ### Method POST ### Endpoint /tf.signal.hannWindow ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **windowLength** (number) - Required - The length of the window. ### Request Example ```json { "windowLength": 10 } ``` ### Response #### Success Response (200) - **tensor** (tf.Tensor1D) - The generated Hann window tensor. #### Response Example ```json { "tensor": "[Tensor object representation]" } ``` ``` -------------------------------- ### Create Scalar Tensor with tf.scalar Source: https://js.tensorflow.org/api/latest/index Illustrates the creation of a rank-0 tensor (scalar) using the `tf.scalar` function. This is a more readable alternative to `tf.tensor` for single-value tensors. The example shows how to print the scalar's value. ```javascript tf.scalar(3.14).print(); ``` -------------------------------- ### take (count) Source: https://js.tensorflow.org/api/latest/index Creates a `Dataset` with at most `count` initial elements from this dataset. ```APIDOC ## take (count) ### Description Creates a `Dataset` with at most `count` initial elements from this dataset. ### Method take ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **count** (number) - The number of elements of this dataset that should be taken to form the new dataset. If `count` is `undefined` or negative, or if `count` is greater than the size of this dataset, the new dataset will contain all elements of this dataset. ### Request Example ```javascript const a = tf.data.array([1, 2, 3, 4, 5, 6]).take(3); a.forEachAsync(e => console.log(e)); ``` ### Response #### Success Response (200) - **tf.data.Dataset** - The dataset with a limited number of elements. #### Response Example ```json { "example": "Dataset object" } ``` ``` -------------------------------- ### tf.registerBackend Source: https://js.tensorflow.org/api/latest/index Registers a global backend. ```APIDOC ## tf.registerBackend (name, factory, priority?) ### Description Registers a global backend. The registration should happen when importing a module file (e.g. when importing `backend_webgl.ts`), and is used for modular builds (e.g. custom tfjs bundle with only webgl support). ### Method N/A (Backend function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Example of registering a custom backend (hypothetical) const customBackendFactory = () => { return { // ... backend implementation details ... name: 'custom', binding: () => ({ name: 'custom' }) }; }; tf.registerBackend('custom', customBackendFactory, 2); console.log('Custom backend registered.'); ``` ### Response #### Success Response (N/A) - **boolean** - True if the backend was successfully registered, false otherwise. #### Response Example ```json true ``` ``` -------------------------------- ### Slice Tensor2D using TensorFlow.js Source: https://js.tensorflow.org/api/latest/index Extracts a slice from a 2-dimensional tensor. This TensorFlow.js function allows for precise selection of sub-tensors by specifying the starting coordinates and the size of the slice along each dimension. It is compatible with multiple backends. ```javascript const x = tf.tensor2d([1, 2, 3, 4], [2, 2]); x.slice([1, 0], [1, 2]).print(); ``` -------------------------------- ### Calculate Binary Accuracy (JavaScript) Source: https://js.tensorflow.org/api/latest/index Computes the binary accuracy metric between true labels (`yTrue`) and predicted labels (`yPred`). Both tensors are expected to contain values between 0 and 1. The example demonstrates calculating accuracy for two sets of predictions. ```javascript tf.metrics.binaryAccuracy (yTrue, yPred) function Source Binary accuracy metric function. `yTrue` and `yPred` can have 0-1 values. Example: ``` const x = tf.tensor2d([[1, 1, 1, 1], [0, 0, 0, 0]], [2, 4]); const y = tf.tensor2d([[1, 0, 1, 0], [0, 0, 0, 1]], [2, 4]); ``` -------------------------------- ### Register a Custom Backend with tf.registerBackend Source: https://js.tensorflow.org/api/latest/index Registers a new backend globally with TensorFlow.js. This is typically done in module files for custom builds. It takes a name, a factory function that returns a backend instance (or a Promise of one), and an optional priority. ```javascript // Example usage (simplified): const customBackendFactory = () => { // Return a custom backend instance return { /* backend implementation */ }; }; tf.registerBackend('my-custom-backend', customBackendFactory, 5); console.log('Custom backend registered.'); ``` -------------------------------- ### Slice Tensor1D using TensorFlow.js Source: https://js.tensorflow.org/api/latest/index Extracts a slice from a 1-dimensional tensor. This TensorFlow.js function takes a tensor, a starting point (begin), and a size for the slice. It's useful for selecting subsets of tensor data. Supports various execution backends. ```javascript const x = tf.tensor1d([1, 2, 3, 4]); x.slice([1], [2]).print(); ``` -------------------------------- ### tf.layers.simpleRNN API Source: https://js.tensorflow.org/api/latest/index Documentation for the tf.layers.simpleRNN function, including its parameters and usage. ```APIDOC ## POST /tf.layers.simpleRNN ### Description Implements a fully-connected Recurrent Neural Network layer where the output is fed back into the input. This layer consists of one `SimpleRNNCell` and operates on a sequence of inputs. ### Method POST ### Endpoint /tf.layers.simpleRNN ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **args** (Object) - The configuration object for the SimpleRNN layer. - **units** (number) - Positive integer, dimensionality of the output space. Required. - **activation** (string) - Activation function to use. Defaults to 'tanh'. - **useBias** (boolean) - Whether the layer uses a bias vector. Defaults to true. - **kernelInitializer** (string|tf.initializers.Initializer) - Initializer for the `kernel` weights matrix. Defaults to 'glorotUniform'. - **recurrentInitializer** (string|tf.initializers.Initializer) - Initializer for the `recurrentKernel` weights matrix. Defaults to 'orthogonal'. - **biasInitializer** (string|tf.initializers.Initializer) - Initializer for the bias vector. Defaults to 'zeros'. - **kernelRegularizer** (string|Regularizer) - Regularizer function applied to the kernel weights matrix. - **recurrentRegularizer** (string|Regularizer) - Regularizer function applied to the recurrentKernel weights matrix. - **biasRegularizer** (string|Regularizer) - Regularizer function applied to the bias vector. - **kernelConstraint** (string|tf.constraints.Constraint) - Constraint function applied to the kernel weights matrix. - **recurrentConstraint** (string|tf.constraints.Constraint) - Constraint function applied to the recurrentKernel weights matrix. - **biasConstraint** (string|tf.constraints.Constraint) - Constraint function applied to the bias vector. - **dropout** (number) - Fraction of the units to drop for the linear transformation of the inputs (between 0 and 1). - **recurrentDropout** (number) - Fraction of the units to drop for the linear transformation of the recurrent state (between 0 and 1). - **dropoutFunc** (Function) - Function for dropout, used for test DI purpose. - **cell** (tf.RNNCell|tf.RNNCell[]) - A RNN cell instance or a list of RNN cell instances. - **returnSequences** (boolean) - Whether to return the last output or the full sequence. Defaults to false. - **returnState** (boolean) - Whether to return the last state in addition to the output. Defaults to false. ### Request Example ```json { "units": 8, "returnSequences": true } ``` ### Response #### Success Response (200) - **layer** (object) - The configured SimpleRNN layer instance. #### Response Example ```json { "layer": { "units": 8, "returnSequences": true, "activation": "tanh", "useBias": true, "kernelInitializer": {"config":{"gain":1.0,"mode":"fanDefault"},"className":"glorotUniform"}, "recurrentInitializer": {"config":{},"className":"orthogonal"}, "biasInitializer": {"config":{},"className":"zeros"}, "kernelRegularizer": null, "recurrentRegularizer": null, "biasRegularizer": null, "kernelConstraint": null, "recurrentConstraint": null, "biasConstraint": null, "dropout": 0, "recurrentDropout": 0, "name": "simple_rnn_1", "trainable": true, "dtype": "float32", "stateful": false, "resetAfterInherits": false, "returnState": false } } ``` ``` -------------------------------- ### Configure 1D Convolutional Layer with Strides and Padding in TensorFlow.js Source: https://js.tensorflow.org/api/latest/index This example shows how to configure a tf.layers.conv1d layer with specific strides and padding. Strides control the step size of the convolution, and padding determines how the input is extended. This is crucial for controlling the output dimensions. ```javascript const convLayerWithStrides = tf.layers.conv1d({ filters: 64, kernelSize: 5, strides: 2, // Move the kernel 2 steps at a time padding: 'same', // Pad the input so the output has the same spatial dimensions activation: 'tanh', inputShape: [null, 64] // Variable-length sequences of 64-dimensional vectors }); console.log(convLayerWithStrides); ```