이 페이지는 Cloud Translation API를 통해 번역되었습니다.
Switch to English

TensorFlow Transform으로 데이터 전처리

TensorFlow Extended (TFX)의 기능 엔지니어링 구성 요소

이 예제 colab 노트북은 TensorFlow Transform ( tf.Transform )을 사용하여 모델을 학습시키고 프로덕션에서 추론을 제공하기 위해 정확히 동일한 코드를 사용하여 데이터를 사전 처리하는 방법에 대한 다소 고급 예제를 제공합니다.

TensorFlow Transform은 학습 데이터 세트 전체를 통과해야하는 기능 생성을 포함하여 TensorFlow의 입력 데이터를 사전 처리하기위한 라이브러리입니다. 예를 들어 TensorFlow Transform을 사용하여 다음을 수행 할 수 있습니다.

  • 평균 및 표준 편차를 사용하여 입력 값 정규화
  • 모든 입력 값에 대해 어휘를 생성하여 문자열을 정수로 변환
  • 관찰 된 데이터 분포에 따라 부동 소수점을 버킷에 할당하여 정수로 변환

TensorFlow에는 단일 예제 또는 예제 일괄 처리에 대한 기본 제공 지원이 있습니다. tf.Transform 은 이러한 기능을 확장하여 전체 학습 데이터 세트에 대한 전체 패스를 지원합니다.

tf.Transform 의 출력은 학습 및 제공 모두에 사용할 수있는 TensorFlow 그래프로 내보내집니다. 학습과 제공에 동일한 그래프를 사용하면 두 단계 모두에 동일한 변환이 적용되므로 편향을 방지 할 수 있습니다.

이 예에서 우리가하는 일

이 예에서는 인구 조사 데이터가 포함널리 사용되는 데이터 세트를 처리하고 분류를 수행하도록 모델을 학습합니다. 그 과정에서 tf.Transform 사용하여 데이터를 변환 할 것입니다.

Pip 업그레이드

로컬에서 실행할 때 시스템에서 Pip을 업그레이드하지 않으려면 Colab에서 실행 중인지 확인하십시오. 물론 로컬 시스템은 별도로 업그레이드 할 수 있습니다.

try:
  import colab
  !pip install --upgrade pip
except:
  pass

TensorFlow 설치

pip install tensorflow==2.2.0
Collecting tensorflow==2.2.0
  Using cached tensorflow-2.2.0-cp36-cp36m-manylinux2010_x86_64.whl (516.2 MB)
Requirement already satisfied: opt-einsum>=2.3.2 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorflow==2.2.0) (3.3.0)
Requirement already satisfied: keras-preprocessing>=1.1.0 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorflow==2.2.0) (1.1.2)
Requirement already satisfied: absl-py>=0.7.0 in /home/kbuilder/.local/lib/python3.6/site-packages (from tensorflow==2.2.0) (0.9.0)
Requirement already satisfied: six>=1.12.0 in /home/kbuilder/.local/lib/python3.6/site-packages (from tensorflow==2.2.0) (1.15.0)
Requirement already satisfied: protobuf>=3.8.0 in /home/kbuilder/.local/lib/python3.6/site-packages (from tensorflow==2.2.0) (3.13.0)
Collecting tensorflow-estimator<2.3.0,>=2.2.0
  Using cached tensorflow_estimator-2.2.0-py2.py3-none-any.whl (454 kB)
Requirement already satisfied: wrapt>=1.11.1 in /home/kbuilder/.local/lib/python3.6/site-packages (from tensorflow==2.2.0) (1.12.1)
Requirement already satisfied: termcolor>=1.1.0 in /home/kbuilder/.local/lib/python3.6/site-packages (from tensorflow==2.2.0) (1.1.0)
Requirement already satisfied: numpy<2.0,>=1.16.0 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorflow==2.2.0) (1.18.5)
Requirement already satisfied: scipy==1.4.1; python_version >= "3" in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorflow==2.2.0) (1.4.1)
Collecting tensorboard<2.3.0,>=2.2.0
  Using cached tensorboard-2.2.2-py3-none-any.whl (3.0 MB)
Requirement already satisfied: google-pasta>=0.1.8 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorflow==2.2.0) (0.2.0)
Requirement already satisfied: grpcio>=1.8.6 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorflow==2.2.0) (1.31.0)
Requirement already satisfied: wheel>=0.26; python_version >= "3" in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorflow==2.2.0) (0.35.1)
Requirement already satisfied: astunparse==1.6.3 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorflow==2.2.0) (1.6.3)
Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorflow==2.2.0) (2.10.0)
Requirement already satisfied: gast==0.3.3 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorflow==2.2.0) (0.3.3)
Requirement already satisfied: setuptools in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from protobuf>=3.8.0->tensorflow==2.2.0) (49.6.0)
Requirement already satisfied: markdown>=2.6.8 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (3.2.2)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.7.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (0.4.1)
Requirement already satisfied: google-auth<2,>=1.6.3 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.20.1)
Requirement already satisfied: werkzeug>=0.11.15 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.0.1)
Requirement already satisfied: requests<3,>=2.21.0 in /home/kbuilder/.local/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (2.24.0)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in /home/kbuilder/.local/lib/python3.6/site-packages (from markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.7.0)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.3.0)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/lib/python3/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (0.2.1)
Requirement already satisfied: rsa<5,>=3.1.4; python_version >= "3.5" in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (4.6)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /home/kbuilder/.local/lib/python3.6/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (4.1.1)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (2.6)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (1.22)
Requirement already satisfied: certifi>=2017.4.17 in /home/kbuilder/.local/lib/python3.6/site-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (2020.6.20)
Requirement already satisfied: zipp>=0.5 in /home/kbuilder/.local/lib/python3.6/site-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (3.1.0)
Requirement already satisfied: oauthlib>=3.0.0 in /tmpfs/src/tf_docs_env/lib/python3.6/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (3.1.0)
Requirement already satisfied: pyasn1>=0.1.3 in /usr/lib/python3/dist-packages (from rsa<5,>=3.1.4; python_version >= "3.5"->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow==2.2.0) (0.4.2)
Installing collected packages: tensorflow-estimator, tensorboard, tensorflow
  Attempting uninstall: tensorflow-estimator
    Found existing installation: tensorflow-estimator 2.3.0
    Uninstalling tensorflow-estimator-2.3.0:
      Successfully uninstalled tensorflow-estimator-2.3.0
  Attempting uninstall: tensorboard
    Found existing installation: tensorboard 2.3.0
    Uninstalling tensorboard-2.3.0:
      Successfully uninstalled tensorboard-2.3.0
  Attempting uninstall: tensorflow
    Found existing installation: tensorflow 2.3.0
    Uninstalling tensorflow-2.3.0:
      Successfully uninstalled tensorflow-2.3.0
Successfully installed tensorboard-2.2.2 tensorflow-2.2.0 tensorflow-estimator-2.2.0

Python 검사, 가져 오기 및 전역

먼저 Python 3을 사용하고 있는지 확인한 다음 필요한 항목을 설치하고 가져옵니다.

import sys

# Confirm that we're using Python 3
assert sys.version_info.major is 3, 'Oops, not running Python 3. Use Runtime > Change runtime type'
import os
import pprint

