Monday, December 22, 2025
HomeLanguagesJavascriptTensorflow.js tf.layers build() Method

Tensorflow.js tf.layers build() Method

Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.

The .build() function is used to create the weights of the layer stated. This method should be applied on every layers that hold weights. Moreover, its invoked when the apply() method is invoked in order to build the weights.

Syntax:

build(inputShape)

Parameters:

  • inputShape: It is the stated shape or an array of shape that is untouched.

Return Value: It returns void.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating a model
const model = tf.sequential();
  
// Adding a layer
model.add(tf.layers.dense({units: 1, inputShape: [3]}));
  
// Defining input
const input = tf.input({shape: [6, 2, 6]});
  
// Calling build method with its 
// parameter
model.layers[0].build([input.Shape]);
  
// Printing output
console.log(JSON.stringify(input.shape));
model.layers[0].getWeights()[0].print();


Output:

[null,6,2,6]
Tensor
    [[-0.3726568],
     [0.7343086 ],
     [-0.2459907]]

Here, getWeights() method is used to print the weights.

Example 2:

Javascript




// Importing the tensorflow.js library
//import * as tf from "@tensorflow/tfjs"
  
// Creating a model
const model = tf.sequential();
  
// Adding layers
model.add(tf.layers.dense({units: 1, inputShape: [2]}));
model.add(tf.layers.dense({units: 2}));
  
  
// Defining inputs
const input1 = tf.input({shape: [1, 2]});
const input2 = tf.input({shape: [1.7, 2.7, 6.5]});
  
// Calling build method with its 
// parameter
model.layers[0].build([input1.Shape]);
model.layers[1].build([input2.Shape]);
  
// Printing outputs
console.log(JSON.stringify(input1.shape));
console.log(JSON.stringify(input2.shape));
model.layers[0].getWeights()[0].print();
model.layers[1].getWeights()[0].print();


Output:

[null,1,2]
[null,1.7,2.7,6.5]
Tensor
    [[0.6224715],
     [1.2144204]]
Tensor
     [[0.8342852, 0.4770206],]

Reference: https://js.tensorflow.org/api/latest/#tf.layers.Layer.build

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32456 POSTS0 COMMENTS
Milvus
111 POSTS0 COMMENTS
Nango Kala
6824 POSTS0 COMMENTS
Nicole Veronica
11959 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12038 POSTS0 COMMENTS
Shaida Kate Naidoo
6958 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6912 POSTS0 COMMENTS
Umr Jansen
6890 POSTS0 COMMENTS