Why tensorflow may want to specify dynamic dimension - python

I have an existing complex model. Inside there is tensor x with shape (None, 128, 128, 3). First axis has dynamic shape, that should be materialized when batch is passed to feed_dict in session.run. However when I attempt to define broadcast operation to shape of x:
y = tf.broadcast_to(z, (x.shape[0], x.shape[1], x.shape[2], 1))
Exception is raised:
Failed to convert object of type <class 'tuple'> to
Tensor. Contents: (Dimension(None), Dimension(128),
Dimension(128), 1). Consider casting elements to a supported type.
Exception occurs when creating model, not when running it. Converting first element to number helps, but this is not the solution.

The .shape attribute gives you the shape known at graph construction time, which is a tf.TensorShape structure. If the shape of x were fully known, you could get your code to work as follows:
y = tf.broadcast_to(z, (x.shape[0].value, x.shape[1].value, x.shape[2].value, 1))
However, in your case x has an unknown first dimension. In order to use the actual tensor shape as a regular tf.Tensor (with value only known at runtime), you can use tf.shape:
x_shape = tf.shape(x)
y = tf.broadcast_to(z, (x_shape[0], x_shape[1], x_shape[2], 1))

Related

tf.reshape(tensor, [-1]) VS tf.reshape(tensor, -1)

What is the difference between these two?
1- tf.reshape(tensor, [-1])
2- tf.reshape(tensor, -1)
I can not find any difference between these two, but when I use -1 without brackets, an error occurs when trying to map the function to a TensorSliceDataset.
Here is the simplified version of the code:
def reshapeME(tensor):
reshaped = tf.reshape(tensor,-1)
return reshaped
new_y_test = y_test.map(reshapeME)
and here is the Error:
ValueError: Shape must be rank 1 but is rank 0 for '{{node Reshape}} = Reshape[T=DT_FLOAT, Tshape=DT_INT32](one_hot, Reshape/shape)' with input shapes: [6], [].
If I add the bracket, there is no error. Also, there is no error when the function is used by calling and feeding a tensor.
tf.reshape expects a tensor or tensor-like variable as the shape in Graph mode:
A Tensor. Must be one of the following types: int32, int64. Defines the shape of the output tensor.
So, simple scalars will not work in this case. The map function of a tf.data.Dataset is always executed in Graph mode:
Note that irrespective of the context in which map_func is defined
(eager vs. graph), tf.data traces the function and executes it as a
graph.

How to create a 1-D range tensor when dimension is Unknown?

I have a n-D array. I need to create a 1-D range tensor based on dimensions.
for an example:
x = tf.placeholder(tf.float32, shape=[None,4])
r = tf.range(start=0, limit=, delta=x.shape[0],dtype=tf.int32, name='range')
sess = tf.Session()
result = sess.run(r, feed_dict={x: raw_lidar})
print(r)
The problem is, x.shape[0] is none at the time of building computational graph. So I can not build the tensor using range. It gives an error.
ValueError: Cannot convert an unknown Dimension to a Tensor: ?
Any suggestion or help for the problem.
Thanks in advance
x.shape[0] might not exist yet when running this code is graph mode. If you want a value, you need to use tf.shape(x)[0].
More information about that behaviour in the documentation for tf.Tensor.get_shape. An excerpt (emphasis is mine):
tf.Tensor.get_shape() is equivalent to tf.Tensor.shape.
When executing in a tf.function or building a model using tf.keras.Input, Tensor.shape may return a partial shape (including None for unknown dimensions). See tf.TensorShape for more details.
>>> inputs = tf.keras.Input(shape = [10])
>>> # Unknown batch size
>>> print(inputs.shape)
(None, 10)
The shape is computed using shape inference functions that are registered for each tf.Operation.
The returned tf.TensorShape is determined at build time, without executing the underlying kernel. It is not a tf.Tensor. If you need a shape tensor, either convert the tf.TensorShape to a tf.constant, or use the tf.shape(tensor) function, which returns the tensor's shape at execution time.

In Keras, how to use Reshape layer with None dimension?

In my model, a layer has a shape of [None, None, 40, 64]. I want to reshape this into [None, None, 40*64]. However, if I simply do the following:
reshaped_layer = Reshape((None, None, 40*64))(my_layer)
It throws an error complaining that None values not supported.
(Just to be clear, this is not tf.keras, this is just Keras).
First of all, the argument you pass to Reshape layer is the desired shape of one sample in the batch and not the whole batch of samples. So since each of the samples in the batch is a 3D tensor, the argument must also consider only that 3D tensor (i.e. excluding the batch axis).
Second, you can use -1 as the shape of only one axis. It tells to the Reshape layer to automatically infer the shape of that axis based on the shape of other axes you provide. So considering these two points, it would be:
reshaped_out = Reshape((-1, 40*64))(layer_out)

Keras LSTM Input - ValueError: Error when checking input: expected input_1 to have 3 dimensions, but got array with shape (1745, 1)

