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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


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}))





I think you can't find a static shape for a placeholder, because it's not defined. So that's why you can only find dynamic shape (tf.shape(tensor)
– guillaumegg10
2 days ago





Why do you pass shapes when sess.run(a, feed_dict={a: x}) executes ? The type of shapes is [<tf.Tensor 'unstack:0' shape=() dtype=int32>, 128]
– Mohan Radhakrishnan
2 days ago




sess.run(a, feed_dict={a: x})


[<tf.Tensor 'unstack:0' shape=() dtype=int32>, 128]





@MohanRadhakrishnan Because I want to evaluate the shapes since it contains a Tensorflow operation.
– aligholamee
2 days ago







@guillaumegg10 Nevermind. the condition inside get_shape handles that one.
– aligholamee
2 days ago




1 Answer
1



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.


s[0]


int


tf.constant(s[0])


s[0]






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

415 Unsupported Media Type while sending json file over REST Template

PHP parse/syntax errors; and how to solve them?