如何切片和总结张量矩阵

问题描述

如何对张量矩阵求和。我有一个像这样的矩阵:

[[0.   0.   0.   0.12 0.75 0.13 0.   0.   0.  ]
 [0.   0.   0.   0.06 0.89 0.05 0.   0.   0.  ]
 [0.   0.   0.   0.3  0.39 0.31 0.   0.   0.  ]
 [0.   0.   0.   0.18 0.63 0.19 0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.   0.09 0.03 0.89]
 [0.   0.   0.   0.14 0.7  0.16 0.   0.   0.  ]
 [0.   0.   0.   0.   0.   0.   0.12 0.02 0.86]
 [0.   0.   0.   0.   0.   0.   0.1  0.02 0.88]
 [0.   0.   0.   0.03 0.93 0.04 0.   0.   0.  ]
 [ 0.06 0.89 0.05 0.   0.   0.  0.   0.   0.  ]],shape=(10,9),dtype=float64)

结果,我想删除所有零并得到一个像这样的矩阵:

[[0.12 0.75 0.13]
 [0.06 0.89 0.05]
 [0.3  0.39 0.31]
 [0.18 0.63 0.19]
 [0.09 0.03 0.89]
 [0.14 0.7  0.16]
 [0.12 0.02 0.86]
 [0.1  0.02 0.88]
 [0.03 0.93 0.04]
 [0.06 0.89 0.05]],3),dtype=float64)

我认为我应该将输入矩阵切成shape =(10,3)的三个部分,并将它们概括为tf.math.add(tf.math.add(tf.slice(x,[0,0],[- 1,3]),tf.slice(x,[0,3],[-1,3])), tf.slice(x,[0,6],[-1,3] 谢谢你的建议

解决方法

尝试一下:

import tensorflow as tf

x = [[0.,0.,0.12,0.75,0.13,0.],[0.,0.06,0.89,0.05,0.3,0.39,0.31,0.18,0.63,0.19,0.09,0.03,0.89],0.14,0.7,0.16,0.02,0.86],0.1,0.88],0.93,0.04,[0.06,0.]]

tf.reshape(tf.gather_nd(x,tf.where(tf.not_equal(x,0))),(-1,3))
<tf.Tensor: shape=(10,3),dtype=float32,numpy=
array([[0.12,0.13],0.05],[0.3,0.31],[0.18,0.19],[0.09,[0.14,0.16],[0.12,[0.1,[0.03,0.04],0.05]],dtype=float32)>
,

TensorFlow 2.x

import tensorflow as tf

x = tf.convert_to_tensor(
    [[0.,0.]]
     )


res = tf.reshape(x[(x!=0)],3))

如果每行上有正数个可变数。

x_ragged = tf.RaggedTensor.from_tensor(x)
mask_ragged = tf.RaggedTensor.from_tensor(x!=0)

res = tf.ragged.boolean_mask(x_ragged,mask_ragged)

PS:第二种解决方案导致数字差异很小(例如0.12变为0.199999)(可能是数据类型问题)。您可能可以通过强制使用f32或f64数据类型来解决此问题。我还没有调查。