Create tensor of a sequence with a defined shape using TensorFlow

Create a tensor Y of shape (2,3) having a sequence of numbers 12,15,18,...., 150

I tried using the below code

tf.constant(np.arange(12,153,3),dtype=tf.dtypes.float32,shape=[2,3])

I got an error saying the tensor with 47 elements cannot be converted into 6 elements.

I added the following third dimension in shape and it worked.

tf.constant(np.arange(12,153,3),dtype=tf.dtypes.float32,shape=[8,2,3])

How to proceed as the given question wants the sequence tensor to be in shape [2,3]?

Please help.

Topic tensorflow machine-learning

Category Data Science


As given in tf.constant documentation:

If value is a list, then the length of the list must be less than or equal to the number of elements implied by the shape argument (if specified).

In your code, the value is the returned array from np.arange(12,153,3) containing 47 integers.

Now, when you specify shape = [2,3], it implies that the length of the list you have provided as value is 2x3 = 6 which is not true because the array generated by np.arange(12,153,3) has the length = 47. In this case, you will get an error saying:

ValueError: Too many elements provided. Needed at most 6, but received 47

On the other hand, when you specify shape = [8,2,3], it implies that the length of the list you have provided as value is 8x2x3 = 48 which is also not true because the actual length is 47. It does not raise an error because the length of the list can be less than the number implied by the shape argument as it says in the documentation:

In the case where the list length is less than the number of elements specified by shape, the last element in the list will be used to fill the remaining entries.

So, it is not possible to shape a sequence of 47 elements to [2,3]

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.