0
$\begingroup$

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.

$\endgroup$
0
$\begingroup$

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]

|improve this answer|||||
$\endgroup$
  • $\begingroup$ Thanks Is there an alternative where the last element in the list be 0 if length of list less than shape? $\endgroup$ – ten do Jul 18 '19 at 2:08
  • $\begingroup$ @tendo I do not completely understand your question but check this code if it helps. $\endgroup$ – Nowroz Islam Jul 18 '19 at 2:55
  • $\begingroup$ I got your point but can we make a sequence whose length is less than the shape and the remaining elements padded with 0? $\endgroup$ – ten do Jul 18 '19 at 3:56
  • $\begingroup$ just add a zero at the end of your sequence so, when it is passed as the value in tf.constant, the remaining entries will be filled with zero if the length of the sequence is less than the number of elements implied by the shape. $\endgroup$ – Nowroz Islam Jul 18 '19 at 17:28
  • $\begingroup$ Ok got it thanks $\endgroup$ – ten do Jul 18 '19 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.