将具有非固定长度元素的列表转换为张量

Lil*_*ope 4 python tensorflow

似乎我无法将具有非固定长度元素的列表转换为张量。例如,我得到一个类似的列表[[1,2,3],[4,5],[1,4,6,7]],我想将其转换为张量tf.convert_to_tensor,但它不起作用并抛出一个ValueError: Argument must be a dense tensor: [[1, 2, 3], [4, 5], [1, 4, 6, 7]] - got shape [3], but wanted [3, 3].我不知道由于某些原因不想填充或裁剪元素,有什么方法可以解决吗?
提前致谢!

小智 5

Tensorflow(据我所知)目前不支持沿维度具有不同长度的张量。

根据您的目标,您可以用零填充列表(受此问题启发),然后转换为张量。例如使用 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)
Run Code Online (Sandbox Code Playgroud)