Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a tensorflow equivalent to np.empty?

Numpy has this helper function, np.empty, which will:

Return a new array of given shape and type, without initializing entries.

I find it pretty useful when I want to create a tensor using tf.concat since:

The number of dimensions of the input tensors must match, and all dimensions except axis must be equal.

So it comes in handy to start with an empty tensor of an expected shape. Is there any way to achieve this in tensorflow?

[edit]

A simplified example of why I want this

    netInput = np.empty([0, 4])
    netTarget = np.empty([0, 4])
    inputWidth = 2

    for step in range(data.shape.as_list()[-2]-frames_width-1):
        netInput = tf.concat([netInput, data[0, step:step + frames_width, :]], -2)
        target = tf.concat([target, data[0, step + frames_width + 1:step + frames_width + 2, :]], -2)

In this example, if netInput or netTarget are initialized, I'll be concatenating an extra example with that initialization. And to initialize them with the first value, I need to hack the loop. Nothing mayor, I just wondered if there is a 'tensorflow' way to solve this.

like image 780
Andrés Marafioti Avatar asked May 22 '18 08:05

Andrés Marafioti


People also ask

How do you initialize an empty tensor in TensorFlow?

If you use tf. global_variables_initializer() to initialize your variables, disable putting your variable in the list of global variables during initialization by setting collections=[] . Here np. empty is provided to x only to specify its shape and type, not for initialization.

How do you make an empty tensor?

If you want a Tensor with no data in it. you can create a Tensor with 0 size: x = torch. empty(0, 3) .

How do I know if my tensor is empty?

To know whether an allocated tensor has zero elements, use numel() To know whether a tensor is allocated and whether it has zero elements, use defined() and then numel()

Does TensorFlow include NumPy?

TensorFlow implements a subset of the NumPy API, available as tf. experimental. numpy . This allows running NumPy code, accelerated by TensorFlow, while also allowing access to all of TensorFlow's APIs.


2 Answers

If you're creating an empty tensor, tf.zeros will do

>>> a = tf.zeros([0, 4])
>>> tf.concat([a, [[1, 2, 3, 4], [5, 6, 7, 8]]], axis=0)
<tf.Tensor: shape=(2, 4), dtype=float32, numpy=
array([[1., 2., 3., 4.],
       [5., 6., 7., 8.]], dtype=float32)>
like image 153
joel Avatar answered Oct 09 '22 18:10

joel


In TF 2,

tensor = tf.reshape(tf.convert_to_tensor(()), (0, n))

worked for me.

like image 31
Sibbs Gambling Avatar answered Oct 09 '22 17:10

Sibbs Gambling