import tensorflow as tf
print('TF: {}'.format(tf.__version__))

print('Installing Apache Beam')
!pip install -Uq apache_beam==2.21.0
import apache_beam as beam
print('Beam: {}'.format(beam.__version__))

print('Installing TensorFlow Transform')
!pip install -q tensorflow-transform==0.22.0
import tensorflow_transform as tft
print('Transform: {}'.format(tft.__version__))

import tensorflow_transform.beam as tft_beam

!wget https://storage.googleapis.com/artifacts.tfx-oss-public.appspot.com/datasets/census/adult.data
!wget https://storage.googleapis.com/artifacts.tfx-oss-public.appspot.com/datasets/census/adult.test

train = './adult.data'
test = './adult.test'
TF: 2.2.0
Installing Apache Beam
Beam: 2.21.0
Installing TensorFlow Transform
ERROR: After October 2020 you may experience errors when installing or updating packages. This is because pip will change the way that it resolves dependency conflicts.

We recommend you use --use-feature=2020-resolver to test your packages with the new resolver before it becomes the default.

tensorflow-serving-api 2.3.0 requires tensorflow<3,>=2.3, but you'll have tensorflow 2.2.0 which is incompatible.
Transform: 0.22.0
--2020-08-18 09:24:09--  https://storage.googleapis.com/artifacts.tfx-oss-public.appspot.com/datasets/census/adult.data
Resolving storage.googleapis.com (storage.googleapis.com)... 64.233.189.128, 108.177.97.128, 108.177.125.128, ...
Connecting to storage.googleapis.com (storage.googleapis.com)|64.233.189.128|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3974305 (3.8M) [application/octet-stream]
Saving to: ‘adult.data’

adult.data          100%[===================>]   3.79M  --.-KB/s    in 0.02s   

2020-08-18 09:24:10 (216 MB/s) - ‘adult.data’ saved [3974305/3974305]

--2020-08-18 09:24:10--  https://storage.googleapis.com/artifacts.tfx-oss-public.appspot.com/datasets/census/adult.test
Resolving storage.googleapis.com (storage.googleapis.com)... 64.233.188.128, 74.125.203.128, 108.177.125.128, ...
Connecting to storage.googleapis.com (storage.googleapis.com)|64.233.188.128|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2003153 (1.9M) [application/octet-stream]
Saving to: ‘adult.test’

adult.test          100%[===================>]   1.91M  --.-KB/s    in 0.02s   

2020-08-18 09:24:11 (96.5 MB/s) - ‘adult.test’ saved [2003153/2003153]


열 이름 지정

데이터 세트의 열을 참조하기위한 몇 가지 편리한 목록을 만들 것입니다.

CATEGORICAL_FEATURE_KEYS = [
    'workclass',
    'education',
    'marital-status',
    'occupation',
    'relationship',
    'race',
    'sex',
    'native-country',
]
NUMERIC_FEATURE_KEYS = [
    'age',
    'capital-gain',
    'capital-loss',
    'hours-per-week',
]
OPTIONAL_NUMERIC_FEATURE_KEYS = [
    'education-num',
]
LABEL_KEY = 'label'

기능 및 스키마 정의

입력에있는 열의 유형을 기반으로 스키마를 정의 해 보겠습니다. 무엇보다도 이것은 올바르게 가져 오는 데 도움이됩니다.

RAW_DATA_FEATURE_SPEC = dict(
    [(name, tf.io.FixedLenFeature([], tf.string))
     for name in CATEGORICAL_FEATURE_KEYS] +
    [(name, tf.io.FixedLenFeature([], tf.float32))
     for name in NUMERIC_FEATURE_KEYS] +
    [(name, tf.io.VarLenFeature(tf.float32))
     for name in OPTIONAL_NUMERIC_FEATURE_KEYS] +
    [(LABEL_KEY, tf.io.FixedLenFeature([], tf.string))]
)

RAW_DATA_METADATA = tft.tf_metadata.dataset_metadata.DatasetMetadata(
    tft.tf_metadata.dataset_schema.schema_utils.schema_from_feature_spec(RAW_DATA_FEATURE_SPEC))

초 매개 변수 및 기본 관리 설정

훈련에 사용되는 상수 및 초 매개 변수. 버킷 크기에는 데이터 세트 설명에 나열된 모든 범주와 "?"에 대한 추가 범주가 포함됩니다. 알 수 없음을 나타냅니다.

testing = os.getenv("WEB_TEST_BROWSER", False)
if testing:
  TRAIN_NUM_EPOCHS = 1
  NUM_TRAIN_INSTANCES = 1
  TRAIN_BATCH_SIZE = 1
  NUM_TEST_INSTANCES = 1
else:
  TRAIN_NUM_EPOCHS = 16
  NUM_TRAIN_INSTANCES = 32561
  TRAIN_BATCH_SIZE = 128
  NUM_TEST_INSTANCES = 16281

# Names of temp files
TRANSFORMED_TRAIN_DATA_FILEBASE = 'train_transformed'
TRANSFORMED_TEST_DATA_FILEBASE = 'test_transformed'
EXPORTED_MODEL_DIR = 'exported_model_dir'

청소

입력 데이터 정리를위한 빔 변환 생성

Apache Beam의 PTransform 클래스의 하위 클래스를 생성하고 실제 처리 로직을 지정하기 위해 expand 메서드를 재정 의하여 Beam Transform 을 생성합니다. PTransform 은 파이프 라인의 데이터 처리 작업 또는 단계를 나타냅니다. 모든 PTransform 은 하나 이상의 PCollection 개체를 입력으로 사용하고 해당 PCollection 의 요소에 대해 제공하는 처리 기능을 수행하며 0 개 이상의 출력 PCollection 개체를 생성합니다.

우리의 변환 클래스는 빔의 적용 ParDo 입력에 PCollection 출력 깨끗한 데이터를 생성, 우리의 인구 조사 데이터 집합을 포함 PCollection .

class MapAndFilterErrors(beam.PTransform):
  """Like beam.Map but filters out errors in the map_fn."""

  class _MapAndFilterErrorsDoFn(beam.DoFn):
    """Count the bad examples using a beam metric."""

    def __init__(self, fn):
      self._fn = fn
      # Create a counter to measure number of bad elements.
      self._bad_elements_counter = beam.metrics.Metrics.counter(
          'census_example', 'bad_elements')

    def process(self, element):
      try:
        yield self._fn(element)
      except Exception:  # pylint: disable=broad-except
        # Catch any exception the above call.
        self._bad_elements_counter.inc(1)

  def __init__(self, fn):
    self._fn = fn

  def expand(self, pcoll):
    return pcoll | beam.ParDo(self._MapAndFilterErrorsDoFn(self._fn))

tf.Transform 전처리

tf.Transform preprocessing_fn 만들기

