如何可视化TFX脚本运行生成的已保存统计工件?
如何可视化LocalDagRunner运行TFX流水线生成的统计工件?
你已经知道TFX流水线有两种运行方式:用Jupyter Notebook的InteractiveContext可以直接可视化统计工件,而用LocalDagRunner的Python脚本运行时无法直接展示。但两种方式生成的统计工件完全一致,你可以通过以下几种方式来可视化后者生成的统计结果:
方法1:用InteractiveContext连接已有流水线元数据
你可以在Jupyter环境中,用InteractiveContext连接到LocalDagRunner使用的同一个元数据数据库,然后获取并展示已生成的统计工件:
from tfx import v1 as tfx from tfx.orchestration.experimental.interactive.interactive_context import InteractiveContext # 连接到流水线的元数据和根目录 context = InteractiveContext( pipeline_root=_pipeline_data_folder, metadata_connection_config=tfx.orchestration.metadata.sqlite_metadata_connection_config( f'{_pipeline_data_folder}/metadata.db' ) ) # 获取最新的StatisticsGen输出工件 statistics_artifact = context.get_latest_artifact('StatisticsGen', 'statistics') # 展示可视化结果 context.show(statistics_artifact)
运行这段代码后,就能在Jupyter浏览器界面看到和交互式运行时一样的统计可视化界面。
方法2:用TFDV直接读取统计文件
统计工件以TFRecord格式存储在流水线根目录的StatisticsGen/statistics/子目录下,你可以直接用TensorFlow Data Validation(TFDV)库加载并可视化:
import tensorflow_data_validation as tfdv # 替换为你的统计文件实际路径,文件名通常是类似"Split-train.tfrecord.stats"的格式 stats_file_path = f'{_pipeline_data_folder}/StatisticsGen/statistics/Split-train.tfrecord.stats' # 加载统计数据 statistics = tfdv.load_statistics(stats_file_path) # 生成可视化 tfdv.visualize_statistics(statistics)
同样,在Jupyter环境中执行这段代码,就能直接看到统计结果的可视化界面。
补充说明
两种方法的核心都是读取LocalDagRunner生成的同一个统计工件:
- 方法1借助TFX的元数据管理体系,不需要手动查找文件路径,更适合流水线迭代场景;
- 方法2直接操作文件,适合快速定位查看特定版本的统计结果。
内容的提问来源于stack exchange,提问作者Mehran
相关产品推荐
相关产品推荐

