【问题标题】:Vector shift (Roll) in TensorflowTensorflow 中的矢量移位(滚动)
【发布时间】:2017-03-07 15:07:53
【问题描述】:

假设我们确实想使用 Keras/TensorFlow 处理图像(或 ndim 向量)。 而且,为了花哨的正则化,我们希望将每个输入向左移动随机数量的位置(溢出的部分重新出现在右侧)。

如何查看和解决:

1)

TensorFlow 的 numpy roll 函数有什么变化吗?

2)

x - 2D tensor
ri - random integer
concatenate(x[:,ri:],x[:,0:ri], axis=1) #executed for each single input to the layer, ri being random again and again (I can live with random only for each batch)

【问题讨论】:

    标签: tensorflow theano keras


    【解决方案1】:

    在 TensorFlow v1.15.0 及更高版本中,您可以使用 tf.roll,其工作方式与 numpy roll 类似。 https://github.com/tensorflow/tensorflow/pull/14953 。 要改进上述答案,您可以这样做:

    # size of x dimension
    x_len = tensor.get_shape().as_list()[1]
    # random roll amount
    i = tf.random_uniform(shape=[1], maxval=x_len, dtype=tf.int32)
    output = tf.roll(tensor, shift=i, axis=[1])
    

    对于从 v1.6.0 开始的旧版本,您必须使用 tf.manip.roll :

    # size of x dimension
    x_len = tensor.get_shape().as_list()[1]
    # random roll amount
    i = tf.random_uniform(shape=[1], maxval=x_len, dtype=tf.int32)
    output = tf.manip.roll(tensor, shift=i, axis=[1])
    

    【讨论】:

      【解决方案2】:

      我只需要自己做这件事,不幸的是,我认为没有 tensorflow 操作可以做 np.roll。不过,您上面的代码看起来基本正确,只是它不是按 ri 滚动,而是按 (x.shape[1] - ri) 滚动。

      另外你需要小心选择你的随机整数,它来自 range(1,x.shape[1]+1) 而不是 range(0,x.shape[1]),好像 ri 是 0 ,则 x[:,0:ri] 将为空。

      所以我的建议更像是(沿着维度 1 滚动):

      x_len = x.get_shape().as_list()[1] 
      i = np.random.randint(0,x_len) # The amount you want to roll by
      y = tf.concat([x[:,x_len-i:], x[:,:x_len-i]], axis=1)
      

      编辑:在 hannes 的正确评论之后添加了缺少的冒号。

      【讨论】:

      • 最后一行缺少:,应该是y = tf.concat([x[:,x_len-i:], x[:,:x_len-i]], axis=1)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多