전처리 기능 은 tf.Transform의 가장 중요한 개념입니다. 전처리 기능은 데이터 세트의 변환이 실제로 발생하는 곳입니다. 텐서는 Tensor 또는 SparseTensor 의미하는 Tensor 사전을 허용하고 반환합니다. 일반적으로 전처리 기능의 핵심을 형성하는 두 가지 주요 API 호출 그룹이 있습니다.

  1. TensorFlow Ops : 일반적으로 TensorFlow 작업을 의미하는 텐서를 수락하고 반환하는 모든 함수입니다. 이렇게하면 원시 데이터를 한 번에 하나의 특성 벡터로 변환 된 데이터로 변환하는 TensorFlow 작업이 그래프에 추가됩니다. 이는 훈련과 서빙 중 모든 예에서 실행됩니다.
  2. TensorFlow Transform Analyzers : tf.Transform에서 제공하는 모든 분석기. 분석기는 또한 텐서를 수락하고 반환하지만 TensorFlow 작업과 달리 학습 중에 한 번만 실행되며 일반적으로 전체 학습 데이터 세트에 대해 전체 패스를 수행합니다. 그들은 그래프에 추가되는 텐서 상수를 만듭니다. 예를 들어 tft.min 은 훈련 데이터 세트에 대한 텐서의 최소값을 계산합니다. tf.Transform은 고정 된 분석기 세트를 제공하지만 향후 버전에서 확장 될 예정입니다.
def preprocessing_fn(inputs):
  """Preprocess input columns into transformed columns."""
  # Since we are modifying some features and leaving others unchanged, we
  # start by setting `outputs` to a copy of `inputs.
  outputs = inputs.copy()

  # Scale numeric columns to have range [0, 1].
  for key in NUMERIC_FEATURE_KEYS:
    outputs[key] = tft.scale_to_0_1(outputs[key])

  for key in OPTIONAL_NUMERIC_FEATURE_KEYS:
    # This is a SparseTensor because it is optional. Here we fill in a default
    # value when it is missing.
    sparse = tf.sparse.SparseTensor(outputs[key].indices, outputs[key].values,
                                    [outputs[key].dense_shape[0], 1])
    dense = tf.sparse.to_dense(sp_input=sparse, default_value=0.)
    # Reshaping from a batch of vectors of size 1 to a batch to scalars.
    dense = tf.squeeze(dense, axis=1)
    outputs[key] = tft.scale_to_0_1(dense)

  # For all categorical columns except the label column, we generate a
  # vocabulary but do not modify the feature.  This vocabulary is instead
  # used in the trainer, by means of a feature column, to convert the feature
  # from a string to an integer id.
  for key in CATEGORICAL_FEATURE_KEYS:
    tft.vocabulary(inputs[key], vocab_filename=key)

  # For the label column we provide the mapping from string to index.
  table_keys = ['>50K', '<=50K']
  initializer = tf.lookup.KeyValueTensorInitializer(
      keys=table_keys,
      values=tf.cast(tf.range(len(table_keys)), tf.int64),
      key_dtype=tf.string,
      value_dtype=tf.int64)
  table = tf.lookup.StaticHashTable(initializer, default_value=-1)
  outputs[LABEL_KEY] = table.lookup(outputs[LABEL_KEY])

  return outputs

데이터 변환

이제 Apache Beam 파이프 라인에서 데이터 변환을 시작할 준비가되었습니다.

  1. CSV 리더를 사용하여 데이터 읽기
  2. 새로운 MapAndFilterErrors 변환을 사용하여 정리
  3. 각 범주에 대한 어휘를 생성하여 숫자 데이터를 확장하고 범주 형 데이터를 문자열에서 int64 값 인덱스로 변환하는 전처리 파이프 라인을 사용하여 변환합니다.
  4. 결과를 Example TFRecordTFRecord 로 작성합니다. 나중에 모델 학습에 사용할 것입니다.
def transform_data(train_data_file, test_data_file, working_dir):
  """Transform the data and write out as a TFRecord of Example protos.

  Read in the data using the CSV reader, and transform it using a
  preprocessing pipeline that scales numeric data and converts categorical data
  from strings to int64 values indices, by creating a vocabulary for each
  category.

  Args:
    train_data_file: File containing training data
    test_data_file: File containing test data
    working_dir: Directory to write transformed data and metadata to
  """

  # The "with" block will create a pipeline, and run that pipeline at the exit
  # of the block.
  with beam.Pipeline() as pipeline:
    with tft_beam.Context(temp_dir=tempfile.mkdtemp()):
      # Create a coder to read the census data with the schema.  To do this we
      # need to list all columns in order since the schema doesn't specify the
      # order of columns in the csv.
      ordered_columns = [
          'age', 'workclass', 'fnlwgt', 'education', 'education-num',
          'marital-status', 'occupation', 'relationship', 'race', 'sex',
          'capital-gain', 'capital-loss', 'hours-per-week', 'native-country',
          'label'
      ]
      converter = tft.coders.CsvCoder(ordered_columns, RAW_DATA_METADATA.schema)

      # Read in raw data and convert using CSV converter.  Note that we apply
      # some Beam transformations here, which will not be encoded in the TF
      # graph since we don't do them from within tf.Transform's methods
      # (AnalyzeDataset, TransformDataset etc.).  These transformations are just
      # to get data into a format that the CSV converter can read, in particular
      # removing spaces after commas.
      #
      # We use MapAndFilterErrors instead of Map to filter out decode errors in
      # convert.decode which should only occur for the trailing blank line.
      raw_data = (
          pipeline
          | 'ReadTrainData' >> beam.io.ReadFromText(train_data_file)
          | 'FixCommasTrainData' >> beam.Map(
              lambda line: line.replace(', ', ','))
          | 'DecodeTrainData' >> MapAndFilterErrors(converter.decode))

      # Combine data and schema into a dataset tuple.  Note that we already used
      # the schema to read the CSV data, but we also need it to interpret
      # raw_data.
      raw_dataset = (raw_data, RAW_DATA_METADATA)
      transformed_dataset, transform_fn = (
          raw_dataset | tft_beam.AnalyzeAndTransformDataset(preprocessing_fn))
      transformed_data, transformed_metadata = transformed_dataset
      transformed_data_coder = tft.coders.ExampleProtoCoder(
          transformed_metadata.schema)

      _ = (
          transformed_data
          | 'EncodeTrainData' >> beam.Map(transformed_data_coder.encode)
          | 'WriteTrainData' >> beam.io.WriteToTFRecord(
              os.path.join(working_dir, TRANSFORMED_TRAIN_DATA_FILEBASE)))

      # Now apply transform function to test data.  In this case we remove the
      # trailing period at the end of each line, and also ignore the header line
      # that is present in the test data file.
      raw_test_data = (
          pipeline
          | 'ReadTestData' >> beam.io.ReadFromText(test_data_file,
                                                   skip_header_lines=1)
          | 'FixCommasTestData' >> beam.Map(
              lambda line: line.replace(', ', ','))
          | 'RemoveTrailingPeriodsTestData' >> beam.Map(lambda line: line[:-1])
          | 'DecodeTestData' >> MapAndFilterErrors(converter.decode))

      raw_test_dataset = (raw_test_data, RAW_DATA_METADATA)

      transformed_test_dataset = (
          (raw_test_dataset, transform_fn) | tft_beam.TransformDataset())
      # Don't need transformed data schema, it's the same as before.
      transformed_test_data, _ = transformed_test_dataset

      _ = (
          transformed_test_data
          | 'EncodeTestData' >> beam.Map(transformed_data_coder.encode)
          | 'WriteTestData' >> beam.io.WriteToTFRecord(
              os.path.join(working_dir, TRANSFORMED_TEST_DATA_FILEBASE)))

      # Will write a SavedModel and metadata to working_dir, which can then
      # be read by the tft.TFTransformOutput class.
      _ = (
          transform_fn
          | 'WriteTransformFn' >> tft_beam.WriteTransformFn(working_dir))

전처리 된 데이터를 사용하여 모델 학습

tf.Transform 통해 학습과 제공 모두에 동일한 코드를 사용하여 왜곡을 방지하는 방법을 보여주기 위해 모델을 학습 할 것입니다. 모델을 훈련하고 생산을 위해 훈련 된 모델을 준비하려면 입력 함수를 만들어야합니다. 학습 입력 함수와 제공 입력 함수의 주요 차이점은 학습 데이터에는 레이블이 포함되고 프로덕션 데이터에는 포함되지 않는다는 것입니다. 인수와 반환도 약간 다릅니다.

훈련을위한 입력 함수 만들기

def _make_training_input_fn(tf_transform_output, transformed_examples,
                            batch_size):
  """Creates an input function reading from transformed data.

  Args:
    tf_transform_output: Wrapper around output of tf.Transform.
    transformed_examples: Base filename of examples.
    batch_size: Batch size.

  Returns:
    The input function for training or eval.
  """
  def input_fn():
    """Input function for training and eval."""
    dataset = tf.data.experimental.make_batched_features_dataset(
        file_pattern=transformed_examples,
        batch_size=batch_size,
        features=tf_transform_output.transformed_feature_spec(),
        reader=tf.data.TFRecordDataset,
        shuffle=True)

    transformed_features = tf.compat.v1.data.make_one_shot_iterator(
        dataset).get_next()

    # Extract features and label from the transformed tensors.
    transformed_labels = transformed_features.pop(LABEL_KEY)

    return transformed_features, transformed_labels

  return input_fn

제공하기위한 입력 함수 만들기

프로덕션에서 사용할 수있는 입력 함수를 만들고 제공 할 훈련 된 모델을 준비해 보겠습니다.

def _make_serving_input_fn(tf_transform_output):
  """Creates an input function reading from raw data.

  Args:
    tf_transform_output: Wrapper around output of tf.Transform.

  Returns:
    The serving input function.
  """
  raw_feature_spec = RAW_DATA_FEATURE_SPEC.copy()
  # Remove label since it is not available during serving.
  raw_feature_spec.pop(LABEL_KEY)

  def serving_input_fn():
    """Input function for serving."""
    # Get raw features by generating the basic serving input_fn and calling it.
    # Here we generate an input_fn that expects a parsed Example proto to be fed
    # to the model at serving time.  See also
    # tf.estimator.export.build_raw_serving_input_receiver_fn.
    raw_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(
        raw_feature_spec, default_batch_size=None)
    serving_input_receiver = raw_input_fn()

    # Apply the transform function that was used to generate the materialized
    # data.
    raw_features = serving_input_receiver.features
    transformed_features = tf_transform_output.transform_raw_features(
        raw_features)

    return tf.estimator.export.ServingInputReceiver(
        transformed_features, serving_input_receiver.receiver_tensors)

  return serving_input_fn

입력 데이터를 FeatureColumns로 래핑

모델은 TensorFlow FeatureColumns에서 데이터를 예상합니다.

def get_feature_columns(tf_transform_output):
  """Returns the FeatureColumns for the model.

  Args:
    tf_transform_output: A `TFTransformOutput` object.

  Returns:
    A list of FeatureColumns.
  """
  # Wrap scalars as real valued columns.
  real_valued_columns = [tf.feature_column.numeric_column(key, shape=())
                         for key in NUMERIC_FEATURE_KEYS]

  # Wrap categorical columns.
  one_hot_columns = [
      tf.feature_column.categorical_column_with_vocabulary_file(
          key=key,
          vocabulary_file=tf_transform_output.vocabulary_file_by_name(
              vocab_filename=key))
      for key in CATEGORICAL_FEATURE_KEYS]

  return real_valued_columns + one_hot_columns

모델 훈련, 평가 및 내보내기

def train_and_evaluate(working_dir, num_train_instances=NUM_TRAIN_INSTANCES,
                       num_test_instances=NUM_TEST_INSTANCES):
  """Train the model on training data and evaluate on test data.

  Args:
    working_dir: Directory to read transformed data and metadata from and to
        write exported model to.
    num_train_instances: Number of instances in train set
    num_test_instances: Number of instances in test set

  Returns:
    The results from the estimator's 'evaluate' method
  """
  tf_transform_output = tft.TFTransformOutput(working_dir)

  run_config = tf.estimator.RunConfig()

  estimator = tf.estimator.LinearClassifier(
      feature_columns=get_feature_columns(tf_transform_output),
      config=run_config,
      loss_reduction=tf.losses.Reduction.SUM)

  # Fit the model using the default optimizer.
  train_input_fn = _make_training_input_fn(
      tf_transform_output,
      os.path.join(working_dir, TRANSFORMED_TRAIN_DATA_FILEBASE + '*'),
      batch_size=TRAIN_BATCH_SIZE)
  estimator.train(
      input_fn=train_input_fn,
      max_steps=TRAIN_NUM_EPOCHS * num_train_instances / TRAIN_BATCH_SIZE)

  # Evaluate model on test dataset.
  eval_input_fn = _make_training_input_fn(
      tf_transform_output,
      os.path.join(working_dir, TRANSFORMED_TEST_DATA_FILEBASE + '*'),
      batch_size=1)

  # Export the model.
  serving_input_fn = _make_serving_input_fn(tf_transform_output)
  exported_model_dir = os.path.join(working_dir, EXPORTED_MODEL_DIR)
  estimator.export_saved_model(exported_model_dir, serving_input_fn)

  return estimator.evaluate(input_fn=eval_input_fn, steps=num_test_instances)

모두 모아

인구 조사 데이터를 전처리하고, 모델을 훈련시키고, 제공 할 준비를하는 데 필요한 모든 것을 만들었습니다. 지금까지 우리는 준비를 마쳤습니다. 달리기를 시작할 시간입니다!

import tempfile
temp = tempfile.gettempdir()

transform_data(train, test, temp)
results = train_and_evaluate(temp)
pprint.pprint(results)
WARNING:apache_beam.runners.interactive.interactive_environment:Dependencies required for Interactive Beam PCollection visualization are not available, please use: `pip install apache-beam[interactive]` to install necessary dependencies to enable all data visualization features.

Warning:tensorflow:Tensorflow version (2.2.0) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 

Warning:tensorflow:Tensorflow version (2.2.0) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 

Warning:tensorflow:Tensorflow version (2.2.0) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 

