Open In App

Tensorflow.js tf.layers.globalAveragePooling2d() 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.globalAveragePooling2d() function is used for applying global average pooling operation for spatial data.



Syntax: 

tf.layers.globalAveragePooling2d( args )

Parameters: 



Return Value: It returns GobalAveragePooling2D

Example 1: 




import * as tf from "@tensorflow/tfjs";
  
const Input = tf.input({ shape: [3, 3, 3] });
const globalAveragePooling2d =
    tf.layers.globalAveragePooling2d({  
        dataFormat: 'channelsFirst',
        batchInputShape:[4,3, 3], 
        trainable: true 
    });
  
const Output = globalAveragePooling2d.apply(Input);
  
const Data = tf.ones([4, 3, 3, 3]);
const model =
    tf.model({ inputs: Input, outputs: Output });
  
model.predict(Data).print();

Output: 

Tensor
    [[1, 1, 1],
     [1, 1, 1],
     [1, 1, 1],
     [1, 1, 1]]

Example 2:




import * as tf from "@tensorflow/tfjs";
  
const Input = tf.input({ shape: [2,  2, 3] });
  
const globalAveragePooling2d =
    tf.layers.globalAveragePooling2d({
        dataFormat: 'channelsLast'
        batchInputShape: [4, 3, 3], 
        trainable:true
    });
      
const Output = globalAveragePooling2d.apply(Input);
  
const model = tf.model({ inputs: Input, outputs: Output });
  
const Data = tf.tensor4d([8, 2, 2, 6, 8, 9, 9, 
    4, 8, 9, 3, 8, 5, 2, 5, 2, 8, 6, 4, 5, 9, 
    12, 8, 11], [2, 2 ,2, 3]);
      
model.predict(Data).print();

Output:

Tensor
    [[8   , 4.25, 6.75],
     [5.75, 5.75, 7.75]]

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


Article Tags :