我经常在许多 Tensorflow教程中看到这样的文字:
要进行此计算,您需要列均值。您显然需要在现实生活中计算这些,但在本示例中,我们将只提供它们。
对于中小型 CSV 数据集,计算平均值就像pandas
在数据帧上使用方法或使用 `scikit-learn 一样简单
但是,如果我们有大型数据集,比如说一个 50GB 的 CSV 文件,那么你如何计算平均值或其他类似的统计数据。Tensorflow Transform
声称它可以计算全局汇总统计数据,但他们并没有真正解释它是如何工作的或如何将其集成到工作流中。
这是他们的入门指南中的代码示例。
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
}
Run Code Online (Sandbox Code Playgroud)
文档说这段代码将tft.mean(x)
在整个数据集上运行,但不清楚这将如何发生,因为x
仅限于批处理的范围?然而,这是文档中的声明。
虽然在上面的例子中并不明显,但用户定义的预处理函数被传递代表批次而不是单个实例的张量,就像在训练和使用 TensorFlow 服务期间发生的那样。另一方面,分析器对整个数据集执行计算,返回单个值而不是一批值。x 是形状为 (batch_size,) 的张量,而 tft.mean(x) 是形状为 () 的张量。
所以问题是
是否首先tft.mean()
运行整个数据集,只有在计算全局平均值后才开始加载批次?
tft.transforms
在工作流中是否有更详细或完整的使用示例?就像这些转换可以包含在调用的单个批处理preprocessing
函数中一样tf.data.Dataset.map()
,或者如何包含?
因此,如果我试图编写一些代码来计算age
我的 tensorflow 数据集中个体的平均值。这是我到目前为止的代码。这是做这样的事情的最好方法,还是有更好的方法?
我使用了 tensorflow-2.0 make_csv_dataset()
,它负责将 CSV 文件中的示例堆叠到列结构中。请注意,我make_csv_dataset()
从上面链接中引用的 tensorflow 网站上的新教程中获取了 的代码。
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)
Run Code Online (Sandbox Code Playgroud)
需要注意的是,我划分了 ,batch_sum/len(ex_features)
因为最终批次的大小不一定与其他批次相同,因此我手动计算而不是使用tf.reduce_mean()
。如果您有很多批次,这可能是一个小问题,但只是想要尽可能准确。
任何建议,将不胜感激。
归档时间: |
|
查看次数: |
1256 次 |
最近记录: |