Warning:tensorflow:Tensorflow version (2.2.0) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_transform/tf_utils.py:220: Tensor.experimental_ref (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use ref() instead.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_transform/tf_utils.py:220: Tensor.experimental_ref (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use ref() instead.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/saved_model/signature_def_utils_impl.py:201: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/saved_model/signature_def_utils_impl.py:201: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.

INFO:tensorflow:Assets added to graph.

INFO:tensorflow:Assets added to graph.

INFO:tensorflow:No assets to write.

INFO:tensorflow:No assets to write.

Warning:tensorflow:Issue encountered when serializing tft_mapper_use.
Type is unsupported, or the types of the items don't match field type in CollectionDef. Note this is a warning and probably safe to ignore.
'Counter' object has no attribute 'name'

Warning:tensorflow:Issue encountered when serializing tft_mapper_use.
Type is unsupported, or the types of the items don't match field type in CollectionDef. Note this is a warning and probably safe to ignore.
'Counter' object has no attribute 'name'

Warning:tensorflow:Issue encountered when serializing tft_analyzer_use.
Type is unsupported, or the types of the items don't match field type in CollectionDef. Note this is a warning and probably safe to ignore.
'Counter' object has no attribute 'name'

Warning:tensorflow:Issue encountered when serializing tft_analyzer_use.
Type is unsupported, or the types of the items don't match field type in CollectionDef. Note this is a warning and probably safe to ignore.
'Counter' object has no attribute 'name'

INFO:tensorflow:SavedModel written to: /tmp/tmptntmkgtc/tftransform_tmp/6807e6f02233499db5d910c34462bba9/saved_model.pb

INFO:tensorflow:SavedModel written to: /tmp/tmptntmkgtc/tftransform_tmp/6807e6f02233499db5d910c34462bba9/saved_model.pb

INFO:tensorflow:Assets added to graph.

INFO:tensorflow:Assets added to graph.

INFO:tensorflow:No assets to write.

INFO:tensorflow:No assets to write.

Warning:tensorflow:Issue encountered when serializing tft_mapper_use.
Type is unsupported, or the types of the items don't match field type in CollectionDef. Note this is a warning and probably safe to ignore.
'Counter' object has no attribute 'name'

Warning:tensorflow:Issue encountered when serializing tft_mapper_use.
Type is unsupported, or the types of the items don't match field type in CollectionDef. Note this is a warning and probably safe to ignore.
'Counter' object has no attribute 'name'

Warning:tensorflow:Issue encountered when serializing tft_analyzer_use.
Type is unsupported, or the types of the items don't match field type in CollectionDef. Note this is a warning and probably safe to ignore.
'Counter' object has no attribute 'name'

Warning:tensorflow:Issue encountered when serializing tft_analyzer_use.
Type is unsupported, or the types of the items don't match field type in CollectionDef. Note this is a warning and probably safe to ignore.
'Counter' object has no attribute 'name'

INFO:tensorflow:SavedModel written to: /tmp/tmptntmkgtc/tftransform_tmp/d350b2f9afca405f80c7f6069b138eb0/saved_model.pb

INFO:tensorflow:SavedModel written to: /tmp/tmptntmkgtc/tftransform_tmp/d350b2f9afca405f80c7f6069b138eb0/saved_model.pb

Warning:tensorflow:Tensorflow version (2.2.0) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 

Warning:tensorflow:Tensorflow version (2.2.0) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 

Warning:tensorflow:Tensorflow version (2.2.0) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 

Warning:tensorflow:Tensorflow version (2.2.0) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 
WARNING:apache_beam.utils.interactive_utils:Failed to alter the label of a transform with the ipython prompt metadata. Cannot figure out the pipeline that the given pvalueish ((<PCollection[DecodeTestData/ParDo(_MapAndFilterErrorsDoFn).None] at 0x7f042c2f0be0>, {'_schema': feature {
  name: "age"
  type: FLOAT
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "capital-gain"
  type: FLOAT
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "capital-loss"
  type: FLOAT
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "education"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "education-num"
  type: FLOAT
}
feature {
  name: "hours-per-week"
  type: FLOAT
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "label"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "marital-status"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "native-country"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "occupation"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "race"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "relationship"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "sex"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "workclass"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
}), (<PCollection[AnalyzeAndTransformDataset/AnalyzeDataset/CreateSavedModel/BindTensors/ReplaceWithConstants.None] at 0x7f042c318550>, BeamDatasetMetadata(dataset_metadata={'_schema': feature {
  name: "age"
  type: FLOAT
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "capital-gain"
  type: FLOAT
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "capital-loss"
  type: FLOAT
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "education"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "education-num"
  type: FLOAT
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "hours-per-week"
  type: FLOAT
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "label"
  type: INT
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "marital-status"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "native-country"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "occupation"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "race"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "relationship"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "sex"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
feature {
  name: "workclass"
  type: BYTES
  presence {
    min_fraction: 1.0
  }
  shape {
  }
}
}, deferred_metadata=<PCollection[AnalyzeAndTransformDataset/AnalyzeDataset/ComputeDeferredMetadata.None] at 0x7f042c2fce48>))) belongs to. Thus noop.

INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:tensorflow:Assets added to graph.

INFO:tensorflow:Assets added to graph.

INFO:tensorflow:Assets written to: /tmp/tmptntmkgtc/tftransform_tmp/a838335ddf08440faef27b83689d05cf/assets

INFO:tensorflow:Assets written to: /tmp/tmptntmkgtc/tftransform_tmp/a838335ddf08440faef27b83689d05cf/assets

INFO:tensorflow:SavedModel written to: /tmp/tmptntmkgtc/tftransform_tmp/a838335ddf08440faef27b83689d05cf/saved_model.pb

INFO:tensorflow:SavedModel written to: /tmp/tmptntmkgtc/tftransform_tmp/a838335ddf08440faef27b83689d05cf/saved_model.pb

Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_3:0\022\tworkclass"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_3:0\022\tworkclass"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_5:0\022\teducation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_5:0\022\teducation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_7:0\022\016marital-status"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_7:0\022\016marital-status"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_9:0\022\noccupation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_9:0\022\noccupation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_11:0\022\014relationship"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_11:0\022\014relationship"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_13:0\022\004race"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_13:0\022\004race"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_15:0\022\003sex"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_15:0\022\003sex"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_17:0\022\016native-country"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_17:0\022\016native-country"


INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:tensorflow:Saver not created because there are no variables in the graph to restore

Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_3:0\022\tworkclass"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_3:0\022\tworkclass"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_5:0\022\teducation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_5:0\022\teducation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_7:0\022\016marital-status"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_7:0\022\016marital-status"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_9:0\022\noccupation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_9:0\022\noccupation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_11:0\022\014relationship"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_11:0\022\014relationship"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_13:0\022\004race"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_13:0\022\004race"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_15:0\022\003sex"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_15:0\022\003sex"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_17:0\022\016native-country"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_17:0\022\016native-country"


INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:tensorflow:Saver not created because there are no variables in the graph to restore
WARNING:apache_beam.io.tfrecordio:Couldn't find python-snappy so the implementation of _TFRecordUtil._masked_crc32c is not as fast as it could be.

Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_3:0\022\tworkclass"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_3:0\022\tworkclass"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_5:0\022\teducation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_5:0\022\teducation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_7:0\022\016marital-status"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_7:0\022\016marital-status"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_9:0\022\noccupation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_9:0\022\noccupation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_11:0\022\014relationship"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_11:0\022\014relationship"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_13:0\022\004race"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_13:0\022\004race"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_15:0\022\003sex"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_15:0\022\003sex"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_17:0\022\016native-country"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_17:0\022\016native-country"


INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:tensorflow:vocabulary_size = 9 in workclass is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/workclass.

INFO:tensorflow:vocabulary_size = 9 in workclass is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/workclass.

INFO:tensorflow:vocabulary_size = 16 in education is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/education.

INFO:tensorflow:vocabulary_size = 16 in education is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/education.

INFO:tensorflow:vocabulary_size = 7 in marital-status is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/marital-status.

INFO:tensorflow:vocabulary_size = 7 in marital-status is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/marital-status.

INFO:tensorflow:vocabulary_size = 15 in occupation is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/occupation.

INFO:tensorflow:vocabulary_size = 15 in occupation is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/occupation.

INFO:tensorflow:vocabulary_size = 6 in relationship is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/relationship.

INFO:tensorflow:vocabulary_size = 6 in relationship is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/relationship.

INFO:tensorflow:vocabulary_size = 5 in race is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/race.

INFO:tensorflow:vocabulary_size = 5 in race is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/race.

INFO:tensorflow:vocabulary_size = 2 in sex is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/sex.

INFO:tensorflow:vocabulary_size = 2 in sex is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/sex.

INFO:tensorflow:vocabulary_size = 42 in native-country is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/native-country.

INFO:tensorflow:vocabulary_size = 42 in native-country is inferred from the number of elements in the vocabulary_file /tmp/transform_fn/assets/native-country.

Warning:tensorflow:Using temporary folder as model directory: /tmp/tmputnc4riv

Warning:tensorflow:Using temporary folder as model directory: /tmp/tmputnc4riv

INFO:tensorflow:Using config: {'_model_dir': '/tmp/tmputnc4riv', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true
graph_options {
  rewrite_options {
    meta_optimizer_iterations: ONE
  }
}
, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}

INFO:tensorflow:Using config: {'_model_dir': '/tmp/tmputnc4riv', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true
graph_options {
  rewrite_options {
    meta_optimizer_iterations: ONE
  }
}
, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/ops/resource_variable_ops.py:1666: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/ops/resource_variable_ops.py:1666: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.

INFO:tensorflow:Calling model_fn.

INFO:tensorflow:Calling model_fn.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/feature_column/feature_column_v2.py:540: Layer.add_variable (from tensorflow.python.keras.engine.base_layer_v1) is deprecated and will be removed in a future version.
Instructions for updating:
Please use `layer.add_weight` method instead.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/feature_column/feature_column_v2.py:540: Layer.add_variable (from tensorflow.python.keras.engine.base_layer_v1) is deprecated and will be removed in a future version.
Instructions for updating:
Please use `layer.add_weight` method instead.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/optimizer_v2/ftrl.py:144: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/optimizer_v2/ftrl.py:144: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor

INFO:tensorflow:Done calling model_fn.

INFO:tensorflow:Done calling model_fn.

INFO:tensorflow:Create CheckpointSaverHook.

INFO:tensorflow:Create CheckpointSaverHook.

INFO:tensorflow:Graph was finalized.

INFO:tensorflow:Graph was finalized.

INFO:tensorflow:Running local_init_op.

INFO:tensorflow:Running local_init_op.

INFO:tensorflow:Done running local_init_op.

INFO:tensorflow:Done running local_init_op.

INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0...

INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0...

INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmputnc4riv/model.ckpt.

INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmputnc4riv/model.ckpt.

INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0...

INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0...

INFO:tensorflow:loss = 88.72284, step = 0

INFO:tensorflow:loss = 88.72284, step = 0

INFO:tensorflow:global_step/sec: 76.9862

INFO:tensorflow:global_step/sec: 76.9862

INFO:tensorflow:loss = 38.703667, step = 100 (1.301 sec)

INFO:tensorflow:loss = 38.703667, step = 100 (1.301 sec)

INFO:tensorflow:global_step/sec: 99.9878

INFO:tensorflow:global_step/sec: 99.9878

INFO:tensorflow:loss = 45.19542, step = 200 (1.000 sec)

INFO:tensorflow:loss = 45.19542, step = 200 (1.000 sec)

INFO:tensorflow:global_step/sec: 99.859

INFO:tensorflow:global_step/sec: 99.859

INFO:tensorflow:loss = 45.45166, step = 300 (1.001 sec)

INFO:tensorflow:loss = 45.45166, step = 300 (1.001 sec)

INFO:tensorflow:global_step/sec: 100.861

INFO:tensorflow:global_step/sec: 100.861

INFO:tensorflow:loss = 43.172836, step = 400 (0.991 sec)

INFO:tensorflow:loss = 43.172836, step = 400 (0.991 sec)

INFO:tensorflow:global_step/sec: 100.344

INFO:tensorflow:global_step/sec: 100.344

INFO:tensorflow:loss = 47.976437, step = 500 (0.997 sec)

INFO:tensorflow:loss = 47.976437, step = 500 (0.997 sec)

INFO:tensorflow:global_step/sec: 100.028

INFO:tensorflow:global_step/sec: 100.028

INFO:tensorflow:loss = 36.716545, step = 600 (0.999 sec)

INFO:tensorflow:loss = 36.716545, step = 600 (0.999 sec)

INFO:tensorflow:global_step/sec: 101.002

INFO:tensorflow:global_step/sec: 101.002

INFO:tensorflow:loss = 49.73072, step = 700 (0.990 sec)

INFO:tensorflow:loss = 49.73072, step = 700 (0.990 sec)

INFO:tensorflow:global_step/sec: 100.215

INFO:tensorflow:global_step/sec: 100.215

INFO:tensorflow:loss = 51.18441, step = 800 (0.998 sec)

INFO:tensorflow:loss = 51.18441, step = 800 (0.998 sec)

INFO:tensorflow:global_step/sec: 100.284

INFO:tensorflow:global_step/sec: 100.284

INFO:tensorflow:loss = 43.9189, step = 900 (0.997 sec)

INFO:tensorflow:loss = 43.9189, step = 900 (0.997 sec)

INFO:tensorflow:global_step/sec: 100.351

INFO:tensorflow:global_step/sec: 100.351

INFO:tensorflow:loss = 42.52917, step = 1000 (0.997 sec)

INFO:tensorflow:loss = 42.52917, step = 1000 (0.997 sec)

INFO:tensorflow:global_step/sec: 112.56

INFO:tensorflow:global_step/sec: 112.56

INFO:tensorflow:loss = 44.90046, step = 1100 (0.888 sec)

INFO:tensorflow:loss = 44.90046, step = 1100 (0.888 sec)

INFO:tensorflow:global_step/sec: 119.925

INFO:tensorflow:global_step/sec: 119.925

INFO:tensorflow:loss = 43.706593, step = 1200 (0.834 sec)

INFO:tensorflow:loss = 43.706593, step = 1200 (0.834 sec)

INFO:tensorflow:global_step/sec: 120.519

INFO:tensorflow:global_step/sec: 120.519

INFO:tensorflow:loss = 44.676178, step = 1300 (0.829 sec)

INFO:tensorflow:loss = 44.676178, step = 1300 (0.829 sec)

INFO:tensorflow:global_step/sec: 119.963

INFO:tensorflow:global_step/sec: 119.963

INFO:tensorflow:loss = 43.093307, step = 1400 (0.834 sec)

INFO:tensorflow:loss = 43.093307, step = 1400 (0.834 sec)

INFO:tensorflow:global_step/sec: 119.763

INFO:tensorflow:global_step/sec: 119.763

INFO:tensorflow:loss = 42.738785, step = 1500 (0.835 sec)

INFO:tensorflow:loss = 42.738785, step = 1500 (0.835 sec)

INFO:tensorflow:global_step/sec: 121.425

INFO:tensorflow:global_step/sec: 121.425

INFO:tensorflow:loss = 40.920486, step = 1600 (0.824 sec)

INFO:tensorflow:loss = 40.920486, step = 1600 (0.824 sec)

INFO:tensorflow:global_step/sec: 119.283

INFO:tensorflow:global_step/sec: 119.283

INFO:tensorflow:loss = 41.593758, step = 1700 (0.838 sec)

INFO:tensorflow:loss = 41.593758, step = 1700 (0.838 sec)

INFO:tensorflow:global_step/sec: 120.527

INFO:tensorflow:global_step/sec: 120.527

INFO:tensorflow:loss = 52.07851, step = 1800 (0.830 sec)

INFO:tensorflow:loss = 52.07851, step = 1800 (0.830 sec)

INFO:tensorflow:global_step/sec: 121.508

INFO:tensorflow:global_step/sec: 121.508

INFO:tensorflow:loss = 47.40565, step = 1900 (0.823 sec)

INFO:tensorflow:loss = 47.40565, step = 1900 (0.823 sec)

INFO:tensorflow:global_step/sec: 120.495

INFO:tensorflow:global_step/sec: 120.495

INFO:tensorflow:loss = 37.15222, step = 2000 (0.830 sec)

INFO:tensorflow:loss = 37.15222, step = 2000 (0.830 sec)

INFO:tensorflow:global_step/sec: 121.44

INFO:tensorflow:global_step/sec: 121.44

INFO:tensorflow:loss = 40.43554, step = 2100 (0.824 sec)

INFO:tensorflow:loss = 40.43554, step = 2100 (0.824 sec)

INFO:tensorflow:global_step/sec: 121.327

INFO:tensorflow:global_step/sec: 121.327

INFO:tensorflow:loss = 34.854286, step = 2200 (0.824 sec)

INFO:tensorflow:loss = 34.854286, step = 2200 (0.824 sec)

INFO:tensorflow:global_step/sec: 121.412

INFO:tensorflow:global_step/sec: 121.412

INFO:tensorflow:loss = 39.517056, step = 2300 (0.824 sec)

INFO:tensorflow:loss = 39.517056, step = 2300 (0.824 sec)

INFO:tensorflow:global_step/sec: 121.074

INFO:tensorflow:global_step/sec: 121.074

INFO:tensorflow:loss = 42.165592, step = 2400 (0.826 sec)

INFO:tensorflow:loss = 42.165592, step = 2400 (0.826 sec)

INFO:tensorflow:global_step/sec: 120.49

INFO:tensorflow:global_step/sec: 120.49

INFO:tensorflow:loss = 41.839676, step = 2500 (0.830 sec)

INFO:tensorflow:loss = 41.839676, step = 2500 (0.830 sec)

INFO:tensorflow:global_step/sec: 120.712

INFO:tensorflow:global_step/sec: 120.712

INFO:tensorflow:loss = 39.65165, step = 2600 (0.829 sec)

INFO:tensorflow:loss = 39.65165, step = 2600 (0.829 sec)

INFO:tensorflow:global_step/sec: 119.787

INFO:tensorflow:global_step/sec: 119.787

INFO:tensorflow:loss = 42.94733, step = 2700 (0.835 sec)

INFO:tensorflow:loss = 42.94733, step = 2700 (0.835 sec)

INFO:tensorflow:global_step/sec: 121.19

INFO:tensorflow:global_step/sec: 121.19

INFO:tensorflow:loss = 41.764587, step = 2800 (0.825 sec)

INFO:tensorflow:loss = 41.764587, step = 2800 (0.825 sec)

INFO:tensorflow:global_step/sec: 120.891

INFO:tensorflow:global_step/sec: 120.891

INFO:tensorflow:loss = 51.07626, step = 2900 (0.827 sec)

INFO:tensorflow:loss = 51.07626, step = 2900 (0.827 sec)

INFO:tensorflow:global_step/sec: 120.676

INFO:tensorflow:global_step/sec: 120.676

INFO:tensorflow:loss = 44.027252, step = 3000 (0.829 sec)

INFO:tensorflow:loss = 44.027252, step = 3000 (0.829 sec)

INFO:tensorflow:global_step/sec: 120.657

INFO:tensorflow:global_step/sec: 120.657

INFO:tensorflow:loss = 39.74543, step = 3100 (0.829 sec)

INFO:tensorflow:loss = 39.74543, step = 3100 (0.829 sec)

INFO:tensorflow:global_step/sec: 119.515

INFO:tensorflow:global_step/sec: 119.515

INFO:tensorflow:loss = 37.307327, step = 3200 (0.837 sec)

INFO:tensorflow:loss = 37.307327, step = 3200 (0.837 sec)

INFO:tensorflow:global_step/sec: 119.363

INFO:tensorflow:global_step/sec: 119.363

INFO:tensorflow:loss = 38.945374, step = 3300 (0.838 sec)

INFO:tensorflow:loss = 38.945374, step = 3300 (0.838 sec)

INFO:tensorflow:global_step/sec: 120.96

INFO:tensorflow:global_step/sec: 120.96

INFO:tensorflow:loss = 35.931507, step = 3400 (0.827 sec)

INFO:tensorflow:loss = 35.931507, step = 3400 (0.827 sec)

INFO:tensorflow:global_step/sec: 119.252

INFO:tensorflow:global_step/sec: 119.252

INFO:tensorflow:loss = 40.045303, step = 3500 (0.838 sec)

INFO:tensorflow:loss = 40.045303, step = 3500 (0.838 sec)

INFO:tensorflow:global_step/sec: 121.723

INFO:tensorflow:global_step/sec: 121.723

INFO:tensorflow:loss = 38.345215, step = 3600 (0.822 sec)

INFO:tensorflow:loss = 38.345215, step = 3600 (0.822 sec)

INFO:tensorflow:global_step/sec: 122.203

INFO:tensorflow:global_step/sec: 122.203

INFO:tensorflow:loss = 47.337906, step = 3700 (0.818 sec)

INFO:tensorflow:loss = 47.337906, step = 3700 (0.818 sec)

INFO:tensorflow:global_step/sec: 120.313

INFO:tensorflow:global_step/sec: 120.313

INFO:tensorflow:loss = 51.29358, step = 3800 (0.831 sec)

INFO:tensorflow:loss = 51.29358, step = 3800 (0.831 sec)

INFO:tensorflow:global_step/sec: 120.656

INFO:tensorflow:global_step/sec: 120.656

INFO:tensorflow:loss = 43.02392, step = 3900 (0.829 sec)

INFO:tensorflow:loss = 43.02392, step = 3900 (0.829 sec)

INFO:tensorflow:global_step/sec: 121.049

INFO:tensorflow:global_step/sec: 121.049

INFO:tensorflow:loss = 34.73887, step = 4000 (0.826 sec)

INFO:tensorflow:loss = 34.73887, step = 4000 (0.826 sec)

INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 4071...

INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 4071...

INFO:tensorflow:Saving checkpoints for 4071 into /tmp/tmputnc4riv/model.ckpt.

INFO:tensorflow:Saving checkpoints for 4071 into /tmp/tmputnc4riv/model.ckpt.

INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 4071...

INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 4071...

INFO:tensorflow:Loss for final step: 38.014317.

INFO:tensorflow:Loss for final step: 38.014317.

Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_3:0\022\tworkclass"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_3:0\022\tworkclass"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_5:0\022\teducation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_5:0\022\teducation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_7:0\022\016marital-status"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_7:0\022\016marital-status"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_9:0\022\noccupation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_9:0\022\noccupation"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_11:0\022\014relationship"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_11:0\022\014relationship"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_13:0\022\004race"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_13:0\022\004race"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_15:0\022\003sex"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_15:0\022\003sex"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_17:0\022\016native-country"


Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\014\n\nConst_17:0\022\016native-country"


INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:tensorflow:Calling model_fn.

INFO:tensorflow:Calling model_fn.

INFO:tensorflow:Done calling model_fn.

INFO:tensorflow:Done calling model_fn.

INFO:tensorflow:Signatures INCLUDED in export for Classify: ['serving_default', 'classification']

INFO:tensorflow:Signatures INCLUDED in export for Classify: ['serving_default', 'classification']

INFO:tensorflow:Signatures INCLUDED in export for Regress: ['regression']

INFO:tensorflow:Signatures INCLUDED in export for Regress: ['regression']

INFO:tensorflow:Signatures INCLUDED in export for Predict: ['predict']

INFO:tensorflow:Signatures INCLUDED in export for Predict: ['predict']

INFO:tensorflow:Signatures INCLUDED in export for Train: None

INFO:tensorflow:Signatures INCLUDED in export for Train: None

INFO:tensorflow:Signatures INCLUDED in export for Eval: None

INFO:tensorflow:Signatures INCLUDED in export for Eval: None

INFO:tensorflow:Restoring parameters from /tmp/tmputnc4riv/model.ckpt-4071

INFO:tensorflow:Restoring parameters from /tmp/tmputnc4riv/model.ckpt-4071

INFO:tensorflow:Assets added to graph.

INFO:tensorflow:Assets added to graph.

INFO:tensorflow:Assets written to: /tmp/exported_model_dir/temp-1597742714/assets

INFO:tensorflow:Assets written to: /tmp/exported_model_dir/temp-1597742714/assets

INFO:tensorflow:SavedModel written to: /tmp/exported_model_dir/temp-1597742714/saved_model.pb

INFO:tensorflow:SavedModel written to: /tmp/exported_model_dir/temp-1597742714/saved_model.pb

INFO:tensorflow:Calling model_fn.

INFO:tensorflow:Calling model_fn.

INFO:tensorflow:Done calling model_fn.

INFO:tensorflow:Done calling model_fn.

INFO:tensorflow:Starting evaluation at 2020-08-18T09:25:17Z

INFO:tensorflow:Starting evaluation at 2020-08-18T09:25:17Z

INFO:tensorflow:Graph was finalized.

INFO:tensorflow:Graph was finalized.

INFO:tensorflow:Restoring parameters from /tmp/tmputnc4riv/model.ckpt-4071

INFO:tensorflow:Restoring parameters from /tmp/tmputnc4riv/model.ckpt-4071

INFO:tensorflow:Running local_init_op.

INFO:tensorflow:Running local_init_op.

INFO:tensorflow:Done running local_init_op.

INFO:tensorflow:Done running local_init_op.

INFO:tensorflow:Evaluation [1628/16281]

INFO:tensorflow:Evaluation [1628/16281]

INFO:tensorflow:Evaluation [3256/16281]

INFO:tensorflow:Evaluation [3256/16281]

INFO:tensorflow:Evaluation [4884/16281]

INFO:tensorflow:Evaluation [4884/16281]

INFO:tensorflow:Evaluation [6512/16281]

INFO:tensorflow:Evaluation [6512/16281]

INFO:tensorflow:Evaluation [8140/16281]

INFO:tensorflow:Evaluation [8140/16281]

INFO:tensorflow:Evaluation [9768/16281]

INFO:tensorflow:Evaluation [9768/16281]

INFO:tensorflow:Evaluation [11396/16281]

INFO:tensorflow:Evaluation [11396/16281]

INFO:tensorflow:Evaluation [13024/16281]

INFO:tensorflow:Evaluation [13024/16281]

INFO:tensorflow:Evaluation [14652/16281]

INFO:tensorflow:Evaluation [14652/16281]

INFO:tensorflow:Evaluation [16280/16281]

INFO:tensorflow:Evaluation [16280/16281]

INFO:tensorflow:Evaluation [16281/16281]

INFO:tensorflow:Evaluation [16281/16281]

INFO:tensorflow:Inference Time : 129.68261s

INFO:tensorflow:Inference Time : 129.68261s

INFO:tensorflow:Finished evaluation at 2020-08-18-09:27:26

INFO:tensorflow:Finished evaluation at 2020-08-18-09:27:26

INFO:tensorflow:Saving dict for global step 4071: accuracy = 0.85037774, accuracy_baseline = 0.76377374, auc = 0.901911, auc_precision_recall = 0.96723056, average_loss = 0.3240134, global_step = 4071, label/mean = 0.76377374, loss = 0.3240134, precision = 0.8783774, prediction/mean = 0.7628007, recall = 0.93333334

INFO:tensorflow:Saving dict for global step 4071: accuracy = 0.85037774, accuracy_baseline = 0.76377374, auc = 0.901911, auc_precision_recall = 0.96723056, average_loss = 0.3240134, global_step = 4071, label/mean = 0.76377374, loss = 0.3240134, precision = 0.8783774, prediction/mean = 0.7628007, recall = 0.93333334

INFO:tensorflow:Saving 'checkpoint_path' summary for global step 4071: /tmp/tmputnc4riv/model.ckpt-4071

INFO:tensorflow:Saving 'checkpoint_path' summary for global step 4071: /tmp/tmputnc4riv/model.ckpt-4071

{'accuracy': 0.85037774,
 'accuracy_baseline': 0.76377374,
 'auc': 0.901911,
 'auc_precision_recall': 0.96723056,
 'average_loss': 0.3240134,
 'global_step': 4071,
 'label/mean': 0.76377374,
 'loss': 0.3240134,
 'precision': 0.8783774,
 'prediction/mean': 0.7628007,
 'recall': 0.93333334}

우리가 한 일

이 예에서는 tf.Transform 을 사용하여 인구 조사 데이터의 데이터 세트를 전처리하고 정리 및 변환 된 데이터로 모델을 훈련 시켰습니다. 또한 학습 된 모델을 프로덕션 환경에 배포하여 추론을 수행 할 때 사용할 수있는 입력 함수를 만들었습니다. 훈련과 추론 모두에 동일한 코드를 사용함으로써 데이터 왜곡 문제를 피할 수 있습니다. 그 과정에서 데이터를 정리하는 데 필요한 변환을 수행하기 위해 Apache Beam 변환을 생성하고 TensorFlow FeatureColumns 데이터를 래핑하는 방법을 배웠습니다. 이것은 TensorFlow Transform이 할 수있는 일의 작은 부분 일뿐입니다! tf.Transform 대해 tf.Transform 알아보고 어떤 tf.Transform 있는지 알아 보시기 바랍니다.