Open In App

Tensorflow.js tf.layers.conv2d() Function

Tensorflow.js is a Google-developed open-source toolkit for executing machine learning models and deep learning neural networks in the browser or on the node platform. It also enables developers to create machine learning models in JavaScript and utilize them directly in the browser or with Node.js.

The tf.layers.conv2d() function is used to apply the 2D convolution operation on data.



Syntax:

tf.layers.conv2d(args)

Parameters: It accepts the args object which can have the following properties:



Returns: It returns an object (Conv2D).

Example 1:




import * as tf from "@tensorflow/tfjs";
  
const input = tf.input({ shape: [4, 4, 4] });
const conv2DLayer = tf.layers.conv2d({ filters: 2, kernelSize: 2});
const output = conv2DLayer.apply(input);
  
const model = tf.model({ inputs: input, outputs: output });
model.predict(tf.ones([1, 4, 4, 4])).print();

Output:

Tensor
   [[[[1.1710266, -1.0081921],
      [1.1710266, -1.0081921],
      [1.1710266, -1.0081921]],
     [[1.1710266, -1.0081921],
      [1.1710266, -1.0081921],
      [1.1710266, -1.0081921]],
     [[1.1710266, -1.0081921],
      [1.1710266, -1.0081921],
      [1.1710266, -1.0081921]]]]

Example 2:




import * as tf from "@tensorflow/tfjs";
  
const input = tf.input({ shape: [4, 4, 1] });
  
const conv2DLayer = tf.layers
    .conv2d({ filters: 2, kernelSize: 3});
      
const output = conv2DLayer.apply(input);
  
const model = tf.model({ inputs: input, outputs: output });
  
const x = tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8, 
    9, 10, 11, 12, 13, 14, 15, 16], [1, 4, 4, 1]);
  
model.predict(x).print();

Output:

Tensor
   [[[[2.3521864, 1.9806139],
      [2.9982643, 2.055856 ]],
     [[4.9365001, 2.2815819],
      [5.5825787, 2.3568242]]]]

Reference: https://js.tensorflow.org/api/latest/#layers.conv2d


Article Tags :