user9200689
user9200689

Reputation: 129

TensorFlow to Keras Tensor

I'm tyring to mix TensorFlow tensor and Keras tensor using this blog's info:

But the problems occurs at the last layer when output needs to be Keras tensor not TensorFlow tensor. Is there a simple way to just convert? Or is there a Keras function that does bilinear resize?

finalOut = predict_flow2
finalOut = tf.image.resize_bilinear(finalOut, tf.stack([h, w]), align_corners=True)
model = Model(input=input, output=finalOut)
model.summary()

Error msg:

TypeError: Output tensors to a Model must be Keras tensors. Found: Tensor("ResizeBilinear:0", shape=(?, 320, 1152, 2), dtype=float32)

Upvotes: 5

Views: 7975

Answers (1)

ldavid
ldavid

Reputation: 2552

I mean, there's no way for me to know what is predict_flow2. I'm going to suppose it's a Keras tensor, but you can generalize my answer if it's not.

A model is composed of layers, which aren't exactly functions. To use TF functions (or any functions) like this, you need to wrap them around the Lambda layer:

import numpy as np
import tensorflow as tf
from keras import Input, Model
from keras.layers import Lambda


x = Input((224, 224, 3))
h, w = 299, 299

y = Lambda(lambda inputs: tf.image.resize_bilinear(inputs,
                                                   tf.stack([h, w]),
                                                   align_corners=True))(x)
model = Model(inputs=x, output=y)
model.summary()

p = model.predict(np.random.randn(1, 224, 224, 3))
print('shape:', p.shape)

Which will output:

Using TensorFlow backend.
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 224, 224, 3)       0         
_________________________________________________________________
lambda_1 (Lambda)            (None, 299, 299, 3)       0         
=================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0
_________________________________________________________________

shape: (1, 299, 299, 3)

Upvotes: 5

Related Questions