Skip to main content
 首页 » 编程设计

python之Tensorflow 转换 : How to find the mean of a variable over the entire dataset

2024年09月03日2898°冷暖

我经常在很多Tensorflow中看到tutorials文字如:

To do this calculation, you need the column means. You would obviously need to compute these in real life, but for this example we'll just provide them.

对于中小型 CSV 数据集,计算平均值就像在数据帧上使用 pandas 方法或使用 `scikit-learn

一样简单

但是,如果我们有大型数据集,比如一个 50GB 的 CSV 文件,那么您如何计算平均值或其他类似的统计数据。 Tensorflow Transform 声称它可以计算全局汇总统计信息,但他们并没有真正解释这是如何工作的,也没有解释如何将其集成到工作流中。

这是来自他们的 getting started guide 的代码示例.

import tensorflow as tf 
import tensorflow_transform as tft 
 
def preprocessing_fn(inputs): 
  x = inputs['x'] 
  y = inputs['y'] 
  s = inputs['s'] 
  x_centered = x - tft.mean(x) 
  y_normalized = tft.scale_to_0_1(y) 
  s_integerized = tft.compute_and_apply_vocabulary(s) 
  x_centered_times_y_normalized = x_centered * y_normalized 
  return { 
      'x_centered': x_centered, 
      'y_normalized': y_normalized, 
      'x_centered_times_y_normalized': x_centered_times_y_normalized, 
      's_integerized': s_integerized 
  } 

文档说此代码将在整个数据集上运行 tft.mean(x),但尚不清楚这将如何发生,因为 x 仅限于只是批处理的范围?然而,这是文档中的声明。

While not obvious in the example above, the user defined preprocessing function is passed tensors representing batches and not individual instances, as happens during training and serving with TensorFlow. On the other hand, analyzers perform a computation over the entire dataset that returns a single value and not a batch of values. x is a Tensor with a shape of (batch_size,), while tft.mean(x) is a Tensor with a shape of ().

所以问题是

  1. tft.mean() 是否首先在整个数据集上运行,并且只有在计算出全局平均值之后才开始批量加载?

  2. 是否有在工作流中使用 tft.transforms 的更详细或更完整的示例?比如这些转换是否可以包含在 tf.data.Dataset.map() 调用的单个批处理 preprocessing 函数中,或者如何包含?

因此,如果我尝试编写一些代码来计算我的 tensorflow 数据集中个体的平均年龄。这是我到目前为止的代码。这是做这样的事情的最好方法,还是有更好的方法?

我使用了 tensorflow-2.0 make_csv_dataset(),它负责将 CSV 文件中的示例堆叠到列结构中。请注意,我从上面链接中引用的 tensorflow 网站上的新教程中获取了 make_csv_dataset() 的代码。

  dataset = tf.data.experimental.make_csv_dataset( 
      file_path, 
      batch_size=32,  
      label_name=LABEL_COLUMN, 
      na_value="?", 
      num_epochs=1, 
      ignore_errors=True) 
 
 ds_iter = dataset.make_one_shot_iterator() 
 
 list_of_batch_means = [] 
 
 for ex_features, ex_labels in ds_iter: 
    batch_length = len(ex_features) 
    batch_sum = tf.reduce_sum(ex_features['age']) 
    list_of_batch_means.append(batch_sum/len(ex_features) 
 
 average_age = np.mean(list_of_batch_means) 

作为一个警告,我划分了 batch_sum/len(ex_features),因为最终批处理不一定与其他批处理大小相同,因此我手动计算而不是使用 >tf.reduce_mean()。如果您有很多批处理,这可能是个小问题,但只是希望尽可能准确。

如有任何建议,我们将不胜感激。

请您参考如下方法:

tf.transform 最重要​​的概念是预处理功能。预处理函数是数据集转换的逻辑描述。预处理函数接受并返回张量字典。有两种函数(步骤)用于定义预处理函数:

  1. 分析步骤
  2. 转换步骤

分析步骤:它遍历整个数据集并创建一个图表。因此,例如为了计算均值,我们传递完整的数据集来计算该数据集特定列的平均值(此步骤需要完整传递数据集)

转换步骤:它基本上使用在分析步骤中创建的图形并转换完整的数据集。

因此,基本上在分析步骤中计算的常量用于转换步骤。

为了更好的理解,你可以通过这个video其次是这个 presentation这应该会巩固您对 Tensorflow Transform 内部工作原理的理解。