Reputation: 39
It seems that I can't convert a list with non-fixed length elements to tensor.For example, I get a list like [[1,2,3],[4,5],[1,4,6,7]]
,and I want to convert it to a tensor by tf.convert_to_tensor
, and It doesn't work and throw a ValueError: Argument must be a dense tensor: [[1, 2, 3], [4, 5], [1, 4, 6, 7]] - got shape [3], but wanted [3, 3].
I don't want to pad or crop the elements for some reasons, is there any method to solve it?
Thanks in advance!
Upvotes: 4
Views: 6070
Reputation: 544
Tensorflow (as far as I know) currently does not support Tensors with different lengths along a dimension.
Depending on your goal, you could pad your list with zeros (inspired by this question) and then convert to a tensor. For example using numpy:
>>> import numpy as np
>>> x = np.array([[1,2,3],[4,5],[1,4,6,7]])
>>> max_length = max(len(row) for row in x)
>>> x_padded = np.array([row + [0] * (max_length - len(row)) for row in x])
>>> x_padded
array([[1, 2, 3, 0],
[4, 5, 0, 0],
[1, 4, 6, 7]])
>>> x_tensor = tf.convert_to_tensor(x_padded)
Upvotes: 5