至于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]
我是一名优秀的程序员,十分优秀!