从张量产生越来越多的段

发布于 2025-02-01 18:39:40 字数 240 浏览 4 评论 0原文

假设我有这样的张量。

t1 = tf.constant([0,1,2,3,5,6,7,8,9,10,19,20,21,22,23,24])

我想将其分为段,其中包含数字紧邻的组。预期的输出将是这样的:

t2 = [0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2]

关于如何使用TensorFlow方法进行此操作的任何想法?

Suppose I have a tensor like this.

t1 = tf.constant([0,1,2,3,5,6,7,8,9,10,19,20,21,22,23,24])

I want to separate it into segments, containing the groups where the numbers are immediately adjacent. The expected output would be something like this:

t2 = [0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2]

Any idea on how to do this using tensorflow methods?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

芸娘子的小脾气 2025-02-08 18:39:40
import tensorflow as tf
t1 = tf.constant([0,1,2,3,5,6,7,8,9,10,19,20,21,22,23,24], dtype=tf.int32)

t2 = tf.roll(t1 - 1, shift=-1, axis=0)
output = tf.math.cumsum(tf.cast(t2 != t1, dtype=tf.int32), exclusive=True)

output # [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]
import tensorflow as tf
t1 = tf.constant([0,1,2,3,5,6,7,8,9,10,19,20,21,22,23,24], dtype=tf.int32)

t2 = tf.roll(t1 - 1, shift=-1, axis=0)
output = tf.math.cumsum(tf.cast(t2 != t1, dtype=tf.int32), exclusive=True)

output # [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]
囍孤女 2025-02-08 18:39:40

实现此功能的一种方法就是这样:

diff = t1[1:] - t1[:-1]
jumps = tf.abs(diff) > 1

t2 = tf.math.cumsum(tf.cast(jumps, 'int32'))
t2 = tf.concat([[0], t2], 0)

我们首先采用连续元素之间的差异,然后检查绝对差异是否大于一个(在这种情况下,数字不相邻)。这在“跳跃”的位置和在其他地方的错误位置产生了一个阵列。 abs确保正确处理较低的数字(即[4、5、6、1、2])。如果您知道数字总是在增加,则可以忽略它。

将此数组的累积总和(铸造为整数类型)将提供一个数组,其中以整数表示不同的部分。最后,由于差异将数组的长度减少一个,因此我们用t2使用0进行预处,因为第一个数字应属于第一部分。

一小笔记:这将数字减少一个(IE [4、5、6、5、4]),并将其放在同一部分中。

One way to achieve this functionality would be like this:

diff = t1[1:] - t1[:-1]
jumps = tf.abs(diff) > 1

t2 = tf.math.cumsum(tf.cast(jumps, 'int32'))
t2 = tf.concat([[0], t2], 0)

We first take the difference between consecutive elements, then check if the absolute difference is greater than one (in which case the numbers are not adjacent). This yields an array with True at the places of the 'jumps' and False elsewhere. The abs makes sure that a jump to a lower number (i.e. [4, 5, 6, 1, 2]) is handled correctly. You can leave it out if you know that numbers will always be increasing.

Taking the cumulative sum of this array (casted to an integer type) will provide an array with the different sections represented as integers. Finally, since taking the difference reduces the length of the array by one, we prepend t2 with a 0, since the first number should belong to the first section.

One small note: this treats numbers decreasing by one (i.e. [4, 5, 6, 5, 4]) as adjacent and puts them in the same section.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文