partition or mask or filter a Tensor in tensorflow.js

本秂侑毒 提交于 2019-12-07 00:40:29

To partition your tensor, you can first iterate over your ids tensor to get the number of subtensor to create and the index of the elements it should contain. This information can be stored in an object where the key is the number of the partition in the ids array and the value is an array of indexes.

const data = tf.tensor([6,2,8,4,5]);
const ids = tf.tensor([0,1,1,0,2]);

const data2 = tf.tensor([[6,2],[8,4], [5, 4], [6, 5]]);
const ids2 = tf.tensor([0,1,1,0]);

const filterT = (t, p) => {
  t.print()
  p.print()
  const l = p.unstack().reduce((a, b, i) => {
  const v = b.dataSync()[0]
  if (Object.keys(a).includes(v.toString())) {
    a[v].push(i)
  } else {
    a[v] = [i]
  }
  return a
}, {})

  const r = Object.keys(l).map(k => t.gather(tf.tensor1d(l[k], 'int32')))
  r.forEach(e => e.print())
}

filterT(data, ids)
filterT(data2, ids2)
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"> </script>
  </head>

  <body>
  </body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!