### Install Dependencies and Start Server
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/demo/mobilenet/README.md
Installs project dependencies using Yarn and starts a local web server for the demo. The server also watches for file changes.
```bash
cd demo # If not already in the demo directory.
yarn # Installs dependencies.
yarn mobilenet # Starts a web server and opens a page. Also watches for changes.
```
--------------------------------
### Install Dependencies and Start Server
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/demo/control_flow/README.md
Installs project dependencies using yarn and starts a web server for the control flow demo. The server watches for changes and opens a browser page.
```bash
cd demo # If not already in the demo directory.
yarn # Installs dependencies.
yarn control_flow # Starts a web server and opens a page. Also watches for changes.
```
--------------------------------
### Build and Watch Example
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-data/demo/boston-housing/README.md
Build the example and enable watch mode for automatic recompilation on file changes.
```sh
$ yarn watch
```
--------------------------------
### Launch tensorflowjs Converter Wizard
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/python/README.md
Start the interactive tensorflowjs converter wizard to guide model conversion.
```bash
tensorflowjs_wizard
```
--------------------------------
### Development Setup for tfjs-node
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/README.md
Install JS dependencies and run tests for tfjs-node. Use 'yarn enable-gpu' to switch to GPU for local development.
```sh
# Download and install JS dependencies, including libtensorflow 1.8.
yarn
# Run TFJS tests against Node.js backend:
yarn test
```
```sh
# Switch to GPU for local development:
yarn enable-gpu
```
--------------------------------
### Install dependencies from source
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-vis/README.md
Install project dependencies using yarn or npm when building from source.
```bash
yarn
```
```bash
npm install
```
--------------------------------
### Download and Install Benchmark Tool
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/browserstack-benchmark/README.md
Clone the tfjs repository, navigate to the benchmark directory, and install dependencies using yarn.
```shell
git clone https://github.com/tensorflow/tfjs.git
cd tfjs/e2e/benchmarks/browserstack-benchmark
yarn install
```
--------------------------------
### Install Dependencies
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-data/demo/boston-housing/README.md
Install project dependencies using npm or yarn.
```sh
$ npm install
# Or
$ yarn
```
--------------------------------
### Prepare and Build Demo
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-nodegl/demo/README.md
Install demo-specific dependencies using yarn.
```sh
yarn
```
--------------------------------
### Web-friendly format example URLs
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/README.md
Example URLs for a converted MobileNet model, showing the model.json file and the sharded weight files.
```html
https://storage.cloud.google.com/tfjs-models/savedmodel/mobilenet_v1_1.0_224/model.json
https://storage.cloud.google.com/tfjs-models/savedmodel/mobilenet_v1_1.0_224/group1-shard1of5
...
https://storage.cloud.google.com/tfjs-models/savedmodel/mobilenet_v1_1.0_224/group1-shard5of5
```
--------------------------------
### Install tfjs-vis with npm
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-vis/README.md
Install the tfjs-vis library using npm. Ensure TensorFlow.js is also installed.
```bash
npm install @tensorflow/tfjs-vis
```
--------------------------------
### Run Benchmark Tool
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/browserstack-benchmark/README.md
Execute the benchmark tool using Node.js. This will start a local server for accessing the benchmark interface.
```shell
node app.js
```
--------------------------------
### Install tfjs-vis with yarn
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-vis/README.md
Install the tfjs-vis library using yarn. Ensure TensorFlow.js is also installed.
```bash
yarn add @tensorflow/tfjs-vis
```
--------------------------------
### Install TensorFlow.js Node.js (GPU)
Source: https://context7.com/tensorflow/tfjs/llms.txt
Install the GPU-accelerated version for Node.js, requiring CUDA and cuDNN.
```bash
npm install @tensorflow/tfjs-node-gpu
```
--------------------------------
### Run Cartoonizer Demo Locally
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-tflite/demo/README.md
Execute this command to start the demo locally after building dependencies.
```sh
yarn watch
```
--------------------------------
### Install Python Environment
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/README.md
Use pyenv to install and set a specific Python version for your project. This is recommended to avoid conflicts with existing TensorFlow/Keras installations.
```bash
pyenv install 3.7.10
pyenv local 3.7.10
```
--------------------------------
### Install Python Dependencies
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/DEVELOPMENT.md
Installs necessary Python dependencies for development and testing. Ensure you are in the 'python/' directory.
```sh
cd python
pip install -r requirements.txt
```
--------------------------------
### Install tensorflowjs
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-layers/demos/README.md
Install the tensorflowjs package using pip. This is a prerequisite for running the benchmark scripts.
```bash
pip install tensorflowjs
```
--------------------------------
### Install Xcode Command Line Tools
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/README.md
On Mac OS X, install the Xcode command line tools using the xcode-select command.
```sh
$ xcode-select --install
```
--------------------------------
### Enable GPU Support by Installing from Source
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/DEVELOPMENT.md
Enables GPU support by performing the same steps as `yarn install-from-source` but using the TensorFlow GPU library.
```sh
yarn enable-gpu
```
--------------------------------
### Install Build Tools Manually
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/WINDOWS_TROUBLESHOOTING.md
Install the necessary system build tools manually. This command should be run in a privileged (Administrator) shell if it fails in a regular prompt.
```sh
npm install -g --production windows-build-tools
```
--------------------------------
### Manual Forward Pass Example
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/README.md
Example of performing a manual forward pass using loaded weights. This demonstrates matrix multiplication and addition with bias.
```javascript
const input = tf.tensor(...);
tf.matMul(weightMap['fc1/weights'], input).add(weightMap['fc1/bias']);
```
--------------------------------
### Install tensorflowjs with CLI Support
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/python/README.md
Install the tensorflowjs Python package with support for the interactive CLI wizard.
```bash
pip install tensorflowjs[wizard]
```
--------------------------------
### Build Dependencies for Cartoonizer Demo
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-tflite/demo/README.md
Run these commands to build the necessary dependencies and install the project locally.
```sh
yarn build-deps
yarn
```
--------------------------------
### Install from Source with Local Addon Compilation
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/DEVELOPMENT.md
Clears local resources, downloads the TensorFlow C library, and compiles the native addon from source. This is an alternative to downloading pre-compiled addons.
```sh
yarn install-from-source
```
--------------------------------
### Install Build Tools with Python Path
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/WINDOWS_TROUBLESHOOTING.md
Use this command to install Windows build tools and add Python to the system path, which can resolve 'python2' not found errors during node-gyp configuration.
```sh
$ npm --add-python-to-path='true' --debug install --global windows-build-tools
```
--------------------------------
### Install CPU TensorFlow.js for Node
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/README.md
Use npm or yarn to install the CPU version of TensorFlow.js for Node.js.
```sh
npm install @tensorflow/tfjs-node
(or)
```
```sh
yarn add @tensorflow/tfjs-node
```
--------------------------------
### Configure node-gyp Verbose
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/WINDOWS_TROUBLESHOOTING.md
Run this command to inspect missing components when node-gyp configuration fails. You might need to install node-gyp globally first.
```sh
node-gyp configure --verbose
```
--------------------------------
### Install GPU TensorFlow.js for Node (Linux/Windows)
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/README.md
Use npm or yarn to install the GPU-accelerated version of TensorFlow.js for Node.js on Linux or Windows.
```sh
npm install @tensorflow/tfjs-node-gpu
(or)
```
```sh
yarn add @tensorflow/tfjs-node-gpu
```
--------------------------------
### Setup Kernel Timing Table
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/local-benchmark/index.html
Configures the table headers for displaying kernel timing information. It adapts the columns based on the `kernelTiming` state, including inputs, outputs, and GPU programs if applicable.
```javascript
async function setupKernelTable() {
kernelsTableHead.innerText = '';
kernelTable.innerHTML = '';
const rows = ['Kernel', 'Time(ms)'];
if (state.kernelTiming === 'individual') {
rows.push('Inputs', 'Output');
if (state.backend === 'webgl') {
rows.push('GPUPrograms');
}
}
appendRow(kernelsTableHead, ...rows);
await tf.nextFrame();
}
```
--------------------------------
### Install Node.js with arm64 binary on Mac M1
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/README.md
Ensure your terminal is configured for arm64 and install Node.js with an arm64 binary for Mac M1 compatibility.
```sh
uname -m
```
```javascript
node -e 'console.log(os.arch())'
```
--------------------------------
### Install Python Build Dependencies
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/README.md
Installs necessary packages for building Python from source, including SSL, foreign functions, and zlib development packages. Use this for Debian-based systems.
```bash
sudo apt-get build-dep python3
sudo apt install libssl-dev libffi-dev zlib1g-dev
```
--------------------------------
### Install tfjs-automl via CDN
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-automl/README.md
Include the tfjs-automl package in your HTML using a CDN link.
```html
```
--------------------------------
### Install TensorFlow.js via NPM
Source: https://context7.com/tensorflow/tfjs/llms.txt
Use NPM or Yarn to add the TensorFlow.js library to your project.
```bash
npm install @tensorflow/tfjs
# or with yarn
yarn add @tensorflow/tfjs
```
--------------------------------
### Run Python Unit Tests with Bazel
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/DEVELOPMENT.md
Executes Python unit tests using Bazel. Ensure Bazel is installed and configured.
```sh
cd python
bazel test tensorflowjs/...
```
--------------------------------
### Install TensorFlow.js via CDN
Source: https://context7.com/tensorflow/tfjs/llms.txt
Include the TensorFlow.js library in your HTML using a CDN script tag.
```html
```
--------------------------------
### Display Benchmarking Parameters
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/local-benchmark/index.html
Populates a table with the current benchmarking parameters, such as benchmark type, model details, backend, and input configurations. This helps in documenting the test setup.
```javascript
function showBenchmarkingParameters() {
appendRow(parameterTable, 'task', 'Performance Benchmark');
appendRow(parameterTable, 'benchmark', state.benchmark);
appendRow(parameterTable, 'modelType', state.modelType || 'Unknown');
appendRow(parameterTable, 'convertedBy', model?.artifacts?.convertedBy || 'Unknown');
if (state.benchmark === 'custom') {
appendRow(parameterTable, 'modelUrl', state.modelUrl);
}
appendRow(parameterTable, 'numRuns', state.numRuns);
appendRow(parameterTable, 'numProfiles', state.numProfiles);
appendRow(parameterTable, 'backend', state.backend);
appendRow(parameterTable, 'kernelTiming', state.kernelTiming);
if (isParameterDefined('inputSizes')) {
appendRow(parameterTable, 'inputSize', state.inputSize);
}
if (isParameterDefined('inputTypes')) {
appendRow(parameterTable, 'inputType', state.inputType);
}
if (isParameterDefined('architectures')) {
appendRow(parameterTable, 'architecture', state.architecture);
}
}
```
--------------------------------
### Expected Demo Output
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-nodegl/demo/README.md
This output shows the successful execution of the MobileNet inference demo, including platform information, model loading times, cold start performance, and inference speed.
```sh
node run_mobilenet_inference.js dog.jpg
Platform node has already been set. Overwriting the platform with [object Object].
- gl.VERSION: OpenGL ES 3.0 (ANGLE 2.1.0.9512a0ef062a)
- gl.RENDERER: ANGLE (Intel Inc., Intel(R) Iris(TM) Plus Graphics 640, OpenGL 4.1 core)
- Loading model...
- Mobilenet load: 6450.763924002647ms
- Coldstarting model...
- Mobilenet cold start: 297.92842200398445ms
- Running inference (100x) ...
- Mobilenet inference: (100x) : 35.75772546708584ms
```
--------------------------------
### Configure WSL for TensorFlow.js Development
Source: https://github.com/tensorflow/tfjs/blob/master/DEVELOPMENT.md
Sets up environment variables for Chrome and Bazel within WSL. Ensure CHROME_BIN points to your chrome.exe installation. This configuration is necessary for running browser tests from WSL.
```bash
# Add yarn bin to the path
echo "export PATH=$PATH:~/.yarn/bin/" >> ~/.bashrc &&
# Set CHROME_BIN. Change this if your CHROME_BIN has a different path.
echo "export CHROME_BIN=/mnt/c/Program\ Files/Google/Chrome/Application/chrome.exe" >> ~/.bashrc &&
source ~/.bashrc &&
# Clone tfjs.
git clone https://github.com/tensorflow/tfjs.git &&
cd tfjs &&
# Create the .bazelrc.user file for WSL.
echo "# Pass necessary WSL variables for running in Windows Subsystem for Linux.
# WSLENV and WSL_DISTRO_NAME are build-in variables that are needed for running
# the 'wslpath' command, which Karma uses to resolve file paths.
# DISPLAY=:0 is passed to the Chrome process to make it launch in a window
# since running Chrome headlessly from WSL does not seem to work. If you get
# this working, please send a PR updating these docs (or open an issue :).
run --test_env=CHROME_BIN --test_env=WSLENV --test_env=WSL_DISTRO_NAME --define DISPLAY=:0
test --test_env=CHROME_BIN --test_env=WSLENV --test_env=WSL_DISTRO_NAME --define DISPLAY=:0" > .bazelrc.user &&
printf "\n\nDone! Try running a browser test to verify the installation worked, e.g. 'cd tfjs-core && yarn && yarn test-browser'\n"
```
--------------------------------
### Render a barchart with tfjs-vis
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-vis/README.md
Example of rendering a barchart using tfjs-vis. This involves preparing data, getting a surface, and then rendering the chart on that surface.
```javascript
const data = [
{ index: 0, value: 50 },
{ index: 1, value: 100 },
{ index: 2, value: 150 },
];
// Get a surface
const surface = tfvis.visor().surface({ name: 'Barchart', tab: 'Charts' });
// Render a barchart on that surface
tfvis.render.barchart(surface, data, {});
```
--------------------------------
### Show Help Menu
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/browserstack-benchmark/README.md
Use the -h or --help flags to display the help menu and all available optional arguments in the shell.
```shell
node app.js --h
```
```shell
node app.js --help
```
--------------------------------
### Initialize Benchmark GUI and Load TFJS
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/local-benchmark/index.html
Sets up the GUI, parses URL parameters, and loads the TensorFlow.js library with specified local builds if provided.
```typescript
async function onPageLoad() {
const gui = new lil.GUI({ width: 350 });
gui.domElement.id = 'gui';
urlState = getURLState(location.search);
let localBuild = [];
if (urlState && urlState.has('localBuild')) {
localBuild = urlState.get('localBuild').split(',');
}
await loadTFJS(localBuild);
if (urlState && urlState.has('backend')) state.backend = urlState.get('backend');
await tf.setBackend(state.backend);
const modelFolder = gui.addFolder('Benchmark');
let modelUrlController = null;
modelController = modelFolder.add(state, 'benchmark', Object.keys(benchmarks));
modelController.name('models').onChange(async model => {
await showMsg(null);
const benchmark = benchmarks[state.benchmark];
state.isModelChanged = true;
state.isModelLoaded = false;
if (modelArchitectureController !== null) {
modelArchitectureController.destroy();
modelArchitectureController = null;
}
if (inputSizeController !== null) {
inputSizeController.destroy();
inputSizeController = null;
}
if (inputTypeController !== null) {
inputTypeController.destroy();
inputTypeController = null;
}
if (isParameterDefined('inputSizes')) {
inputSizeController = modelParameterFolder.add(state, 'inputSize', benchmark['inputSizes']).name('inputSizes').onChange(async inputSize => {
state.inputSize = inputSize;
state.isModelChanged = true;
});
// Current use first value as default.
let defaultInputSize = 0;
if (isURLParameterDefined('inputSize')) {
defaultInputSize = urlState.get('inputSize');
} else {
defaultInputSize = benchmark['inputSizes'][0];
}
inputSizeController.setValue(defaultInputSize);
state.inputSize = defaultInputSize;
} else {
// Model doesn't support input size.
state.inputSize = 0;
}
if (isParameterDefined('architectures')) {
modelArchitectureController = modelParameterFolder.add(state, 'architecture', benchmark['architectures']).name('architectures').onChange(async architecture => {
state.architecture = architecture;
state.isModelChanged = true;
});
// Current use first value as default.
let defaultModelArchitecture = null;
if (isURLParameterDefined('architecture')) defaultModelArchitecture = urlState.get('architecture');
else defaultModelArchitecture = benchmark['architectures'][0];
modelArchitectureController.setValue(defaultModelArchitecture);
state.architecture = defaultModelArchitecture;
} else {
// Model doesn't support architecture.
state.architecture = '';
}
if (isParameterDefined('inputTypes')) {
inputTypeController = modelParameterFolder.add(state, 'inputType', benchmark['inputTypes']).name('inputTypes').onChange(async inputType => {
state.inputType = inputType;
state.isModelChanged = true;
});
// Current use first value as default.
let defaultInputType =
```
--------------------------------
### Host model and benchmark tool locally
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/local-benchmark/README.md
Run a local HTTP server to host the benchmark tool and the downloaded model.
```shell
npx http-server
```
--------------------------------
### Visor Instance
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-vis/demos/api/index.html
Demonstrates how to create and manage visor instances and surfaces.
```APIDOC
## visorInstance = tfvis.visor()
### Description
Creates a new visor instance. This instance can then be used to create and manage surfaces.
### Method
`tfvis.visor()`
### Parameters
None
### Example
```javascript
const visorInstance = tfvis.visor();
visorInstance.surface({ name: 'Surface 1' });
visorInstance.surface({ name: 'Surface 2' });
visorInstance.surface({ name: 'Surface 3', tab: 'Tab 2' });
visorInstance.surface({ name: 'Just a surface', tab: 'A really long tab name' });
```
```
--------------------------------
### Install tfjs-automl via npm
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-automl/README.md
Install the tfjs-automl package using npm for use in your project.
```sh
npm i @tensorflow/tfjs-automl
```
--------------------------------
### Run Benchmarks with Configuration File
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/browserstack-benchmark/README.md
Use the --benchmarks argument to specify a JSON file containing benchmark configurations. This file defines models, runs, backends, and browser targets for benchmarking.
```shell
node app.js --benchmarks=relative_file_path.json
```
--------------------------------
### Create and Manage Visor Surfaces
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-vis/demos/api/index.html
Demonstrates how to create a visor instance and add multiple surfaces to it, including surfaces within different tabs.
```javascript
visorInstance = tfvis.visor();
visorInstance.surface({ name: 'Surface 1' });
visorInstance.surface({ name: 'Surface 2' });
visorInstance.surface({ name: 'Surface 3', tab: 'Tab 2' });
visorInstance.surface({ name: 'Just a surface', tab: 'A really long tab name' });
```
--------------------------------
### Clone Project and Install Dependencies
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/README.md
Clones the TensorFlow.js repository and installs project dependencies using Yarn. This is a prerequisite for development.
```bash
git clone https://github.com/tensorflow/tfjs.git
cd tfjs
yarn # Installs dependencies.
```
--------------------------------
### Configure Model Parameters GUI
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/local-benchmark/index.html
Sets up GUI controllers for model-specific parameters like architecture, input size, and input type. These are shown only if defined for the selected model.
```javascript
if (isParameterDefined('architectures')) {
modelArchitectureController = modelParameterFolder.add(state, 'architecture', benchmarks[state.benchmark]['architectures']);
modelArchitectureController.setValue(state.architecture);
}
if (isParameterDefined('inputSizes')) {
inputSizeController = modelParameterFolder.add(state, 'inputSize', benchmarks[state.benchmark]['inputSizes']);
inputSizeController.setValue(state.inputSize);
}
if (isParameterDefined('inputTypes')) {
inputTypeController = modelParameterFolder.add(state, 'inputType', benchmarks[state.benchmark]['inputTypes']);
inputTypeController.setValue(state.inputType);
}
```
--------------------------------
### Initialize GUI and State
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/local-benchmark/index.html
Initializes the dat.GUI interface, including folders for model, parameters, and environment. It also sets up controllers for various benchmark settings and loads initial state from URL.
```javascript
const gui = new dat.GUI();
gui.width = 300;
const state = {
benchmark: 'mobilenet',
architecture: 'MobileNetV1',
inputSize: '224',
inputType: 'image',
numWarmups: 5,
numRuns: 10,
numProfiles: 10,
kernelTiming: 'aggregate',
parallelCompile: true,
backend: 'webgl',
modelUrl: '',
isModelChanged: true,
isModelLoaded: false,
testCorrectness: () => {},
run: () => {},
};
const modelFolder = gui.addFolder('Model');
const modelController = modelFolder.add(state, 'benchmark', Object.keys(benchmarks));
modelController.onChange(async benchmark => {
state.benchmark = benchmark;
state.isModelChanged = true;
state.isModelLoaded = false;
await showMsg(null);
// Update model parameters based on the selected benchmark.
if (isParameterDefined('architectures')) {
modelArchitectureController.update({
min: benchmarks[state.benchmark]['architectures'],
});
state.architecture = benchmarks[state.benchmark]['architectures'][0];
}
if (isParameterDefined('inputSizes')) {
inputSizeController.update({
min: benchmarks[state.benchmark]['inputSizes'],
});
state.inputSize = benchmarks[state.benchmark]['inputSizes'][0];
}
if (isParameterDefined('inputTypes')) {
inputTypeController.update({
min: benchmarks[state.benchmark]['inputTypes'],
});
state.inputType = benchmarks[state.benchmark]['inputTypes'][0];
}
// Unfolding the model parameter UI if any model parameters are deinfed
// in the current model.
if (isParameterDefined('inputSizes') || isParameterDefined('inputTypes') || isParameterDefined('architectures')) {
defaultInputType = urlState.get('inputType');
} else {
defaultInputType = benchmark['inputTypes'][0];
}
inputTypeController.setValue(defaultInputType);
state.inputType = defaultInputType;
} else {
// Model doesn't support input type.
state.inputType = '';
}
// Unfolding the model parameter UI if any model parameters are deinfed
// in the current model.
if (isParameterDefined('inputSizes') || isParameterDefined('inputTypes') || isParameterDefined('architectures')) {
modelParameterFolder.open();
}
if (model === 'custom') {
if (modelUrlController === null) {
modelUrlController = modelFolder.add(state, 'modelUrl').onChange(async modelUrl => {
state.isModelChanged = true;
state.isModelLoaded = false;
await showMsg(null);
});
modelUrlController.domElement.querySelector('input').placeholder = 'https://your-domain.com/model-path/model.json';
if (modelUrlController != null && urlState && urlState.has('modelUrl')) {
modelUrlController.setValue(urlState.get('modelUrl'));
}
}
} else if (modelUrlController != null) {
modelUrlController.destroy();
modelUrlController = null;
}
});
modelFolder.open();
const parameterFolder = gui.addFolder('Parameters');
numWarmupsController = parameterFolder.add(state, 'numWarmups');
numRunsController = parameterFolder.add(state, 'numRuns');
numProfilesController = parameterFolder.add(state, 'numProfiles');
parameterFolder.add(state, 'kernelTiming', ['aggregate', 'individual']);
parallelCompileController = parameterFolder.add(state, 'parallelCompile');
parameterFolder.open();
// Show model parameter UI when loading the page.
modelParameterFolder = gui.addFolder('Model Parameters');
// For each model parameter, show it only if it is defined in the
// pre-selected model.
if (isParameterDefined('architectures')) {
modelArchitectureController = modelParameterFolder.add(state, 'architecture', benchmarks[state.benchmark]['architectures']);
modelArchitectureController.setValue(state.architecture);
}
if (isParameterDefined('inputSizes')) {
inputSizeController = modelParameterFolder.add(state, 'inputSize', benchmarks[state.benchmark]['inputSizes']);
inputSizeController.setValue(state.inputSize);
}
if (isParameterDefined('inputTypes')) {
inputTypeController = modelParameterFolder.add(state, 'inputType', benchmarks[state.benchmark]['inputTypes']);
inputTypeController.setValue(state.inputType);
}
// Unfolding the model parameter UI if any model parameters are deinfed
// in the pre-selected model.
if (isParameterDefined('inputSizes') || isParameterDefined('inputTypes') || isParameterDefined('architectures')) {
modelParameterFolder.open();
}
const envFolder = gui.addFolder('Environment');
envFolder.open();
runButton = gui.add(state, 'run');
runButton.name('Run benchmark');
correctnessButton = gui.add(state, 'testCorrectness');
correctnessButton.name('Test correctness');
tunableFlagsControllers = await showFlagSettingsAndReturnTunableFlagControllers(envFolder, state.backend);
showVersions();
await showEnvironment();
await showGpuInfo();
updateGUIFromURLState();
```
--------------------------------
### Get Layer Activation
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-vis/demos/mnist_internals/index.html
Helper function to get the output (activation) of a specific layer for a given input. This is useful for visualizing intermediate results.
```javascript
// An 'activation' is the output of any of the internal layers of the
// network.
function getActivation(input, model, layer) {
const activationModel = tf.model({
inputs: model.input,
outputs: layer.output,
});
return activationModel.predict(input);
}
```
--------------------------------
### Build Project
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-webgpu/README.md
Run the build command using yarn to compile the project.
```shell
yarn build
```
--------------------------------
### Build, Train, and Predict with a Sequential Model
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-layers/README.md
Demonstrates building a simple sequential model, compiling it with a loss function and optimizer, training it on synthetic data, and performing inference.
```javascript
import * as tf from '@tensorflow/tfjs';
// A sequential model is a container which you can add layers to.
const model = tf.sequential();
// Add a dense layer with 1 output unit.
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// Specify the loss type and optimizer for training.
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.
await model.fit(xs, ys, {epochs: 500});
// After the training, perform inference.
const output = model.predict(tf.tensor2d([[5]], [1, 1]));
output.print();
```
--------------------------------
### Build Benchmark Demo Script
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-layers/demos/README.md
Execute the build script to construct Keras models in Python and benchmark their training. This script also initiates a local HTTP server.
```bash
./scripts/build-benchmarks-demo.sh
```
--------------------------------
### Build Package and Compile TypeScript
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-nodegl/demo/README.md
Install dependencies and compile TypeScript files for the tfjs-backend-nodegl package.
```sh
yarn && yarn tsc
```
--------------------------------
### Navigate to Demo Directory
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-nodegl/demo/README.md
Change the current directory to the demo folder within tfjs-backend-nodegl.
```sh
cd demo
```
--------------------------------
### Run Python Linter
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/DEVELOPMENT.md
Executes the Python linter to check code quality. This requires 'pylint' to be installed separately.
```sh
cd python
pylint tensorflowjs
```
--------------------------------
### Import CPU Backend via Script Tag (Standard)
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-cpu/README.md
Include the TensorFlow.js core and the CPU backend using standard script tags. This makes them available globally.
```html
```
--------------------------------
### Rebuild Native Addon on Raspberry Pi
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/README.md
After installing the package on a Raspberry Pi, rebuild the native addon using npm.
```sh
npm rebuild @tensorflow/tfjs-node --build-from-source
```
--------------------------------
### View tensorflowjs Converter Help
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/python/README.md
Run the tensorflowjs_converter command with the --help flag to see available CLI options.
```bash
tensorflowjs_converter --help
```
--------------------------------
### Set Custom Binaries URI with Environment Variable
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/README.md
Configure tfjs-node to use custom binaries by setting the TFJS_NODE_CDN_STORAGE environment variable before installation.
```sh
TFJS_NODE_CDN_STORAGE="https://yourmirrorofchoice.com/" npm install
(or)
```
```sh
TFJS_NODE_CDN_STORAGE="https://yourmirrorofchoice.com/" yarn install
```
--------------------------------
### Initialize Benchmark Parameters
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/benchmarks/local-benchmark/index.html
Sets default values for benchmark parameters and allows overriding them via URL query parameters. Supports configuring run times, profile times, warmup times, task type, and parallel compilation.
```javascript
'use strict'; let urlState = null; let runTimes = 50; let profileTimes = 1; let warmupTimes = 1; let paralllelCompile = false; // Default do not run any task. let task = ''; function getURLState(url) { let params = new URLSearchParams(url); const keys = [...params.keys()]; if (keys.length === 0) return null; if (params.has('run')) { runTimes = Number(params.get('run')); } if (params.has('profile')) { profileTimes = Number(params.get('profile')); } if (params.has('warmup')) { warmupTimes = Number(params.get('warmup')); } if (params.has('task')) { task = params.get('task'); } if (params.has('parallelCompile')) { paralllelCompile = Boolean(params.get('parallelCompile')); } return params; }
```
--------------------------------
### Create and Print Tensors
Source: https://context7.com/tensorflow/tfjs/llms.txt
Demonstrates creating 2D tensors from flat arrays, random tensors, zeros, and ones. Shows how to print tensor values and inspect their shapes and data types.
```javascript
import * as tf from '@tensorflow/tfjs';
// 2-D tensor (matrix) from a flat array
const mat = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]); // shape [2, 3]
mat.print();
// Tensor [[1, 2, 3], [4, 5, 6]]
// Random tensors
const noise = tf.randomNormal([3, 3]);
noise.print();
// Zeros / ones
const z = tf.zeros([2, 2]);
const o = tf.ones([2, 2]);
console.log(z.shape, o.dtype); // [2, 2] float32
```
--------------------------------
### Publish NPM Package
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/DEVELOPMENT.md
Compiles a new node addon, uploads it to GCP, then builds and publishes a new npm package. Review the publishing script instructions beforehand.
```sh
yarn publish-npm
```
--------------------------------
### Automatic Differentiation
Source: https://context7.com/tensorflow/tfjs/llms.txt
Illustrates how to compute gradients of functions with respect to their inputs using `tf.grad` and `tf.GradientTape`. Shows examples for single and multiple output gradients.
```javascript
import * as tf from '@tensorflow/tfjs';
// Automatic differentiation
const f = (x) => tf.mul(x, x); // f(x) = x^2
const df = tf.grad(f);
const x = tf.scalar(3);
df(x).print(); // 6 (derivative of x^2 at x=3)
// Gradient for multiple outputs
const g = (x) => tf.sum(tf.mul(x, x));
const dg = tf.grad(g);
const xs = tf.tensor1d([1, 2, 3]);
dg(xs).print(); // [2, 4, 6]
```
--------------------------------
### Get Activation Table Data
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-vis/demos/mnist_internals/index.html
Prepares data for rendering activation tables. It extracts filters and computes activations for a given layer, organizing them for display.
```javascript
function getActivationTable(layerName) {
const exampleImageSize = 28;
const layer = model.getLayer(layerName);
// Get the filters
let filters = tf.tidy(() => layer.kernel.val.transpose([3, 0, 1, 2]).unstack());
// It is hard to draw high dimensional filters so we just use a string
if (filters[0].shape[2] > 3) {
filters = filters.map((d, i) => `Filter ${i + 1}`);
}
filters.unshift('Input');
// Get the inputs
const numExamples = examples.xs.shape[0];
const xs = examples.xs.reshape([numExamples, exampleImageSize, exampleImageSize, 1]);
// Get the activations
const activations = tf.tidy(() => {
return getActivation(xs, model, layer).unstack();
});
const activationImageSize = activations[0].shape[0]; // e.g. 24
const numFilters = activations[0].shape[2]; // e.g. 8
const filterActivations = activations.map((activation, i) => {
// activation has shape [activationImageSize, activationImageSize, i];
const unpackedActivations = Array(numFilters).fill(0).map((_, i) =>
activation.slice([0, 0, i], [activationImageSize, activationImageSize, 1])
);
// prepend the input image
const inputExample = tf.tidy(() => xs.slice([i], [1]).reshape([exampleImageSize, exampleImageSize, 1]));
unpackedActivations.unshift(inputExample);
return unpackedActivations;
});
return {
filters,
filterActivations,
};
}
```
--------------------------------
### Select Backend and Manage Memory
Source: https://context7.com/tensorflow/tfjs/llms.txt
Demonstrates selecting between WebGL and WASM backends and managing memory usage with `tf.memory()` and `tf.tidy()`.
```js
import * as tf from '@tensorflow/tfjs';
import '@tensorflow/tfjs-backend-webgl';
import '@tensorflow/tfjs-backend-wasm';
// Query available backends
console.log(tf.engine().registeredBackends()); // { webgl: ..., wasm: ..., cpu: ... }
// Switch to WASM (e.g., on devices without reliable WebGL)
await tf.setBackend('wasm');
await tf.ready();
console.log('Active backend:', tf.getBackend()); // 'wasm'
// Switch back to WebGL
await tf.setBackend('webgl');
await tf.ready();
// Profile memory usage
const memBefore = tf.memory();
console.log(`Tensors in memory: ${memBefore.numTensors}, bytes: ${memBefore.numBytes}`);
const heavy = tf.randomNormal([1000, 1000]);
const memAfter = tf.memory();
console.log(`After allocation: ${memAfter.numTensors} tensors`);
heavy.dispose();
// Keep all tensors in a block, dispose all at once
tf.tidy(() => {
const a = tf.randomNormal([500, 500]);
const b = tf.matMul(a, a);
return b.mean(); // only this tensor escapes tidy
}).dispose();
console.log(`Final tensors: ${tf.memory().numTensors}`); // same as memBefore.numTensors
```
--------------------------------
### Build TensorFlow.js Core API from Source
Source: https://github.com/tensorflow/tfjs/blob/master/DEVELOPMENT.md
Clones the TensorFlow.js Core repository and installs dependencies using yarn. This is the initial step for building the library from source.
```bash
$ git clone https://github.com/tensorflow/tfjs-core.git
$ cd tfjs-core
$ yarn # Installs dependencies.
```
--------------------------------
### Build and Upload Windows Node Addon
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-node/DEVELOPMENT.md
Builds and uploads the native node addon specifically for Windows. This command should be run on a Windows machine.
```sh
yarn upload-windows-addon
```
--------------------------------
### Build and Test TensorFlow.js Pip Package
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-converter/DEVELOPMENT.md
Builds the TensorFlow.js pip package and runs tests after installation. It's crucial to use a virtual environment for this operation.
```sh
./build-pip-package.sh --test /tmp/my_tensorflowjs_pip
```
--------------------------------
### Heatmap Displays Labels in Order Provided
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-vis/demos/api/index.html
Demonstrates that heatmap labels are rendered in the exact order they are provided in the data. This example uses numerical labels for ticks.
```javascript
const data = {
values: [
[5, 4, 3, 2, 1],
[10, 9, 8, 7, 6],
[15, 14, 13, 12, 11],
[20, 19, 18, 17, 16],
[24, 24, 23, 22, 21],
],
xTickLabels: [0, 1, 10, 50, 100],
yTickLabels: [0, 1, 10, 50, 100],
};
// Render to visor
const surface = tfvis.visor().surface({
name: 'Heatmap w Custom Colormap',
tab: 'Charts'
});
tfvis.render.heatmap(surface, data);
// Render to page
const container = document.getElementById('heatmap-sort-order');
tfvis.render.heatmap(container, data);
```
--------------------------------
### Standard TFJS Module Script
Source: https://github.com/tensorflow/tfjs/blob/master/e2e/custom_module/development.md
This is the standard way to invoke the tfjs-custom-module CLI using npx. It's an alternative to the direct node execution shown in other examples.
```bash
"make-custom-tfjs-modules": "npx tfjs-custom-module --config app_tfjs_config.json"
```
--------------------------------
### Create and Get a Surface in tfjs-vis
Source: https://github.com/tensorflow/tfjs/blob/master/tfjs-vis/demos/mnist/index.html
Creates a new surface or retrieves an existing one. Use this to define areas for displaying visualizations or content within the visor.
```javascript
tfvis.visor().surface({name: 'My First Surface', tab: 'Input Data'});
```
--------------------------------
### Run Linting and Tests
Source: https://github.com/tensorflow/tfjs/blob/master/DEVELOPMENT.md
Execute linting and testing commands from the repository root or package directory. Use `yarn test-dev` to avoid unnecessary dependency rebuilds during development.
```bash
# Run this at the root of the repository
$ yarn lint
# cd into the package directory you want to test
$ yarn test
# You may also need to run 'yarn lint' in the directory you want to test
$ yarn lint
```