Registry / ai-ml / tensorflow-model-analysis

tensorflow-model-analysis

JSON →
library0.52.0pypypiunverified

TensorFlow Model Analysis (TFMA) is a library for performing deep analysis and evaluation of TensorFlow models, especially useful for understanding model performance on different data slices. It is built on Apache Beam, enabling scalable analysis. The current version is 0.48.0, and it follows a regular release cadence, often aligning with TensorFlow and TFX releases.

pip install tensorflow-model-analysis apache-beam[direct,gcp] tensorflow
INSTALL
IMPORT
SIG · TENSORFLOW-MODEL-A
T
tensorflow-model-analysis
ai-mlpythonv0.52.0
Install
Import
Disk
Pass rate
0/ 10
Env Coverage0 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.52.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
✕ build_error
✕ timeout
py 3.11
✕ build_error
✕ timeout
py 3.12
✕ build_error
1/2 runs
py 3.13
✕ build_error
1/2 runs
py 3.9
✕ build_error
✕ timeout
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

tfma
import tensorflow_model_analysis as tfma

This quickstart demonstrates how to set up a dummy TensorFlow model, create synthetic TFRecord data, define an `EvalConfig`, and run a basic model analysis with TFMA locally. It shows how to obtain overall and sliced metrics.

import tensorflow as tf import tensorflow_model_analysis as tfma import os import shutil # 1. Create a simple Keras model and save it # This model expects a 'feature_1' input and outputs 'prediction'. class SimplePredictionModel(tf.keras.Model): def __init__(self): super().__init__() self.dense = tf.keras.layers.Dense(1, activation='sigmoid') @tf.function(input_signature=[ tf.TensorSpec(shape=[None], dtype=tf.float32, name='feature_1') ]) def serving_default(self, feature_1): return {'predictions': self.dense(tf.expand_dims(feature_1, axis=-1))} model = SimplePredictionModel() # Initialize weights by calling the serving function once _ = model.serving_default(tf.constant([1.0, 2.0])) model_dir = '/tmp/tfma_quickstart_model' if os.path.exists(model_dir): shutil.rmtree(model_dir) tf.saved_model.save(model, model_dir, signatures={'serving_default': model.serving_default}) # 2. Create dummy data as TFRecord (TFMA expects tf.train.Example protos) data_path = '/tmp/tfma_quickstart_data.tfrecord' if os.path.exists(data_path): os.remove(data_path) examples_proto = [] for i in range(10): feature_val = float(i) label_val = 1.0 if i % 2 == 0 else 0.0 example = tf.train.Example(features=tf.train.Features(feature={ 'feature_1': tf.train.Feature(float_list=tf.train.FloatList(value=[feature_val])), 'label': tf.train.Feature(float_list=tf.train.FloatList(value=[label_val])), })) examples_proto.append(example.SerializeToString()) with tf.io.TFRecordWriter(data_path) as writer: for ex in examples_proto: writer.write(ex) # 3. Define EvalConfig eval_config = tfma.EvalConfig( model_specs=[tfma.ModelSpec( signature_name='serving_default', label_key='label', prediction_key='predictions' # Key from model output dict )], metrics_specs=[ tfma.MetricsSpec( metrics=[ tfma.MetricConfig(class_name='ExampleCount'), tfma.MetricConfig(class_name='Accuracy') ] ) ], slicing_specs=[ tfma.SlicingSpec(), # Overall slice tfma.SlicingSpec(feature_keys=['feature_1']) # Slice by feature_1 ] ) # 4. Run Model Analysis output_dir = '/tmp/tfma_quickstart_output' if os.path.exists(output_dir): shutil.rmtree(output_dir) print(f"Running TFMA with model: {model_dir}, data: {data_path}, output: {output_dir}") results = tfma.run_model_analysis( model_location=model_dir, data_location=data_path, eval_config=eval_config, output_path=output_dir, # TFMA uses Apache Beam for execution. For local quickstart, # default DirectRunner is used. For cloud, configure Beam options. # e.g., beam_options=os.environ.get('BEAM_OPTIONS', '').split() ) print(f"TFMA analysis complete. Results written to: {output_dir}") # To inspect results (e.g., in a Jupyter Notebook): # from tensorflow_model_analysis.notebook import visualization # visualization.display_metrics(output_dir)
Debug
Known issues
breakingTFMA has strict requirements on Python, TensorFlow, and Apache Beam versions. Upgrading one without considering the others can lead to installation or runtime errors. For instance, Python 3.8 support was dropped in 0.45.0, and `tensorflow` must be `~2.11` and `apache-beam` `~2.54` for 0.48.0.
fix
Always check the official `setup.py` or `pyproject.toml` for exact dependency ranges. Ensure your Python environment matches the `requires_python` range and that `tensorflow` and `apache-beam` versions are compatible.
affects: 0.45.0 and later for Python, 0.47.0 and later for TensorFlow/Beam
gotchaTFMA expects input data in `tf.train.Example` format, typically stored in TFRecord files. It cannot directly consume CSV, JSON, or other raw formats without prior conversion.
fix
Pre-process your data into `tf.train.Example` protos and write them to TFRecord files. Libraries like `tfx_bsl.public.tf_example_io` can assist with this.
affects: All versions
gotchaIncorrectly configuring `ModelSpec` parameters (`signature_name`, `label_key`, `prediction_key`) is a common source of errors. These must precisely match your `SavedModel`'s serving signature and the feature/output keys.
fix
Inspect your `SavedModel` using `saved_model_cli show` to confirm signature names and input/output tensor keys. Ensure `label_key` matches your TFRecord feature name and `prediction_key` matches the relevant output key from your model's prediction dictionary.
affects: All versions
gotchaApache Beam (which TFMA uses for its pipelines) requires specific extras for different runners (e.g., `[direct]` for local, `[gcp]` for Dataflow). Missing these can cause 'ModuleNotFoundError' or runtime errors when trying to use a runner.
fix
Install `apache-beam` with the necessary extras, for example: `pip install apache-beam[direct,gcp]`. Ensure your Beam pipeline options (`beam_options` in `tfma.run_model_analysis`) are correctly configured for your chosen runner.
affects: All versions
Upgrade
Version history
0.52.0latest on PyPI · released Jun 12, 2026
Audit
Dependencies
tensorflowrequiredCore machine learning framework that TFMA analyzes models from.
apache-beamrequiredTFMA is built on Apache Beam; pipelines are executed by Beam. `[direct,gcp]` extras are common for local execution and cloud deployment.
tfx-bslrequiredProvides shared libraries for TFX components, including data parsing and handling crucial for TFMA.
Agent activity
31 hits · last 30 days
node
26
OpenAI (training)
1
Resources
tensorflow-model-analysis — pip install tensorflow-model-analysis · libregistry