1

I have some data that I want to process before feeding/training a model. For this example I want to do a max pool 2d. I wrote a short function to do that with tensorflow.

import tensorflow
import tensorflow.nn as nn

def _tfMaxPool(arr, pool=(4,4), sess=None):
    op = nn.max_pool(arr, (1, 1, pool[0], 1), (1, 1, pool[0], 1 ), padding="VALID")
    op = nn.max_pool(op, (1, 1, 1, pool[1]), (1, 1, 1, pool[1]), padding="VALID")
    if sess is None:
        sess = tensorflow.Session();

    return sess.run(op)

The problem is this can add nodes to my graph each time, which seems to clutter my session. One alternative way is to create a model.

import keras

seq = keras.Sequential([ 
            keras.layers.InputLayer((1, 512, 512)), 
            keras.layers.MaxPool2D((4, 4), (4, 4), data_format="channels_first")
                     ])
def _tfMaxPool2(arr, pool=(4,4), sess=None):
    swapped = arr.swapaxes(0,1)
    return seq.predict(swapped).swapaxes(0,1)

The model is nearly exactly like what I want, but I think I am missing something fundamental.

1
  • I still want to know how to let an op create a layer that would be reused. The Op adds a new node to the graph every time when it was called, regardless of weather reuse=True is set. Commented Jul 15, 2020 at 20:37

1 Answer 1

1

Why don't you reuse your graph with various input? In the following code,tfMaxpool is defined only once.

def _tfMaxPool(arr, pool=(4,4)):
    op = nn.max_pool(arr, (1, 1, pool[0], 1), (1, 1, pool[0], 1 ), padding="VALID")
    op = nn.max_pool(op, (1, 1, 1, pool[1]), (1, 1, 1, pool[1]), padding="VALID")

    return op

input = tf.placeholder()
output = _tfMaxPool(input)

with tf.Session() as sess:
    sess.run(output, feed_dict={input:arr1})
    sess.run(output, feed_dict={input:arr2})
1
  • I will try this, I think this is exactly what I was looking for.
    – matt
    Commented Oct 29, 2018 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.