edo1z blog

プログラミングなどに関するブログです

TensorFlow - tf.nn.max_pool(value, ksize, strides, padding, data_format='NHWC', name=None)

tf.nn.max_pool(value, ksize, strides, padding, data_format='NHWC', name=None)

  • value: A 4-D Tensor with shape [batch, height, width, channels] and type tf.float32.
  • ksize: A list of ints that has length >= 4. The size of the window for each dimension of the input tensor.
  • strides: A list of ints that has length >= 4. The stride of the sliding window for each dimension of the input tensor.
  • padding: A string, either 'VALID' or 'SAME'. The padding algorithm. See the comment here
  • data_format: A string. 'NHWC' and 'NCHW' are supported.
  • name: Optional name for the operation.

max poolingは、特定の領域から最大の数字を取り出します。ksizeが領域の大きさ、stridesが間隔です。ksizeが[1, 2, 2, 1]で、stridesが[1, 2, 2, 1]であれば、2 x 2のmax poolingです。2 x 2の領域から最大値をとります。間隔が2の場合出力サイズは半分になります。ksizeが[1, 3, 3, 1]で、stridesが[1, 2, 2, 1]の場合、3 x 3の領域から最大値をとり、間隔が2になるので、出力サイズは半分のままですが、数値を広範囲から取得することになるので、よりちょっとの差に動じなくなります。

tf.nn.max_poolの動きを確認してみます。 この画像を使います。

画像を読み込む

とりあえず画像を読み込んで、shapeを表示させてみます。

import tensorflow as tf
import numpy as np
from PIL import Image

fpath = './img/sample_pic.jpg'
jpg = tf.read_file(fpath)
img_arr = tf.image.decode_jpeg(jpg, channels=3)

with tf.Session() as sess:
    img = sess.run(img_arr)
    print(img.shape)

結果

(600, 800, 3)

Max poolingしてみる

import tensorflow as tf
import numpy as np
from PIL import Image

fpath = './img/sample_pic.jpg'
jpg = tf.read_file(fpath)
img_arr = tf.image.decode_jpeg(jpg, channels=3)
img_4d = tf.cast(tf.reshape(img_arr, [1, 600, 800, 3]), tf.float32)
pool = tf.nn.max_pool(img_4d, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')

with tf.Session() as sess:
    img, pool = sess.run([img_arr, pool])
    print(img.shape)
    print(pool.shape)

結果

(600, 800, 3)
(1, 300, 400, 3)

おーできてるっぽい。

画像を表示してみる。

Image.fromarray(np.uint8(pool.reshape(pool.shape[1:4]))).save('./img/maxpool1.jpg')

結果

では、わかり易くksizeを[1, 10, 10, 1]でやってみます。

import tensorflow as tf
import numpy as np
from PIL import Image

fpath = './img/sample_pic.jpg'
jpg = tf.read_file(fpath)
img_arr = tf.image.decode_jpeg(jpg, channels=3)
img_4d = tf.cast(tf.reshape(img_arr, [1, 600, 800, 3]), tf.float32)
pool = tf.nn.max_pool(img_4d, [1, 10, 10, 1], [1, 2, 2, 1], 'SAME')

with tf.Session() as sess:
    img, pool = sess.run([img_arr, pool])
    print(img.shape)
    print(pool.shape)
    Image.fromarray(np.uint8(pool.reshape(pool.shape[1:4]))).save('./img/maxpool2.jpg')

結果

(600, 800, 3)
(1, 300, 400, 3)