gpt4 book ai didi

python - 是否有类似于segment_min和segment_max但随机的Tensorflow函数?

转载 作者:太空宇宙 更新时间:2023-11-03 20:40:55 25 4
gpt4 key购买 nike

至于segment_max和segment_min,我有我的数据和我的segment_ids。我不想选择最大值(segment_max)或最小值(segment_min),而是想知道是否存在一个函数可以返回数据中的随机数,即segment_random行。

最佳答案

该功能本身并不存在,但使用现有操作重新创建该功能并不困难。

import tensorflow as tf

def segment_random(data, segment_ids, seed=None):
# segment_ids must be sorted 1D integer tensor
data = tf.convert_to_tensor(data)
segment_ids = tf.convert_to_tensor(segment_ids)
# Find the bounds of the segments
seg_diff = segment_ids[1:] - segment_ids[:-1]
seg_bounds = tf.squeeze(tf.where(tf.not_equal(seg_diff, 0)), 1)
seg_bounds = tf.concat([[0], seg_bounds + 1, [tf.size(segment_ids)]], axis=0)
# Find the size of each segment
seg_sizes = seg_bounds[1:] - seg_bounds[:-1]
# Pick random indices for each segment
seg_r = tf.random.uniform(tf.shape(seg_sizes), seed=seed)
seg_relidx = tf.cast(seg_r * tf.cast(seg_sizes, seg_r.dtype), seg_bounds.dtype)
seg_idx = seg_relidx + seg_bounds[:-1]
# Returned data from picked indices
return tf.gather(data, seg_idx)

# Test
with tf.Graph().as_default(), tf.Session() as sess:
tf.random.set_random_seed(0)
out = segment_random([1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 1, 1, 2, 3, 3, 3, 4, 4])
print(sess.run(out))
# [2 4 7 9]

关于python - 是否有类似于segment_min和segment_max但随机的Tensorflow函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56870897/

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