具有一个固定维数和一个变长维数的二维张量:如何将变长维数限制为最大长度?如果可变长度较短,则应保留最大长度(而不是填充),但如果长度较长,则只需剪掉末端。
例如,假设所有张量都具有(None, 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)...should完全保持不变:
tensor2_trimmed = tf.constant([
[9, 9, 9, 9],
[9, 9, 9, 9],
], dtype=tf.int32)有什么内置的命令来做吗?或者你怎么做到这一点的?
发布于 2020-02-22 12:56:44
tf.strided_slice支持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)>https://stackoverflow.com/questions/60352166
复制相似问题