Skip to content

Instantly share code, notes, and snippets.

@ialhashim
Last active October 19, 2020 14:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ialhashim/864574315c133e5957463d2753c57499 to your computer and use it in GitHub Desktop.
Save ialhashim/864574315c133e5957463d2753c57499 to your computer and use it in GitHub Desktop.
Resize or interpolate tensors to any spatial dimension in Keras
import tensorflow as tf
import keras.backend as K
from keras.layers import Lambda
#
# Keras + TensorFlow
# Resize 'tensorA' to be of the same size as 'tensorB' using 'tf.image.resize_bilinear'
# Very useful for skip-connections and 'Concatenate' layers that might complain about being off by one column
# Only works when dimensions are provided since we use ' K.int_shape' that returns the static shape
#
def ResizeLayerLike(tensorA, tensorB):
sB = K.int_shape(tensorB)
def resize_like(tensor, sB): return tf.image.resize_bilinear(tensor, sB[1:3], align_corners=True)
return Lambda(resize_like, arguments={'sB':sB})(tensorA)
@AhmadMoussa
Copy link

Thanks for this gist, only change I had to make was instead of tf.image.resize_bilinear I needed to use tf.compat.v1.image.resize_bilinear. Weird that this isn't already a standard layer in tensorflow/keras.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment