Skip to content

Random numbers with None value in shape #373

Closed

Description

@bayerj

There are several use cases where the shape of random numbers is to be determined at runtime. E.g. for variational auto encoder or injection of noise into an MLPs units. As of now, this seems not possible in an elegant way with tensorflow:

import tensorflow as tf
x = tf.placeholder('float32', [None, 784])
noised = x + tf.random_normal(x.get_shape())

The above throws this traceback. I have to replace None above with a number known before runtime. But then I have to fix my batch size beforehand (to which the None corresponds) and need different expressions for each batch size.

Activity

  1. rafaljozefowicz commented on Nov 28, 2015

    @rafaljozefowicz

    TF.shape(x) should work instead.

  2. bayerj commented on Nov 29, 2015

    @bayerj
    Author

    Thank you!

  3. guerrillacaptain commented on Nov 29, 2017

    @guerrillacaptain

    like

  4. idofr commented on May 14, 2019

    @idofr

    Uh! that's actually really helpful :) thanks. Why is that?

  5. added a commit that references this issue on Dec 6, 2019
  6. added a commit that references this issue on Jan 23, 2020
  7. BBillot commented on Dec 14, 2020

    @BBillot

    Sorry but this doesn't seem to be working with TF2, as placeholders don't exist anymore.

    Using None to specify the shape doesn't work either, i.e,
    tf.random.normal((None, 784))
    gives
    ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor.

    Any idea, apart from using tf.shape() on another tensor of the model to extract the batchsize ?

  8. JJKK1313 commented on Aug 8, 2021

    @JJKK1313

    Also having the same problem,
    tf.shape() returns some wierd number for placeholder's shape.

        def call(self, inputs, training=True, **kwargs):
            print(inputs)
            print(tf.shape(inputs), inputs.shape)
    

    gives me:

    Tensor("Placeholder:0", shape=(None, 128, 128, 3), dtype=float32)
    Tensor("RandomHSVPreprocessor/Shape:0", shape=(4,), dtype=int32) (None, 128, 128, 3)
    
  9. added a commit that references this issue on May 15, 2026
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions