Python 是否有一个类似于段_min和段_max但随机的张量流函数?

Python 是否有一个类似于段_min和段_max但随机的张量流函数?,python,tensorflow,Python,Tensorflow,至于段_max和段_min,我有我的数据和段_id。我不想选择最大值(segment_max)或最小值(segment_min),而是想知道是否存在一个函数,可以返回数据中的随机数,即线段随机数。该函数本身并不存在,但使用现有操作重新创建该功能并不困难 import tensorflow as tf def segment_random(data, segment_ids, seed=None): # segment_ids must be sorted 1D integer tens

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

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

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]

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

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]

那么你想从张量的连续子序列中选取随机元素?那么你想从张量的连续子序列中选取随机元素?