想象一下,我有一个像这样的张量作为输入:
[[1,1,1,1,1,1,0,0,0,0,0,0,0],
[[1,1,1,1,1,1,0,0,0,0,0,0,0],
[[1,1,1,1,1,1,0,0,0,0,0,0,0],
[[1,1,1,1,1,1,0,0,0,0,0,0,0],
[[1,1,1,1,1,1,0,0,0,0,0,0,0],
[[1,1,1,1,1,1,0,0,0,0,0,0,0],
[[1,1,1,1,1,1,0,0,0,0,0,0,0]
[[1,1,1,1,1,1,0,0,0,0,0,0,0]]
我想输出这个:
[[1,1,1,1,1,1,0,0,0,0,0,0,0],
[[0,1,1,1,1,1,1,0,0,0,0,0,0],
[[0,0,1,1,1,1,1,1,0,0,0,0,0],
[[0,0,0,1,1,1,1,1,1,0,0,0,0],
[[0,0,0,0,1,1,1,1,1,1,0,0,0],
[[0,0,0,0,0,1,1,1,1,1,1,0,0],
[[0,0,0,0,0,0,1,1,1,1,1,1,0]
[[0,0,0,0,0,0,0,1,1,1,1,1,1]]
以任何方式仅使用tf操作(转换为numpy,执行操作,并切换回tf张量是禁止的,因为我正在使用tf优化器进行梯度下降)
答案 0 :(得分:0)
这是一个零填充的解决方案 - 用随机填充替换它很简单。
import numpy as np
import tensorflow as tf
x = np.zeros((8, 13), dtype=np.float32)
x[:, :6] = 1
x = tf.constant(x)
s0 = tf.shape(x)[0]
# add an extra zero column on the right
x2 = tf.concat([x, tf.zeros((s0, 1), dtype=x.dtype)], axis=-1)
# flatten the result and remove as many elements as we just added
x2 = tf.reshape(x2, [-1])[:-s0]
# reshape the result to the original shape
x2 = tf.reshape(x2, [s0, -1])
sess = tf.InteractiveSession()
print(x.eval())
print(x2.eval())
答案 1 :(得分:0)
感谢user1735003
我发现的另一种方法:
def roll(tensor):
T=tf.expand_dims(tf.zeros([tensor.shape[1]),0)
for i in range(tensor.shape[0]):
row=tf.manip.roll(tensor[i,], shift=i, axis=0)
T = tf.concat([T,row],axis=1)
return T