【问题标题】:Detecting out-of-bounds slicing with tf.slice like in numpy像在 numpy 中一样使用 tf.slice 检测越界切片
【发布时间】:2023-03-03 10:11:01
【问题描述】:

在 tensorflow 中,我正在尝试使用 tf.slice,但 as its documentation states,它需要切片以适合输入数组。例如,如果您尝试对张量 [1,2,3,4] 的前 5 个位置进行切片,它将崩溃。我希望拥有与 python 列表或 numpy 数组相同的功能,其中切片可以让您获得原始数组和您要求的切片的交集。例如,如果您要求 [1,2,3,4] 的位置 2 到 6,您将得到 [2,3,4]。

我如何在张量流中做到这一点?

谢谢!

【问题讨论】:

    标签: python numpy tensorflow slice


    【解决方案1】:

    您可以使用 tensorflow 的 python 切片运算符,它比 tf.slice 稍微强大一些,特别是进行一些绑定检查以类似于 numpy

    x = tf.zeros((10,))
    y = tf.slice(x, [5], [15])
    print(y.shape)
    # (15,)
    z = x[5:42]
    print(z.shape)
    # (5,)
    

    【讨论】:

      【解决方案2】:

      你可以使用tf.clip_by_value:

      def robust_slice( t, begin, size, name=None ):
          with tf.name_scope('robust_slice'):
              new_size = tf.clip_by_value(size + begin, clip_value_min = 0, clip_value_max = t.shape()) - begin
              return tf.slice(t, begin, new_size, name)
      

      (未经测试,但类似的东西应该可以完成这项工作)

      【讨论】:

      • 我试过了,但如果部分形状未知,它似乎不起作用。
      猜你喜欢
      • 2016-02-24
      • 1970-01-01
      • 2021-07-26
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 2013-11-09
      • 1970-01-01
      相关资源
      最近更新 更多