Skip to content

tf.reshape does not accept Dimension objects for the shape parameter #11974

Closed

Description

@joseph-valles

Please go to Stack Overflow for help and support:

https://stackoverflow.com/questions/tagged/tensorflow

If you open a GitHub issue, here is our policy:

  1. It must be a bug or a feature request.
  2. The form below must be filled out.
  3. It shouldn't be a TensorBoard issue. Those go here.

Here's why we have that policy: TensorFlow developers respond to issues. We want to focus on work that benefits the whole community, e.g., fixing bugs and adding features. Support only helps individuals. GitHub also notifies thousands of people when issues are filed. We want them to see you communicating an interesting problem, rather than being redirected to Stack Overflow.


System information

  • Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Yes
  • OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Windows 10 x64
  • TensorFlow installed from (source or binary): binary
  • TensorFlow version (use command below): 1.2.1
  • Python version: 3.6.1 (Anaconda 4.4.0 64-bit)
  • Bazel version (if compiling from source):
  • CUDA/cuDNN version:
  • GPU model and memory: GTX 780
  • Exact command to reproduce: tf.reshape()

You can collect some of this information using our environment capture script:

https://github.com/tensorflow/tensorflow/tree/master/tools/tf_env_collect.sh

You can obtain the TensorFlow version with

python -c "import tensorflow as tf; print(tf.GIT_VERSION, tf.VERSION)"

Describe the problem

Describe the problem clearly here. Be sure to convey here why it's a bug in TensorFlow or a feature request.

tf.reshape does not accept a list with mixed Integer and Dimension() as elements for the shape parameter. It should accept shapes that have Dimension as elements since tensor shapes consist of dimensions. Specifically, tf.tensor.shape returns a list of Dimensions, therefore using a similar object to specify a shape in tf.reshape should not cause an error.

Source code / logs

Include any logs or source code that would be helpful to diagnose the problem. If including tracebacks, please include the full traceback. Large logs and files should be attached. Try to provide a reproducible test case that is the bare minimum necessary to generate the problem.

Example code:

X = tf.placeholder("float", [1,784])
X = tf.reshape(X, [1, X.shape[-1]])

results in

TypeError: Failed to convert object of type <class 'list'> to Tensor. Contents: [1, Dimension(784)]. Consider casting elements to a supported type.

This is rectified by casting X.shape[-1] to int before passing to tf.reshape.

A similar unrelated issue is that X.shape returns (784,) while it should return (1,784). This requires reshaping to turn the placeholder back into a 2D tensor. I haven't determined if this is a bug but it occurs when the tensor is explicitly specified as a 2D tensor so it is probably worth changing.

