Skip to content Skip to sidebar Skip to footer

Convert A List With Non-fixed Length Elements To Tensor

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.co

Solution 1:

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)

Post a Comment for "Convert A List With Non-fixed Length Elements To Tensor"