My Keras RNN code is as follows:
def RNN():
inputs = Input(shape = (None, word_vector_size))
layer = LSTM(64)(inputs)
layer = Dense(256,name='FC1')(layer)
layer = Dropout(0.5)(layer)
layer = Dense(num_classes,name='out_layer')(layer)
layer = Activation('softmax')(layer)
model = Model(inputs=inputs,outputs=layer)
return model
I'm getting the error when I call model.fit()
model.fit(np.array(word_vector_matrix), np.array(Y_binary), batch_size=128, epochs=10, validation_split=0.2, callbacks=[EarlyStopping(monitor='val_loss',min_delta=0.0001)])
Word_vector_matrix is a 3-dim numpy array.
I have printed the following :
print(type(word_vector_matrix), type(word_vector_matrix[0]), type(word_vector_matrix[0][0]), type(word_vector_matrix[0][0][0]))
and the answer is :
<class 'numpy.ndarray'> <class 'numpy.ndarray'> <class 'numpy.ndarray'> <class 'numpy.float32'>
It's shape is 1745 x sentence length x word vector size.
The sentence length is variable and I'm trying to pass this entire word vector matrix to the RNN, but I get the error above.
The shape is printed like:
print(word_vector_matrix.shape)
The answer is (1745,)
The shape of the nested arrays are printed like:
print(word_vector_matrix[10].shape)
The answer is (7, 300)
The first number 7 denotes the sentence length, which is variable and changes for each sentence, and the second number is 300, which is fixed for all words and is the word vector size.
I have converted everything to np.array() as suggested by the other posts, but still the same error. Can someone please help me. I'm using python3 btw. The similar thing is working in python2 for me, but not in python3. Thanks!
word_vector_matrix is not a 3-D ndarray. It's a 1-D ndarray of 2-D arrays. This is due to variable sentence length.
Numpy allows ndarray to be list-like structures that may contain a complex element (another ndarray). In Keras however, the ndarray must be converted into a Tensor (which has to be a "mathematical" matrix of some dimension - this is required for the sake of efficient computation).
Therefore, each batch must have fixed size sentences (and not the entire data).
Here are a few alternatives:
Use batch size of 1 - simplest approach, but impedes your network's convergence. I would suggest to only use it as a temporary sanity check.
If sequence length variability is low, pad all your batches to be of the same length.
If sequence length variability is high, pad each batch with the max length within that batch. This would require you to use a custom data generator.
Note: After you padded your data, you need to use Masking, so that the padded part will be ignored during training.

Tensor with unspecified dimension in tensorflow

I'm playing around with tensorflow and ran into a problem with the following code:
def _init_parameters(self, input_data, labels):
# the input shape is (batch_size, input_size)
input_size = tf.shape(input_data)[1]
# labels in one-hot format have shape (batch_size, num_classes)
num_classes = tf.shape(labels)[1]
stddev = 1.0 / tf.cast(input_size, tf.float32)
w_shape = tf.pack([input_size, num_classes], 'w-shape')
normal_dist = tf.truncated_normal(w_shape, stddev=stddev, name='normaldist')
self.w = tf.Variable(normal_dist, name='weights')
(I'm using tf.pack as suggested in this question, since I was getting the same error)
When I run it (from a larger script that invokes this one), I get this error:
ValueError: initial_value must have a shape specified: Tensor("normaldist:0", shape=TensorShape([Dimension(None), Dimension(None)]), dtype=float32)
I tried to replicate the process in the interactive shell. Indeed, the dimensions of normal_dist are unspecified, although the supplied values do exist:
In [70]: input_size.eval()
Out[70]: 4
In [71]: num_classes.eval()
Out[71]: 3
In [72]: w_shape.eval()
Out[72]: array([4, 3], dtype=int32)
In [73]: normal_dist.eval()
Out[73]:
array([[-0.27035281, -0.223277 , 0.14694688],
[-0.16527176, 0.02180306, 0.00807841],
[ 0.22624688, 0.36425814, -0.03099642],
[ 0.25575709, -0.02765726, -0.26169327]], dtype=float32)
In [78]: normal_dist.get_shape()
Out[78]: TensorShape([Dimension(None), Dimension(None)])
This is weird. Tensorflow generates the vector but can't say its shape. Am I doing something wrong?
As Ishamael says, all tensors have a static shape, which is known at graph construction time and accessible using Tensor.get_shape(); and a dynamic shape, which is only known at runtime and is accessible by fetching the value of the tensor, or passing it to an operator like tf.shape. In many cases, the static and dynamic shapes are the same, but they can be different - the static shape can be partially defined - in order allow the dynamic shape to vary from one step to the next.
In your code normal_dist has a partially-defined static shape, because w_shape is a computed value. (TensorFlow sometimes attempts to evaluate
these computed values at graph construction time, but it gets stuck at tf.pack.) It infers the shape TensorShape([Dimension(None), Dimension(None)]), which means "a matrix with an unknown number of rows and columns," because it knowns that w_shape is a vector of length 2, so the resulting normal_dist must be 2-dimensional.
You have two options to deal with this. You can set the static shape as Ishamael suggests, but this requires you to know the shape at graph construction time. For example, the following may work:
normal_dist.set_shape([input_data.get_shape()[1], labels.get_shape()[1]])
Alternatively, you can pass validate_shape=False to the tf.Variable constructor. This allows you to create a variable with a partially-defined shape, but it limits the amount of static shape information that can be inferred later on in the graph.
Similar question is nicely explained in TF FAQ:
In TensorFlow, a tensor has both a static (inferred) shape and a
dynamic (true) shape. The static shape can be read using the
tf.Tensor.get_shape method: this shape is inferred from the operations
that were used to create the tensor, and may be partially complete. If
the static shape is not fully defined, the dynamic shape of a Tensor t
can be determined by evaluating tf.shape(t).
So tf.shape() returns you a tensor, will always have a size of shape=(N,), and can be calculated in a session:
a = tf.Variable(tf.zeros(shape=(2, 3, 4)))
with tf.Session() as sess:
print sess.run(tf.shape(a))
On the other hand you can extract the static shape by using x.get_shape().as_list() and this can be calculated anywhere.
The variable can have a dynamic shape. get_shape() returns the static shape.
In your case you have a tensor that has a dynamic shape, and currently happens to hold value that is 4x3 (but at some other time it can hold a value with a different shape -- because the shape is dynamic). To set the static shape, use set_shape(w_shape). After that the shape you set will be enforced, and the tensor will be a valid initial_value.

Categories