Activity

  1. yaroslavvb commented on Aug 2, 2017

    @yaroslavvb
    Contributor

    One fix could be to add some code before this line that casts all tf.Dimension objects in the list to Python int

  2. added
    stat:contribution welcome
    on Aug 2, 2017
  3. shivaniag commented on Aug 2, 2017

    @shivaniag
    Contributor

    We currently don't have anybody working on this. It would be great if you could help us by working on this and submitting a PR. Let us know if you need further clarification. Thanks!

  4. pmccarter commented on Aug 3, 2017

    @pmccarter

    I'd be interested in working on this, might take a few days to figure out dev workflow.

  5. yaroslavvb commented on Aug 3, 2017

    @yaroslavvb
    Contributor

    I think you basically need to do something along the lines of:

    if hasattr(arr, "__len__") and len(arr)<=8:
      for i in range(len(arr)):
        arr[i] = int(arr[i]) if instanceof(arr[i], Dimension) else arr[i]
    

    And then run the tests and see if something breaks. The len restriction is because this only really matters for shapes and TF has rank limit of 8

  6. facaiy commented on Aug 9, 2017

    @facaiy
    Member

    Hi, @pmccarter . Because tf.reshape is generated automatically, and the implementation is written by C++, hence the question is more difficult to debug than I expected. I opened a PR #12127 to take a try to fix it. If your work has not been started yet, is it OK to link the PR to the issue? Thanks.

  7. yaroslavvb commented on Aug 9, 2017

    @yaroslavvb
    Contributor

    @facaiy this is a Python specific issue so it needs to be at Python side. Look at the stack trace of failing reshape to see where it's happening. The Python layer calls tensor_util.make_tensor_proto which calls numpy.asarray on the result. Numpy asarray tries to figure out dtype of the list, and because it doesn't know about tf.Dimension, it makes it type "np.object" which corresponds to "tf.string".

    The ideal way to fix it would be to figure out how to modify tf.Dimension object so that np.asarray would recognize them as integer. IE, you want

    np.asarray([1,tf.Dimension(1)])

    to return

    array([1, 1]

    instead of

    array([1, Dimension(1)], dtype=object)

    If that's not possible, the next best thing would be to have special case for tf.Dimension object to convert them to int just before np.asarray call. You would want to special-case this for length <=8 since we don't need larger ranks for shape calculations, and this would avoid performance penalty for more general arrays

  8. facaiy commented on Aug 9, 2017

    @facaiy
    Member

    @yaroslavvb Thanks for your suggestion! Yes, I agree with you that casting object to string is a really awkward solution.

    As for the two solutions you advised, I will take a try:

    1. Find a way to make np.asarray recognize tf.Dimension as int, or
    2. Cast tf.Dimension to int before np.asarray call.
  9. facaiy commented on Aug 9, 2017

    @facaiy
    Member

    Hi, @yaroslavvb .

    If I understand correctly, [1, Dimension(1)] doesn't go np.asarray route,

      if isinstance(values, (np.ndarray, np.generic)):
        if dtype:
          nparray = values.astype(dtype.as_numpy_dtype)
        else:
          nparray = values
      elif callable(getattr(values, "__array__", None)):
        # If a class has the __array__ method, then it is possible to convert
        # to numpy array.
        nparray = np.asarray(values, dtype=dtype)
      else:

    In fact, it goes the last branch. In the route, [1, Dimension(1)] is treated as a list of objects. Then each object is treated as string, see:

      if numpy_dtype == dtypes.string and not isinstance(values, np.ndarray):
        proto_values = _FlattenToStrings(values)
    
        # At this point, values may be a list of objects that we could not
        # identify a common type for (hence it was inferred as
        # np.object/dtypes.string).  If we are unable to convert it to a
        # string, we raise a more helpful error message.
        #
        # Ideally, we'd be able to convert the elements of the list to a
        # common type, but this type inference requires some thinking and
        # so we defer it for now.
        try:
          str_values = [compat.as_bytes(x) for x in proto_values]
        except TypeError:
          raise TypeError("Failed to convert object of type %s to Tensor. "
                          "Contents: %s. Consider casting elements to a "
                          "supported type." % (type(values), values))
        tensor_proto.string_val.extend(str_values)
        return tensor_proto

    That's why I think obj.str() might fix the issue. However, the solution is worse in performance. Do you have a better suggestion? Thanks.

  10. yaroslavvb commented on Aug 9, 2017

    @yaroslavvb
    Contributor

    Hm, I may be missing where obj.str is turned into int. Anyway, the performance should be OK if you restrict it to tensors of length <= 8

  11. pmccarter commented on Aug 9, 2017

    @pmccarter

    np.array([1, tf.Dimension(784)], dtype=tf.int32) returns array([1, 2], dtype=int32), so maybe a solution would be to set the dtype to int if it is None and values is a list mix of numbers and Dimensions?

  12. facaiy commented on Aug 10, 2017

    @facaiy
    Member

    Thanks, all.

    @pmccarter 's advice sounds attractive, I'd like to dig deeper.

    In [5]: np.array([1, tf.Dimension(784)], dtype=np.int32)
    Out[5]: array([  1, 784], dtype=int32)
  13. pmccarter commented on Aug 10, 2017

    @pmccarter

    What about defining a thin ungenerated reshape() function that delegates to the generated function, and coerces the shape to a 2d int list if possible?

  14. yaroslavvb commented on Aug 10, 2017

    @yaroslavvb
    Contributor

    @pmccarter actually I like that idea . It would have much less side-effects. We already have Python ops which are essentially 1 line wrappers over underlying generated ops, like reduce sum

    return gen_math_ops._sum(

  15. pmccarter commented on Aug 10, 2017

    @pmccarter

    Cool I can probably get a pull request in tomorrow.

  16. CharlesMei commented on Sep 1, 2017

    @CharlesMei

    X.get_shape().as_list()[-1]

  17. RoboEvangelist commented on Mar 7, 2018

    @RoboEvangelist

    I am using tensorflow 1.4.1, and I am still having the same problem with models/official/resnet/resnet.py

    TypeError: Failed to convert object of type <class 'tensorflow.python.data.ops.dataset_ops.PrefetchDataset'> to Tensor. Contents: <PrefetchDataset shapes: ((?, 32, 32, 3), (?, 10)), types: (tf.float32, tf.float32)>. Consider casting elements to a supported type.

    When will this be fixed? I would not want to spend time fixing this myself, please

  18. facaiy commented on Mar 7, 2018

    @facaiy
    Member

    @RoboEvangelist The bug has been fixed. And about your problem, I don't think so. As the exception said, you mistake Dataset as Tensor.

  19. RoboEvangelist commented on Mar 12, 2018

    @RoboEvangelist

    @facaiy I just upgraded to tensorflow 1.6.0, and I don't have the problem anymore. It is still a bug in tensorflow 1.4.1 due to my experience

  20. dhinar1991 commented on Apr 1, 2018

    @dhinar1991

    @yaroslavvb @mrry I have a completely different error that says

    Failed to convert object of type <class 'werkzeug.datastructures.File.Storage> to tensor.

    TypeError: Failed to convert object of type (class'werkzeug.datastructures.File.Storage') to tensor. Contents: (Filestorage: u'File.txt' ('text/plain')). Consider casting elements to a supported type

    below is the client file with flask framework for tensorflow serving running inside a docker. https://github.com/tensorflow/tensorflow/issues/18157

    
    tf.app.flags.DEFINE_string('server', 'localhost:9000', 'PredictionService host:port')
    FLAGS = tf.app.flags.FLAGS
    
    app = Flask(__name__)
    
    class mainSessRunning():
        
        def __init__(self):
            host, port = FLAGS.server.split(':')
            channel = implementations.insecure_channel(host, int(port))
            self.stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
    
            self.request = predict_pb2.PredictRequest()
            self.request.model_spec.name = 'example_model'
            self.request.model_spec.signature_name = 'prediction'
    
        def inference(self, val_x):
            #temp_data = numpy.random.randn(100, 3).astype(numpy.float32)
            #temp_data = val_x.astype(np.float32).reshape(-1, 3)
            data = val_x
            self.request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(data))
            result = self.stub.Predict(self.request, 5.0)
            return result
    
    run = mainSessRunning()
    
    print("Initialization done. ")
    
    # Define a route for the default URL, which loads the form
    @app.route('/inference', methods=['POST'])
    def inference():
        request_data = request.files['file']
        result = run.inference(request_data)
        r = json_format.MessageToJson(result)
        return jsonify({'result':r})
    
  21. giladsharir commented on Apr 3, 2018

    @giladsharir

    I still have this issue, using tensorflow 1.7

  22. Duke-ding commented on Apr 8, 2018

    @Duke-ding

    i also have this issue

  23. Duke-ding commented on Apr 8, 2018

    @Duke-ding

    def read_and_decode(filename):
    filename_quece = tf.train.string_input_producer([filename])#读入流中

    reader = tf.TFRecordReader()
    _,serialized_example = reader.read(filename_quece)#返回文件名和文件
    features = tf.parse_single_example(serialized_example,features={
        'label':tf.FixedLenFeature([],tf.int64),
        'img_raw' : tf.FixedLenFeature([],tf.string),
    })
    img = tf.decode_raw(features['img_raw'],tf.uint8)
    img = tf.reshape(img,[256,256,3])
    img = tf.cast(img,tf.float32)*(1./255) - 0.5
    label = tf.cast(features['label'],tf.int32)
    
    return img,label
    

    if name == 'main':
    img,label = read_and_decode("train_data.tfrecords")

    print(img.shape)

    print(img[0])

    img_batch,label_batch = tf.train.shuffle_batch([img,label],batch_size=32,capacity=200000,
                                                   min_after_dequeue=100)
    

    img_batch = tf.reshape(img_batch,[None,2562563])

    x = tf.placeholder(tf.float32,[None,256*256*3])
    
    w = tf.Variable(tf.zeros([256*256*3,45]))
    b = tf.Variable(tf.zeros([45]))
    
    y = tf.nn.softmax(tf.matmul(x,w)+b)
    y_ = tf.placeholder(tf.float32,[None])
    
    cross_entropy = -tf.reduce_sum(y_*tf.log(y))
    
    train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
    
    
    #初始化所有的op
    init = tf.global_variables_initializer()
    

    with tf.Session() as sess:
        sess.run(init)
        coord=tf.train.Coordinator()#创建一个协调器,管理线程
        #启动队列
    
        threads = tf.train.start_queue_runners(sess=sess,coord=coord,start=True)
        for i in range(10):
            X_train_batch,y_train_batch = sess.run([img_batch,label_batch])
           
            sess.run(train_step,feed_dict={x:X_train_batch,y_:y_train_batch})
            print(X_train_batch.shape,y_train_batch.shape)
            print(X_train_batch)
        
        coord.request_stop()
        coord.join(threads)
    

    ValueError: Cannot feed value of shape (32, 256, 256, 3) for Tensor 'Placeholder_2:0', which has shape '(?, 196608)'
    I can't deal with this issue

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    stat:contribution welcome

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions