如果没有确切的 py_func,问题 1 很难回答,但正如 hpaulj 在他的评论中提到的那样,它减慢了速度也就不足为奇了。作为最坏情况的后备方案,tf.scan
or tf.while_loop
with a TensorArray
可能会快一些。然而,最好的情况是使用 TensorFlow 操作提供矢量化解决方案,我认为在这种情况下这是可能的。
至于问题 2,我不确定它是否算简单,但这里有一个计算索引表达式的函数:
import tensorflow as tf
def range_mean(index_ranges, values):
"""Take the mean of `values` along ranges specified by `index_ranges`.
return[i, ...] = tf.reduce_mean(
values[i, index_ranges[i, 0]:index_ranges[i, 1], ...], axis=0)
Args:
index_ranges: An integer Tensor with shape [N x 2]
values: A Tensor with shape [N x M x ...].
Returns:
A Tensor with shape [N x ...] containing the means of `values` having
indices in the ranges specified.
"""
m_indices = tf.range(tf.shape(values)[1])[None]
# Determine which parts of `values` will be in the result
selected = tf.logical_and(tf.greater_equal(m_indices, index_ranges[:, :1]),
tf.less(m_indices, index_ranges[:, 1:]))
n_indices = tf.tile(tf.range(tf.shape(values)[0])[..., None],
[1, tf.shape(values)[1]])
segments = tf.where(selected, n_indices + 1, tf.zeros_like(n_indices))
# Throw out segment 0, since that's our "not included" segment
segment_sums = tf.unsorted_segment_sum(
data=values,
segment_ids=segments,
num_segments=tf.shape(values)[0] + 1)[1:]
divisor = tf.cast(index_ranges[:, 1] - index_ranges[:, 0],
dtype=values.dtype)
# Pad the shape of `divisor` so that it broadcasts against `segment_sums`.
divisor_shape_padded = tf.reshape(
divisor,
tf.concat([tf.shape(divisor),
tf.ones([tf.rank(values) - 2], dtype=tf.int32)], axis=0))
return segment_sums / divisor_shape_padded
用法示例:
index_range_tensor = tf.constant([[2, 4], [1, 6], [0, 3], [0, 9]])
values_tensor = tf.reshape(tf.range(4 * 10 * 5, dtype=tf.float32), [4, 10, 5])
with tf.Session():
tf_result = range_mean(index_range_tensor, values_tensor).eval()
index_range_np = index_range_tensor.eval()
values_np = values_tensor.eval()
for i in range(values_np.shape[0]):
print("Slice {}: ".format(i),
tf_result[i],
numpy.mean(values_np[i, index_range_np[i, 0]:index_range_np[i, 1], :],
axis=0))
Prints:
Slice 0: [ 12.5 13.5 14.5 15.5 16.5] [ 12.5 13.5 14.5 15.5 16.5]
Slice 1: [ 65. 66. 67. 68. 69.] [ 65. 66. 67. 68. 69.]
Slice 2: [ 105. 106. 107. 108. 109.] [ 105. 106. 107. 108. 109.]
Slice 3: [ 170. 171. 172. 173. 174.] [ 170. 171. 172. 173. 174.]