tensorflow py_func 很方便,但使我的训练步骤非常缓慢。

Sst*_*rap 5 python indexing numpy machine-learning tensorflow

我在使用 tensorflow 函数 py_func 时遇到了一些效率问题。

语境

在我的项目中,我有一批input_features大小为 的张量[? max_items m]。第一个维度设置为 ,?因为它是一个动态形状(为自定义 tensorflow 读取器读取批次,并使用 tf.train.shuffle_batch_join() 进行混洗)。第二个维度对应一个上限(我的例子可以取的最大项目数),第三个维度对应于特征维度空间。我还有一个张量num_items,其尺寸为批量大小(因此形状为(?,)),表示示例中的项目数,其他设置为 0(以 numpy 写作风格input_feature[k, num_items[k]:, :] = 0

问题

我的工作流需要一些自定义的 python 操作(特别是处理索引,我需要或实例对一些示例块执行聚类操作)并且我使用了一些封装在py_func函数中的numpy函数。这很有效,但训练变得非常慢(比没有这个 py_func 的模型慢大约 50 倍),而且函数本身并不耗时。

问题

1 - 这个计算时间增加正常吗?包裹在其中的函数py_func为我提供了一个新的张量,该张量在此过程中进一步相乘。它解释了计算时间吗?(我的意思是用这样的函数计算梯度可能更困难)。

2 - 我正在尝试修改我的处理并避免使用py_func函数。但是,使用 numpy 索引(尤其是我的数据格式)提取数据非常方便,而且我在以 TF 方式传递它时遇到了一些困难。例如,如果我有一个t1具有形状[-1, n_max, m](第一维是动态的 batch_size)且t2形状[-1,2]包含整数的张量。有没有在tensorflow执行平均操作的简便方法是,在将结果t_mean_chunk与形状(-1, m),其中(在numpy的制剂): t_mean_chunk[i,:] = np.mean(t1[i, t2[i,0]:t2[i,1], :], axis=0)?这是(除其他操作外)我在包装函数中所做的事情。

All*_*oie 2

如果没有确切的 py_func,问题 1 很难回答,但正如 hpaulj 在他的评论中提到的那样,它减慢了速度也就不足为奇了。作为最坏情况的后备方案,tf.scan或者tf.while_loop使用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
Run Code Online (Sandbox Code Playgroud)

用法示例:

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))
Run Code Online (Sandbox Code Playgroud)

印刷:

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.]
Run Code Online (Sandbox Code Playgroud)