Data transformation helps prepare raw data into a clean and useful format for machine learning models. TF Transform makes this process easy and consistent.
Data transformation (TF Transform) in TensorFlow
import tensorflow_transform as tft def preprocessing_fn(inputs): outputs = {} outputs['scaled_feature'] = tft.scale_to_z_score(inputs['feature']) outputs['bucketized_feature'] = tft.bucketize(inputs['feature'], num_buckets=5) return outputs
The preprocessing_fn defines how to change your data.
Use tft functions to transform features, like scaling or bucketizing.
def preprocessing_fn(inputs): outputs = {} outputs['normalized_age'] = tft.scale_to_0_1(inputs['age']) return outputs
def preprocessing_fn(inputs): outputs = {} outputs['word_ids'] = tft.compute_and_apply_vocabulary(inputs['text']) return outputs
def preprocessing_fn(inputs): outputs = {} outputs['filled_income'] = tf.where(tf.math.is_nan(inputs['income']), 0.0, inputs['income']) return outputs
This program uses TF Transform to scale and bucketize a numeric feature. It runs a small pipeline that analyzes the data, applies transformations, and prints the results.
import tensorflow as tf import tensorflow_transform as tft import tensorflow_transform.beam.impl as tft_beam from tensorflow_transform.tf_metadata import dataset_metadata, schema_utils from tensorflow_metadata.proto.v0 import schema_pb2 import apache_beam as beam # Define preprocessing function def preprocessing_fn(inputs): outputs = {} outputs['scaled_feature'] = tft.scale_to_z_score(inputs['feature']) outputs['bucketized_feature'] = tft.bucketize(inputs['feature'], num_buckets=3) return outputs # Sample raw data raw_data = [ {'feature': 10.0}, {'feature': 20.0}, {'feature': 30.0}, {'feature': 40.0}, {'feature': 50.0} ] # Define schema feature_spec = {'feature': tf.io.FixedLenFeature([], tf.float32)} raw_metadata = dataset_metadata.DatasetMetadata(schema_utils.schema_from_feature_spec(feature_spec)) # Run TF Transform pipeline with beam.Pipeline() as pipeline: with tft_beam.Context(temp_dir='/tmp'): transformed_dataset, transform_fn = ( (raw_data, raw_metadata) | tft_beam.AnalyzeAndTransformDataset(preprocessing_fn) ) transformed_data, transformed_metadata = transformed_dataset # Print transformed data _ = transformed_data | 'Print' >> beam.Map(print) result = pipeline.run() result.wait_until_finish()
TF Transform runs transformations on the whole dataset to learn statistics like mean and variance.
It ensures the same transformations apply during training and when the model is used later.
You need Apache Beam to run TF Transform pipelines.
TF Transform helps prepare data by applying consistent changes like scaling and bucketizing.
It learns from the whole dataset to apply accurate transformations.
Use it to make sure your model sees data in the same way during training and serving.
Practice
Solution
Step 1: Understand TF Transform's role
TF Transform is designed to apply the same data transformations consistently during training and serving.Step 2: Compare options
Options A, B, and D describe other tasks unrelated to TF Transform's main purpose.Final Answer:
To apply consistent data transformations during both training and serving -> Option CQuick Check:
Consistent transformations = To apply consistent data transformations during both training and serving [OK]
- Confusing TF Transform with model training
- Thinking TF Transform generates data
- Assuming it visualizes data statistics
age by its mean and variance?Solution
Step 1: Identify correct TF Transform scaling function
TF Transform providestft.scale_to_z_scoreto scale features by mean and variance.Step 2: Check code correctness
def preprocessing_fn(inputs): age = tft.scale_to_z_score(inputs['age']) return {'age_scaled': age} usestft.scale_to_z_scorecorrectly; others use incorrect or arbitrary scaling.Final Answer:
def preprocessing_fn(inputs): age = tft.scale_to_z_score(inputs['age']) return {'age_scaled': age} -> Option AQuick Check:
Use tft.scale_to_z_score for mean-variance scaling [OK]
- Using simple division instead of TF Transform scaling
- Adding arbitrary constants instead of scaling
- Multiplying without normalization
{'income': 50000} if the dataset mean income is 40000 and stddev is 10000?
def preprocessing_fn(inputs):
income_scaled = tft.scale_to_z_score(inputs['income'])
return {'income_scaled': income_scaled}Solution
Step 1: Calculate z-score for income
Z-score = (value - mean) / stddev = (50000 - 40000) / 10000 = 1.0Step 2: Match output format
The function returns {'income_scaled': z-score}, so output is {'income_scaled': 1.0}Final Answer:
{'income_scaled': 1.0} -> Option DQuick Check:
Z-score calculation = 1.0 [OK]
- Forgetting to subtract mean
- Dividing by mean instead of stddev
- Mixing up positive and negative signs
def preprocessing_fn(inputs):
age_bucketized = tft.bucketize(inputs['age'], num_buckets=5)
return {'age_bucketized': age_bucketized}
What is the likely cause of the error?Solution
Step 1: Check tft.bucketize function signature
tft.bucketize requires 'boundaries' argument, not 'num_buckets'.Step 2: Identify error cause
Using 'num_buckets' causes an error because it's not a valid parameter.Final Answer:
The function tft.bucketize requires 'boundaries' instead of 'num_buckets' -> Option BQuick Check:
tft.bucketize needs boundaries, not num_buckets [OK]
- Passing num_buckets instead of boundaries
- Forgetting to import tensorflow_transform
- Returning wrong data type
height and categorical feature color. You want to scale height and one-hot encode color. Which preprocessing function correctly applies these transformations?Solution
Step 1: Scale numeric feature 'height'
Usetft.scale_to_z_scoreto scale 'height' correctly.Step 2: One-hot encode categorical 'color'
First, map 'color' to integer indices usingtft.compute_and_apply_vocabulary, then applytf.one_hotwith correct depth.Step 3: Verify options
def preprocessing_fn(inputs): height_scaled = tft.scale_to_z_score(inputs['height']) color_vocab = tft.compute_and_apply_vocabulary(inputs['color']) color_one_hot = tf.one_hot(color_vocab, depth=3) return {'height_scaled': height_scaled, 'color_one_hot': color_one_hot} correctly chains vocabulary computation and one-hot encoding; others miss steps or misuse functions.Final Answer:
def preprocessing_fn(inputs): height_scaled = tft.scale_to_z_score(inputs['height']) color_vocab = tft.compute_and_apply_vocabulary(inputs['color']) color_one_hot = tf.one_hot(color_vocab, depth=3) return {'height_scaled': height_scaled, 'color_one_hot': color_one_hot} -> Option AQuick Check:
Vocabulary then one-hot encoding = def preprocessing_fn(inputs): height_scaled = tft.scale_to_z_score(inputs['height']) color_vocab = tft.compute_and_apply_vocabulary(inputs['color']) color_one_hot = tf.one_hot(color_vocab, depth=3) return {'height_scaled': height_scaled, 'color_one_hot': color_one_hot} [OK]
- Applying one-hot directly on strings
- Skipping vocabulary computation
- Scaling numeric features incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
