将 BigQuery 中的可为空数据输入 Tensorflow Transform

Chr*_*son 6 python google-bigquery tensorflow apache-beam tensorflow-transform

我们正在尝试构建一个管道,在 TensorFlow 中进行训练之前,从 BigQuery 获取数据,通过 TensorFlow Transform 运行。

管道已启动并正在运行,但我们在 BigQuery 中处理空值时遇到困难。

我们使用 Beam 从 BigQuery 加载:

    raw_data = (pipeline
                | '{}_read_from_bq'.format(step) >> beam.io.Read(
                    beam.io.BigQuerySource(query=source_query,
                                           use_standard_sql=True,
                                           )))
Run Code Online (Sandbox Code Playgroud)

我正在使用数据集元数据,尝试FixedLenFeature各种VarLenFeature列:

    # Categorical feature schema
    categorical_features = {
        column_name: tf.io.FixedLenFeature([], tf.string) for column_name in categorical_columns
    }
    raw_data_schema.update(categorical_features)

    # Numerical feature schema
    numerical_features = {
        column_name: tf.io.VarLenFeature(tf.float32) for column_name in numerical_columns
    }
    raw_data_schema.update(numerical_features)

    # Create dataset_metadata given raw_data_schema
    raw_metadata = dataset_metadata.DatasetMetadata(
        schema_utils.schema_from_feature_spec(raw_data_schema))
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,如果您尝试将 BigQuery NULL 输入到 a 中FixedLenFeature,它就会中断。

但是,当我尝试输入字符串或整数 a 时VarLenFeature,它也会中断。这似乎是因为 VarLenFeature 需要一个列表,但 BigQuerySource 提供一个 Python 原语。它中断的确切点在这里(错误来自我尝试使用整数时):

File "/usr/local/lib/python3.7/site-packages/tensorflow_transform/impl_helper.py", line 157, in <listcomp>
indices = [range(len(value)) for value in values]
TypeError: object of type 'int' has no len()
[while running 'train_transform/AnalyzeDataset/ApplySavedModel[Phase0]/ApplySavedModel/ApplySavedModel']
Run Code Online (Sandbox Code Playgroud)

当我使用字符串输入(例如“UK”)尝试 VarLenFeature 时,输出是一个 SparseTensor,如下所示:

SparseTensorValue(indices=[(0, 0), (0, 1)], values=['U', 'K'], dense_shape=(1, 2))
Run Code Online (Sandbox Code Playgroud)

因此,似乎我需要将一个列表传递到 VarLenFeature 中才能正常工作,但 BigQuerySource 默认情况下不会执行此操作。

有没有一种简单的方法可以实现这一目标?或者我完全错过了从 BigQuery 读取可空列的标记?

预先非常感谢您!

小智 4

您可能需要自己处理 NULL(缺失)值。对于数字列,您可以用平均值或中位数替换 NULL。对于分类列 (STRING),您可以使用一些默认值(例如空字符串)或新值作为缺失值指示符。

我对 VarLenFeature 不太熟悉,但您可能可以替换 source_query 中的 NULL(NULL 插补)。就像是:

IFNULL(col, col_mean) AS col_imputed

缺点是您必须首先使用 sql 计算 col_mean 并将其作为常量填写在此处。另一件事是您需要记住这个平均值并在预测中应用相同的平均值,因为它不是 tf.transform (您的图表)的一部分。

Bigquery 本身有 BQML 作为机器学习平台。他们确实支持TRANSFORM 和自动插补。也许你也可以看一下:)