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.