如何从一维张量中删除零点 - TensorFlow.js?
How to remove zeros from a 1D tensor - TensorFlow.js?
给定一维张量(为了清楚起见,不是数组):[0,2,0,1,-3]
,我只想取回不同于零的值。按照示例,我想返回 [2,1,-3]
作为结果。我怎样才能在 TensorFlow.js 中做到这一点?
首先,我们需要在转换为 bool
的张量上使用 tf.whereAsync
来找到 non-zeros 值的索引。这样,除 0 值外的所有值都是 true
,因此收集了它们的索引。
在 tf.gather
中,我们通过收集先前索引处的值来创建一个新的张量。
t = tf.tensor1d([0,2,0,1,-3])
indices = await tf.whereAsync(t.cast('bool'))
tf.gather(t, indices.reshape([-1])).print()
给定一维张量(为了清楚起见,不是数组):[0,2,0,1,-3]
,我只想取回不同于零的值。按照示例,我想返回 [2,1,-3]
作为结果。我怎样才能在 TensorFlow.js 中做到这一点?
首先,我们需要在转换为
bool
的张量上使用tf.whereAsync
来找到 non-zeros 值的索引。这样,除 0 值外的所有值都是true
,因此收集了它们的索引。在
tf.gather
中,我们通过收集先前索引处的值来创建一个新的张量。
t = tf.tensor1d([0,2,0,1,-3])
indices = await tf.whereAsync(t.cast('bool'))
tf.gather(t, indices.reshape([-1])).print()