hexpheus
hexpheus

Reputation: 761

Tensorflow dynamic/static shapes: Can not convert a int into a Tensor or Operation

In this code, I'm getting the dynamic and static shapes of an input tensor. The problem is that although my Numpy generated array should be considered as a tensor, it does not! Any help will be appreciated!

import tensorflow as tf
import numpy as np


def get_shape(tensor):
    """
        Return the static shape of a tensor only when available
    """

    static_shape = tensor.shape.as_list()
    dynamic_shape = tf.unstack(tf.shape(tensor))

    dim = [s[1] if s[0] is None else s[0] for s in zip(static_shape, dynamic_shape)]

    return dim


a = tf.placeholder(dtype=tf.float32, shape=[None, 128])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    x = np.random.normal(loc=0.5, scale=0.3, size=[150, 128])
    shapes = get_shape(a)
    print(sess.run(shapes, feed_dict={a: x}))

Upvotes: 0

Views: 521

Answers (1)

Vlad-HC
Vlad-HC

Reputation: 4757

Just change the line

dim = [s[1] if s[0] is None else s[0] for s in zip(static_shape, dynamic_shape)]

to

 dim = [s[1] if s[0] is None else tf.constant(s[0]) for s in zip(static_shape, dynamic_shape)]

The thing is that you s[0] in this case refers to int type, because it's a static shape. But here we need a valid tensorflow operation. Using tf.constant(s[0]) instead of s[0] solves the problem.

Upvotes: 1

Related Questions