9

概述

我按照以下指南编写 TF 记录,我曾经tf.Transform在其中预处理我的特征。现在,我想部署我的模型,为此我需要将此预处理功能应用于真实的实时数据。

我的方法

首先,假设我有 2 个功能:

features = ['amount', 'age']

我有transform_fn来自 Apache Beam 的,居住在working_dir=gs://path-to-transform-fn/

然后我使用以下方法加载转换函数:

tf_transform_output = tft.TFTransformOutput(working_dir)

我认为在生产中服务的最简单方法是获取一个处理过的数据的 numpy 数组,然后调用model.predict()(我使用的是 Keras 模型)。

为此,我认为transform_raw_features()方法正是我所需要的。

但是,似乎在构建架构之后:

raw_features = {}
for k in features:
    raw_features.update({k: tf.constant(1)})

print(tf_transform_output.transform_raw_features(raw_features))

我得到:

AttributeError: 'Tensor' object has no attribute 'indices'

现在,我假设发生这种情况是因为我tf.VarLenFeature()preprocessing_fn.

def preprocessing_fn(inputs):
    outputs = inputs.copy()

    for _ in features:
        outputs[_] = tft.scale_to_z_score(outputs[_])

我使用以下方法构建元数据:

RAW_DATA_FEATURE_SPEC = {}
for _ in features:
    RAW_DATA_FEATURE_SPEC[_] = tf.VarLenFeature(dtype=tf.float32)
    RAW_DATA_METADATA = dataset_metadata.DatasetMetadata(
    dataset_schema.from_feature_spec(RAW_DATA_FEATURE_SPEC))

简而言之,给定一本字典:

d = {'amount': [50], 'age': [32]},我想应用这个transform_fn,并适当地缩放这些值以输入到我的模型中进行预测。这个字典正是函数PCollection处理数据之前的我的格式pre_processing()

管道结构:

class BeamProccess():

def __init__(self):

    # init 

    self.run()


def run(self):

    def preprocessing_fn(inputs):

         # outputs = { 'id' : [list], 'amount': [list], 'age': [list] }
         return outputs

    with beam.Pipeline(options=self.pipe_opt) as p:
        with beam_impl.Context(temp_dir=self.google_cloud_options.temp_location):
            data = p | "read_table" >> beam.io.Read(table_bq) \
            | "create_data" >> beam.ParDo(ProcessFn())

            transformed_dataset, transform_fn = (
                        (train, RAW_DATA_METADATA) | beam_impl.AnalyzeAndTransformDataset(
                    preprocessing_fn))

            transformed_data, transformed_metadata = transformed_dataset

            transformed_data | "WriteTrainTFRecords" >> tfrecordio.WriteToTFRecord(
                    file_path_prefix=self.JOB_DIR + '/train/data',
                    file_name_suffix='.tfrecord',
                    coder=example_proto_coder.ExampleProtoCoder(transformed_metadata.schema))

            _ = (
                        transform_fn
                        | 'WriteTransformFn' >>
                        transform_fn_io.WriteTransformFn(path=self.JOB_DIR + '/transform/'))

最后ParDo()是:

class ProcessFn(beam.DoFn):

    def process(self, element):

        yield { 'id' : [list], 'amount': [list], 'age': [list] }
4

1 回答 1

7

问题出在片段上

raw_features = {}
for k in features:
    raw_features.update({k: tf.constant(1)})

print(tf_transform_output.transform_raw_features(raw_features))

在此代码中,您构建一个字典,其中值是张量。就像你说的,这对VarLenFeature. 而不是使用tf.constant尝试使用tf.placeholderfor aaFixedLenFeaturetf.sparse_placeholderfor a VarLenFeature

于 2019-01-25T20:25:23.807 回答