首页 > 解决方案 > 如何对 Nd 张量进行切片和求和?

问题描述

我有一个形状为 [None,2,7] 的张量,一个虚拟形状以便更好地理解。我需要在 tensorflow 中获得以下 numpy 功能。

arr = np.array([[[1, 2, 3,4,5,6,7], [4, 5, 6,1,2,3,4]], [[1, 2, 3,7,6,5,4], [4, 5, 6,4,3,2,1]]])

#in numpy 
x[:, :, -3:] = x[:, :, :3] - \
    x[:, :, :3].sum(axis=1, keepdims=True)/num         #num shape is [None,1,1]

我需要在tensorflow中进行上述操作。但是 tensorflow 不支持对占位符进行切片操作。

在我的情况下,x 的 None 取决于其他操作。如果是输入占位符,那就很容易了。

此问题的任何解决方法或帮助

提前致谢

标签: pythontensorflow

解决方案


执行您需要的操作并与旧张量的其余部分连接。

sliced = x[:, :, :3] - tf.reduce_sum(x[:, :, :3], axis=1, keepdims=True) 
new_tensor = tf.concat([x[:,:,:-3], sliced], axis=-1)

如果你之后需要相同的名字

old_tensor = new_tensor

推荐阅读