Tensorflow中的矢量移位(Roll)

Kha*_*haj 3 theano keras tensorflow

可以说,我们确实希望使用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)
Run Code Online (Sandbox Code Playgroud)

Fer*_*gal 5

我不得不自己这样做,我不认为有一个张量流操作不幸地做np.roll.上面的代码看起来基本上是正确的,除了它不是由ri滚动,而是由(x.shape [1] - ri)滚动.

另外你需要注意选择你的范围(1,x.shape [1] +1)而不是范围(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)
Run Code Online (Sandbox Code Playgroud)

编辑:在汉纳斯的正确评论后添加了缺失的冒号.

  • 在最后一行中缺少一个`:`,应该是`y = tf.concat([x [:,x_len-i:],x [:,:x_len-i]],axis = 1) (2认同)

小智 5

在当前每夜构建的tensorflow(或将来的版本1.6.0)上。您可以使用tf.manip.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.manip.roll(tensor, shift=i, axis=[1])
Run Code Online (Sandbox Code Playgroud)