How to use GlobalMaxPooling2D layer in TensorFlow

This posts explains how to use GlobalMaxPooling2D layer with tf.keras.

For understanding GlobalMaxPooling2D layer lets take an example image, having three channels. Providing this image as input to GlobalMaxPooling2D layer produces 1D tensor that comprises of max values for all channels in the images computed along image height and width.

Applying GlobalMaxPooling2D layer on image with tf.keras

import tensorflow as tf
import matplotlib.pyplot as plt

file = tf.keras.utils.get_file(
    "cat.png",
    "https://storage.googleapis.com/gcptutorials.com/examples/cat.png")

img = tf.keras.preprocessing.image.load_img(file)

x = tf.keras.preprocessing.image.img_to_array(img)
print(x.shape)
input = tf.expand_dims(x, axis=0)
print(input.shape)

output = tf.keras.layers.GlobalMaxPool2D()(input)
print("After applying GlobalMaxPool2D : ", output.numpy())

Output

(256, 256, 3)
(1, 256, 256, 3)

After applying GlobalMaxPool2D :  [[255. 254. 214.]]

As the input image is having 3 channels so GlobalMaxPool2D provides 3 values maximum of each channel

Now lets apply tf.keras.layers.Conv2D layer to increase number of channels before providing input to GlobalMaxPool2D

  
import tensorflow as tf
import matplotlib.pyplot as

file = tf.keras.utils.get_file(
    "cat.png",
    "https://storage.googleapis.com/gcptutorials.com/examples/cat.png")

img = tf.keras.preprocessing.image.load_img(file)

x = tf.keras.preprocessing.image.img_to_array(img)
print(x.shape)
x = tf.expand_dims(x, axis=0)
print(x.shape)

input = tf.keras.layers.Conv2D(filters=5, kernel_size=(2,2), strides=(1,1))(x)
print("After applying Conv2D :",input.shape)

output = tf.keras.layers.GlobalMaxPool2D()(input)
print("After applying GlobalMaxPool2D :", output.numpy())
  
  
Output

(256, 256, 3)
(1, 256, 256, 3)

After applying Conv2D : (1, 255, 255, 5)

After applying GlobalMaxPool2D : [[254.3581  390.10107   7.68734 188.51495  51.93805]]

tf.keras.layers.Conv2D produced 5 channels as we provided filters=5 in arguments and than we provided output of Conv2D to GlobalMaxPool2D which produced 5 values corresponding to max of each of 5 channels.

Categories: TensorFlow