gpt4 book ai didi

python - 求Tensorflow中连续的最大数量

转载 作者:行者123 更新时间:2023-12-02 11:43:01 25 4
gpt4 key购买 nike

我找到了解决方案

Matlab:https://uk.mathworks.com/matlabcentral/answers/85143-find-maximum-number-of-consecutive-negative-values

Numpy:Find consecutive ones in numpy array

但在 Tensorflow 中则不然。我发现的最接近的问题是: Reduce sum with condition in tensorflow

但是,这仅计算第一组,而不是找到最大的组。基本上,如果有一个相当于 Matlab RCUMSUMC 的 Tensorflow,这个问题就很容易解决

https://uk.mathworks.com/matlabcentral/fileexchange/28685-rcumsumc

我的输入是形状为 NxHxW 的二进制张量,输出预计为 NxW,其中每一列代表连续张量的最大数量:

Input = [[1,1,0,0,1,0,1,1,1,1,0,0,1],
[1,0,0,1,1,1,1,1,1,0,0,1,0],
[0,0,0,1,1,1,0,0,1,0,1,1,0]]

Output = [4,6,3]

最佳答案

编辑:以下是如何对 3 维张量执行相同的操作,在第二个维度上搜索一组张量:

import tensorflow as tf

inp = tf.random.stateless_uniform((3, 4, 5), [0, 0], 0, 2, tf.int32)
tf.print(inp)
# [[[0 1 0 0 0]
# [0 0 0 1 1]
# [0 1 1 0 0]
# [0 0 0 0 0]]
#
# [[1 1 0 0 0]
# [0 1 1 0 0]
# [0 1 0 1 0]
# [0 0 0 0 0]]
#
# [[1 1 1 0 0]
# [0 0 1 1 1]
# [0 1 1 0 1]
# [0 1 0 0 0]]]
# Pad with ones to avoid all-zeros
inp = tf.pad(inp, [(0, 1), (0, 0), (0, 0)], constant_values=1)
s = tf.shape(inp)
# Transpose and reshape
inp_t = tf.reshape(tf.transpose(inp, [0, 2, 1]), [-1, s[1]])
# Surround with zeros
inp_t = tf.pad(inp_t, [(0, 0), (1, 1)])
# Find bounds of groups of ones
groups = tf.reshape(tf.where(tf.not_equal(inp_t[:, 1:], inp_t[:, :-1])), [-1, 2, 2])
# Compute group sizes
group_sizes = groups[:, 1, 1] - groups[:, 0, 1]
# Find maximum group sizes
max_ones_group = tf.math.segment_max(group_sizes, groups[:, 0, 0], name=None)
# Reshape back
out = tf.reshape(max_ones_group, [s[0], s[2]])[:-1]
tf.print(out)
# [[0 1 1 1 1]
# [1 3 1 1 0]
# [1 2 3 1 2]]
<小时/>

假设输入是二进制张量(只有零和一),这是一种方法:

import tensorflow as tf

inp = tf.constant([[1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1],
[1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0]])
# Surround with zeros
inp = tf.pad(inp, [(0, 0), (1, 1)])
# Find bounds of groups of ones
groups = tf.reshape(tf.where(tf.not_equal(inp[:, 1:], inp[:, :-1])), [-1, 2, 2])
# Compute group sizes
group_sizes = groups[:, 1, 1] - groups[:, 0, 1]
# Find maximum group sizes
max_ones_group = tf.math.segment_max(group_sizes, groups[:, 0, 0], name=None)
tf.print(max_ones_group)
# [4 6 3]

关于python - 求Tensorflow中连续的最大数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59048143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com