import tensorflow as tf
import tensorflow_model_analysis as tfma
# Assume the model is saved in 'saved_model_dir'
saved_model_dir = 'saved_model'
# Prepare test data as a list of dictionaries
# Example test data with features and labels
raw_test_data = [
{'features': {'age': 25, 'gender': 'male'}, 'label': 1},
{'features': {'age': 30, 'gender': 'female'}, 'label': 0},
{'features': {'age': 22, 'gender': 'female'}, 'label': 1},
{'features': {'age': 35, 'gender': 'male'}, 'label': 0}
]
# Convert raw data to tf.Example format
from tensorflow.train import Example, Features, Feature, BytesList, Int64List
def create_tf_example(data_point):
feature = {}
for key, value in data_point['features'].items():
if isinstance(value, int):
feature[key] = Feature(int64_list=Int64List(value=[value]))
else:
feature[key] = Feature(bytes_list=BytesList(value=[value.encode()]))
feature['label'] = Feature(int64_list=Int64List(value=[data_point['label']]))
example_proto = Example(features=Features(feature=feature))
return example_proto.SerializeToString()
serialized_examples = [create_tf_example(dp) for dp in raw_test_data]
# Write serialized examples to a TFRecord file
import tempfile
test_tfrecord = tempfile.NamedTemporaryFile(delete=False, suffix='.tfrecord').name
with tf.io.TFRecordWriter(test_tfrecord) as writer:
for ex in serialized_examples:
writer.write(ex)
# Define feature specs for parsing
feature_spec = {
'age': tf.io.FixedLenFeature([], tf.int64),
'gender': tf.io.FixedLenFeature([], tf.string),
'label': tf.io.FixedLenFeature([], tf.int64)
}
# Create EvalConfig with slicing on 'gender'
eval_config = tfma.EvalConfig(
model_specs=[tfma.ModelSpec(label_key='label')],
slicing_specs=[
tfma.SlicingSpec(), # Overall slice
tfma.SlicingSpec(feature_keys=['gender']) # Slice by gender
],
metrics_specs=[
tfma.MetricsSpec(metrics=[
tfma.MetricConfig(class_name='Accuracy'),
tfma.MetricConfig(class_name='AUC')
])
]
)
# Run TFMA evaluation
eval_result = tfma.run_model_analysis(
eval_shared_model=tfma.default_eval_shared_model(eval_saved_model_path=saved_model_dir),
data_location=test_tfrecord,
file_format='tfrecord',
eval_config=eval_config
)
# Print overall and slice metrics
for slice_key, metrics in eval_result.slicing_metrics.items():
print(f"Slice: {slice_key}")
for metric_name, metric_value in metrics.items():
print(f" {metric_name}: {metric_value}")