Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将可变长度张量修剪到最大长度_Python_Tensorflow_Tensorflow2.x - Fatal编程技术网

Python 将可变长度张量修剪到最大长度

Python 将可变长度张量修剪到最大长度,python,tensorflow,tensorflow2.x,Python,Tensorflow,Tensorflow2.x,拥有一个固定维度和一个可变长度维度的二维张量:如何将可变长度维度限制为最大长度?如果可变长度较短,则应保持最大长度(且不填充),但如果可变长度较长,则应仅切割末端 例如,假设所有张量的形状都是(无,4),我想将所有张量的最大形状都限制为(3,4)。一个示例输入可以是: tensor1 = tf.constant([ [1, 2, 0, 0], [1, 3, 4, 0], [0, 0, 0, 0], [7, 7, 7, 7], [7, 8, 9, 1], ]

拥有一个固定维度和一个可变长度维度的二维张量:如何将可变长度维度限制为最大长度?如果可变长度较短,则应保持最大长度(且不填充),但如果可变长度较长,则应仅切割末端

例如,假设所有张量的形状都是
(无,4)
,我想将所有张量的最大形状都限制为
(3,4)
。一个示例输入可以是:

tensor1 = tf.constant([
    [1, 2, 0, 0],
    [1, 3, 4, 0],
    [0, 0, 0, 0],
    [7, 7, 7, 7],
    [7, 8, 9, 1],
], dtype=tf.int32)
…,应将其修剪为:

tensor1_trimmed = tf.constant([
    [1, 2, 0, 0],
    [1, 3, 4, 0],
    [0, 0, 0, 0],
], dtype=tf.int32)
但是,任何小于最大值的值都应保持不变:

tensor2 = tf.constant([
    [9, 9, 9, 9],
    [9, 9, 9, 9],
], dtype=tf.int32)
…应该保持完全相同:

tensor2_trimmed = tf.constant([
    [9, 9, 9, 9],
    [9, 9, 9, 9],
], dtype=tf.int32)
是否有任何内置命令来执行此操作?或者您将如何实现这一点?

支持numpy样式的切片,因此您可以在示例中使用
[:3,:]

>>> tensor1 = tf.constant([
...     [1, 2, 0, 0],
...     [1, 3, 4, 0],
...     [0, 0, 0, 0],
...     [7, 7, 7, 7],
...     [7, 8, 9, 1],
... ], dtype=tf.int32)
>>> tensor1[:3,:]
<tf.Tensor: shape=(3, 4), dtype=int32, numpy=
array([[1, 2, 0, 0],
       [1, 3, 4, 0],
       [0, 0, 0, 0]], dtype=int32)>
>>> tensor2 = tf.constant([
...     [9, 9, 9, 9],
...     [9, 9, 9, 9],
... ], dtype=tf.int32)
>>> tensor2[:3,:]
<tf.Tensor: shape=(2, 4), dtype=int32, numpy=
array([[9, 9, 9, 9],
       [9, 9, 9, 9]], dtype=int32)>
张量1=tf.constant([ ... [1, 2, 0, 0], ... [1, 3, 4, 0], ... [0, 0, 0, 0], ... [7, 7, 7, 7], ... [7, 8, 9, 1], …],dtype=tf.int32) >>>张量1[:3,:] >>>张量2=tf.常数([ ... [9, 9, 9, 9], ... [9, 9, 9, 9], …],dtype=tf.int32) >>>张量2[:3,:]