TFMA¶
tensorflow_model_analysis
¶
Init module for TensorFlow Model Analysis.
Attributes¶
AddMetricsCallbackType
module-attribute
¶
AddMetricsCallbackType = Callable[
[
TensorTypeMaybeDict,
TensorTypeMaybeDict,
TensorTypeMaybeDict,
],
Dict[str, Tuple[TensorType, TensorType]],
]
FeaturesPredictionsLabels
module-attribute
¶
FeaturesPredictionsLabels = NamedTuple(
"FeaturesPredictionsLabels",
[
("input_ref", int),
("features", DictOfFetchedTensorValues),
("predictions", DictOfFetchedTensorValues),
("labels", DictOfFetchedTensorValues),
],
)
MaterializedColumn
module-attribute
¶
MaterializedColumn = NamedTuple(
"MaterializedColumn",
[
("name", str),
(
"value",
Union[
List[bytes],
List[int],
List[float],
bytes,
int,
float,
],
),
],
)
MaybeMultipleEvalSharedModels
module-attribute
¶
MaybeMultipleEvalSharedModels = Union[
EvalSharedModel,
List[EvalSharedModel],
Dict[str, EvalSharedModel],
]
TensorValue
module-attribute
¶
TensorValue = Union[
ndarray,
SparseTensorValue,
RaggedTensorValue,
SparseTensorValue,
]
Classes¶
EvalResult
¶
Bases: NamedTuple('EvalResult', [('slicing_metrics', List[SlicedMetrics]), ('plots', List[SlicedPlots]), ('attributions', List[SlicedAttributions]), ('config', EvalConfig), ('data_location', str), ('file_format', str), ('model_location', str)])
The result of a single model analysis run.
ATTRIBUTE | DESCRIPTION |
---|---|
slicing_metrics |
a list of
|
plots |
List of slice-plot pairs.
|
attributions |
List of SlicedAttributions containing attribution values for each slice.
|
config |
The config containing slicing and metrics specification.
|
data_location |
Optional location for data used with config.
|
file_format |
Optional format for data used with config.
|
model_location |
Optional location(s) for model(s) used with config.
|
Functions¶
get_attributions_for_all_slices
¶
get_attributions_for_all_slices(
metric_name: str = "",
output_name: str = "",
class_id: Optional[int] = None,
k: Optional[int] = None,
top_k: Optional[int] = None,
) -> Dict[str, AttributionsByFeatureKey]
Get attribution feature keys and values for every slice.
PARAMETER | DESCRIPTION |
---|---|
metric_name
|
Name of metric to get attributions for. Optional if only one metric used.
TYPE:
|
output_name
|
The name of the output (optional, only used for multi-output models).
TYPE:
|
class_id
|
Used with multi-class metrics to identify a specific class ID. |
k
|
Used with multi-class metrics to identify the kth predicted value. |
top_k
|
Used with multi-class and ranking metrics to identify top-k predicted values. |
RETURNS | DESCRIPTION |
---|---|
Dict[str, AttributionsByFeatureKey]
|
Dictionary mapping slices to attribution feature keys and values. |
Source code in tensorflow_model_analysis/view/view_types.py
get_attributions_for_slice
¶
get_attributions_for_slice(
slice_name: SliceKeyType = (),
metric_name: str = "",
output_name: str = "",
class_id: Optional[int] = None,
k: Optional[int] = None,
top_k: Optional[int] = None,
) -> Union[AttributionsByFeatureKey, None]
Get attribution features names and values for a slice.
PARAMETER | DESCRIPTION |
---|---|
slice_name
|
A tuple of the form (column, value), indicating which slice to get attributions from. Optional; if excluded, use overall slice.
TYPE:
|
metric_name
|
Name of metric to get attributions for. Optional if only one metric used.
TYPE:
|
output_name
|
The name of the output. Optional, only used for multi-output models.
TYPE:
|
class_id
|
Used with multi-class models to identify a specific class ID. |
k
|
Used with multi-class models to identify the kth predicted value. |
top_k
|
Used with multi-class models to identify top-k attribution values. |
RETURNS | DESCRIPTION |
---|---|
Union[AttributionsByFeatureKey, None]
|
Dictionary containing feature keys and values for the specified slice. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If metric_name is required. |
Source code in tensorflow_model_analysis/view/view_types.py
get_metric_names
¶
Get names of metrics.
RETURNS | DESCRIPTION |
---|---|
Sequence[str]
|
List of metric names. |
Source code in tensorflow_model_analysis/view/view_types.py
get_metrics_for_all_slices
¶
get_metrics_for_all_slices(
output_name: str = "",
class_id: Optional[int] = None,
k: Optional[int] = None,
top_k: Optional[int] = None,
) -> Dict[str, MetricsByTextKey]
Get metric names and values for every slice.
PARAMETER | DESCRIPTION |
---|---|
output_name
|
The name of the output (optional, only used for multi-output models).
TYPE:
|
class_id
|
Used with multi-class metrics to identify a specific class ID. |
k
|
Used with multi-class metrics to identify the kth predicted value. |
top_k
|
Used with multi-class and ranking metrics to identify top-k predicted values. |
RETURNS | DESCRIPTION |
---|---|
Dict[str, MetricsByTextKey]
|
Dictionary mapping slices to metric names and values. |
Source code in tensorflow_model_analysis/view/view_types.py
get_metrics_for_slice
¶
get_metrics_for_slice(
slice_name: SliceKeyType = (),
output_name: str = "",
class_id: Optional[int] = None,
k: Optional[int] = None,
top_k: Optional[int] = None,
) -> Union[MetricsByTextKey, None]
Get metric names and values for a slice.
PARAMETER | DESCRIPTION |
---|---|
slice_name
|
A tuple of the form (column, value), indicating which slice to get metrics from. Optional; if excluded, return overall metrics.
TYPE:
|
output_name
|
The name of the output. Optional, only used for multi-output models.
TYPE:
|
class_id
|
Used with multi-class metrics to identify a specific class ID. |
k
|
Used with multi-class metrics to identify the kth predicted value. |
top_k
|
Used with multi-class and ranking metrics to identify top-k predicted values. |
RETURNS | DESCRIPTION |
---|---|
Union[MetricsByTextKey, None]
|
Dictionary containing metric names and values for the specified slice. |
Source code in tensorflow_model_analysis/view/view_types.py
EvalSharedModel
¶
Bases: NamedTuple('EvalSharedModel', [('model_path', str), ('add_metrics_callbacks', List[Callable]), ('include_default_metrics', bool), ('example_weight_key', Union[str, Dict[str, str]]), ('additional_fetches', List[str]), ('model_loader', ModelLoader), ('model_name', str), ('model_type', str), ('rubber_stamp', bool), ('is_baseline', bool), ('resource_hints', Optional[Dict[str, Any]]), ('backend_config', Optional[Any])])
Shared model used during extraction and evaluation.
ATTRIBUTE | DESCRIPTION |
---|---|
model_path |
Path to EvalSavedModel (containing the saved_model.pb file).
|
add_metrics_callbacks |
Optional list of callbacks for adding additional metrics to the graph. The names of the metrics added by the callbacks should not conflict with existing metrics. See below for more details about what each callback should do. The callbacks are only used during evaluation.
|
include_default_metrics |
True to include the default metrics that are part of the saved model graph during evaluation.
|
example_weight_key |
Example weight key (single-output model) or dict of example weight keys (multi-output model) keyed by output_name.
|
additional_fetches |
Prefixes of additional tensors stored in signature_def.inputs that should be fetched at prediction time. The "features" and "labels" tensors are handled automatically and should not be included in this list.
|
model_loader |
Model loader.
|
model_name |
Model name (should align with ModelSpecs.name).
|
model_type |
Model type (tfma.TF_KERAS, tfma.TF_LITE, tfma.TF_ESTIMATOR, ..).
|
rubber_stamp |
True if this model is being rubber stamped. When a model is rubber stamped diff thresholds will be ignored if an associated baseline model is not passed.
|
is_baseline |
The model is the baseline for comparison or not.
|
resource_hints |
The beam resource hints to apply to the PTransform which runs inference for this model.
|
backend_config |
The backend config for running model inference.
|
More details on add_metrics_callbacks:
Each add_metrics_callback should have the following prototype: def add_metrics_callback(features_dict, predictions_dict, labels_dict):
Note that features_dict, predictions_dict and labels_dict are not necessarily dictionaries - they might also be Tensors, depending on what the model's eval_input_receiver_fn returns.
It should create and return a metric_ops dictionary, such that metric_ops['metric_name'] = (value_op, update_op), just as in the Trainer.
Short example:
def add_metrics_callback(features_dict, predictions_dict, labels): metrics_ops = {} metric_ops['mean_label'] = tf.metrics.mean(labels) metric_ops['mean_probability'] = tf.metrics.mean(tf.slice( predictions_dict['probabilities'], [0, 1], [2, 1])) return metric_ops
ModelLoader
¶
Model loader is responsible for loading shared model types.
ATTRIBUTE | DESCRIPTION |
---|---|
construct_fn |
A callable which creates the model instance. The callable should take no args as input (typically a closure is used to capture necessary parameters).
|
tags |
Optional model tags (e.g. 'serve' for serving or 'eval' for EvalSavedModel).
|
Source code in tensorflow_model_analysis/api/types.py
Attributes¶
Functions¶
load
¶
Returns loaded model.
PARAMETER | DESCRIPTION |
---|---|
model_load_time_callback
|
Optional callback to track load time. |
Source code in tensorflow_model_analysis/api/types.py
RaggedTensorValue
¶
Bases: NamedTuple('RaggedTensorValue', [('values', ndarray), ('nested_row_splits', List[ndarray])])
RaggedTensorValue encapsulates a batch of ragged tensor values.
ATTRIBUTE | DESCRIPTION |
---|---|
values |
A np.ndarray of values.
|
nested_row_splits |
A list of np.ndarray values representing the row splits (one per dimension including the batch dimension).
|
SparseTensorValue
¶
Bases: NamedTuple('SparseTensorValue', [('values', ndarray), ('indices', ndarray), ('dense_shape', ndarray)])
SparseTensorValue encapsulates a batch of sparse tensor values.
ATTRIBUTE | DESCRIPTION |
---|---|
values |
A np.ndarray of values.
|
indices |
A np.ndarray of indices.
|
dense_shape |
A np.ndarray representing the dense shape.
|
VarLenTensorValue
¶
Bases: NamedTuple('VarLenTensorValue', [('values', ndarray), ('indices', ndarray), ('dense_shape', ndarray)])
VarLenTensorValue encapsulates a batch of varlen dense tensor values.
ATTRIBUTE | DESCRIPTION |
---|---|
values |
A np.ndarray of values.
|
indices |
A np.ndarray of indices.
|
dense_shape |
A np.ndarray representing the dense shape of the entire tensor. Note that each row (i.e. set of values sharing the same value for the first / batch dimension) is considered to have its own shape based on the presence of values.
|
Classes¶
DenseRowIterator
¶
An Iterator over rows of a VarLenTensorValue as dense np.arrays.
Because the VarLenTensorValue was created from a set of variable length (dense) arrays, we can invert this process to turn a VarLenTensorValue back into the original dense arrays.
Source code in tensorflow_model_analysis/api/types.py
Functions¶
dense_rows
¶
from_dense_rows
classmethod
¶
from_dense_rows(
dense_rows: Iterable[ndarray],
) -> VarLenTensorValue
Converts a collection of variable length dense arrays into a tensor.
PARAMETER | DESCRIPTION |
---|---|
dense_rows
|
A sequence of possibly variable length 1D arrays.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
VarLenTensorValue
|
A new VarLenTensorValue containing the sparse representation of the |
VarLenTensorValue
|
vertically stacked dense rows. The dense_shape attribute on the result |
VarLenTensorValue
|
will be (num_rows, max_row_len). |
Source code in tensorflow_model_analysis/api/types.py
Functions¶
BatchedInputsToExtracts
¶
Converts Arrow RecordBatch inputs to Extracts.
Source code in tensorflow_model_analysis/api/model_eval_lib.py
ExtractAndEvaluate
¶
ExtractAndEvaluate(
extracts: PCollection,
extractors: List[Extractor],
evaluators: List[Evaluator],
) -> Evaluation
Performs Extractions and Evaluations in provided order.
Source code in tensorflow_model_analysis/api/model_eval_lib.py
ExtractEvaluateAndWriteResults
¶
ExtractEvaluateAndWriteResults(
examples: PCollection,
eval_shared_model: Optional[
MaybeMultipleEvalSharedModels
] = None,
eval_config: Optional[EvalConfig] = None,
extractors: Optional[List[Extractor]] = None,
evaluators: Optional[List[Evaluator]] = None,
writers: Optional[List[Writer]] = None,
output_path: Optional[str] = None,
display_only_data_location: Optional[str] = None,
display_only_file_format: Optional[str] = None,
slice_spec: Optional[List[SingleSliceSpec]] = None,
write_config: Optional[bool] = True,
compute_confidence_intervals: Optional[bool] = False,
min_slice_size: int = 1,
random_seed_for_testing: Optional[int] = None,
tensor_adapter_config: Optional[
TensorAdapterConfig
] = None,
schema: Optional[Schema] = None,
config_version: Optional[int] = None,
) -> Dict[str, PCollection]
PTransform for performing extraction, evaluation, and writing results.
Users who want to construct their own Beam pipelines instead of using the lightweight run_model_analysis functions should use this PTransform.
Example usage:
eval_config = tfma.EvalConfig(model_specs=[...], metrics_specs=[...],
slicing_specs=[...])
eval_shared_model = tfma.default_eval_shared_model(
eval_saved_model_path=model_location, eval_config=eval_config)
tfx_io = tf_example_record.TFExampleRecord(
file_pattern=data_location,
raw_record_column_name=tfma.ARROW_INPUT_COLUMN)
with beam.Pipeline(runner=...) as p:
_ = (p
| 'ReadData' >> tfx_io.BeamSource()
| 'ExtractEvaluateAndWriteResults' >>
tfma.ExtractEvaluateAndWriteResults(
eval_shared_model=eval_shared_model,
eval_config=eval_config,
...))
result = tfma.load_eval_result(output_path=output_path)
tfma.view.render_slicing_metrics(result)
NOTE: If running with an EvalSavedModel (i.e. the ModelSpec has signature_name
"eval"), then instead of using the tfxio.BeamSource() code use the following
beam.io.ReadFromTFRecord(data_location)
Note that the exact serialization format is an internal implementation detail and subject to change. Users should only use the TFMA functions to write and read the results.
PARAMETER | DESCRIPTION |
---|---|
examples
|
PCollection of input examples or Arrow Record batches. Examples can be any format the model accepts (e.g. string containing CSV row, TensorFlow.Example, etc). If the examples are in the form of a dict it will be assumed that input is already in the form of tfma.Extracts with examples stored under tfma.INPUT_KEY (any other keys will be passed along unchanged to downstream extractors and evaluators).
TYPE:
|
eval_shared_model
|
Optional shared model (single-model evaluation) or list of shared models (multi-model evaluation). Only required if needed by default extractors, evaluators, or writers and for display purposes of the model path.
TYPE:
|
eval_config
|
Eval config.
TYPE:
|
extractors
|
Optional list of Extractors to apply to Extracts. Typically these will be added by calling the default_extractors function. If no extractors are provided, default_extractors (non-materialized) will be used. |
evaluators
|
Optional list of Evaluators for evaluating Extracts. Typically these will be added by calling the default_evaluators function. If no evaluators are provided, default_evaluators will be used. |
writers
|
Optional list of Writers for writing Evaluation output. Typically these will be added by calling the default_writers function. If no writers are provided, default_writers will be used. |
output_path
|
Path to output results to (config file, metrics, plots, etc). |
display_only_data_location
|
Optional path indicating where the examples were read from. This is used only for display purposes - data will not actually be read from this path. |
display_only_file_format
|
Optional format of the examples. This is used only for display purposes. |
slice_spec
|
Deprecated (use EvalConfig). |
write_config
|
Deprecated (use EvalConfig). |
compute_confidence_intervals
|
Deprecated (use EvalConfig). |
min_slice_size
|
Deprecated (use EvalConfig).
TYPE:
|
random_seed_for_testing
|
Provide for deterministic tests only. |
tensor_adapter_config
|
Tensor adapter config which specifies how to obtain tensors from the Arrow RecordBatch. If None, an attempt will be made to create the tensors using default TensorRepresentations.
TYPE:
|
schema
|
A schema to use for customizing evaluators.
TYPE:
|
config_version
|
Optional config version for this evaluation. This should not be explicitly set by users. It is only intended to be used in cases where the provided eval_config was generated internally, and thus not a reliable indicator of user intent. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If EvalConfig invalid or matching Extractor not found for an Evaluator. |
RETURNS | DESCRIPTION |
---|---|
Dict[str, PCollection]
|
A dict of writer results keyed by the writer stage name. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 |
|
InputsToExtracts
¶
Converts serialized inputs (e.g. examples) to Extracts if not already.
Source code in tensorflow_model_analysis/api/model_eval_lib.py
Validate
¶
Validate(
extracts: PCollection,
alternatives: Dict[str, PTransform],
validators: List[Validator],
) -> Validation
Performs validation of alternative evaluations.
PARAMETER | DESCRIPTION |
---|---|
extracts
|
PCollection of extracts.
TYPE:
|
alternatives
|
Dict of PTransforms (Extracts -> Evaluation) whose output will be compared for validation purposes (e.g. 'baseline' vs 'candidate'). |
validators
|
List of validators for validating the output from running the alternatives. The Validation outputs produced by the validators will be merged into a single output. If there are overlapping output keys, later outputs will replace earlier outputs sharing the same key. |
RETURNS | DESCRIPTION |
---|---|
Validation
|
Validation dict. |
Source code in tensorflow_model_analysis/api/verifier_lib.py
WriteResults
¶
WriteResults(
evaluation_or_validation: Union[Evaluation, Validation],
writers: List[Writer],
) -> Dict[str, PCollection]
Writes Evaluation or Validation results using given writers.
PARAMETER | DESCRIPTION |
---|---|
evaluation_or_validation
|
Evaluation or Validation output.
TYPE:
|
writers
|
Writes to use for writing out output. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If Evaluation or Validation is empty. |
RETURNS | DESCRIPTION |
---|---|
Dict[str, PCollection]
|
A dict of writer results keyed by the writer stage name. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
analyze_raw_data
¶
analyze_raw_data(
data: DataFrame,
eval_config: Optional[EvalConfig] = None,
output_path: Optional[str] = None,
extractors: Optional[List[Extractor]] = None,
evaluators: Optional[List[Evaluator]] = None,
writers: Optional[List[Writer]] = None,
add_metric_callbacks: Optional[
List[AddMetricsCallbackType]
] = None,
) -> EvalResult
Runs TensorFlow model analysis on a pandas.DataFrame.
This function allows you to use TFMA with Pandas DataFrames. The dataframe must include a 'predicted' column for the predicted label and a 'label' column for the actual label.
In addition to a DataFrame, this function requires an eval_config, a
tfma.EvalConfig
object containing various configuration parameters (see
config.proto
for a comprehensive list)...
- the metrics to compute
- the slices to compute metrics on
- the DataFrame's column names for example labels and predictions ('label' and 'prediction' by default)
- confidence interval options
This function returns a tfma.EvalResult
, which contains TFMA's computed
metrics and can be used to generate plots with
tfma.view.render_slicing_metrics
.
Example usage:
model_specs = [
tfma.ModelSpec(
prediction_key='prediction',
label_key='label')
]
metrics_specs = [
tfma.MetricsSpec(metrics=[
tfma.MetricConfig(class_name='Accuracy'),
tfma.MetricConfig(class_name='ExampleCount')
])
]
slicing_specs = [
tfma.SlicingSpec(), # the empty slice represents overall dataset
tfma.SlicingSpec(feature_keys=['language'])
]
eval_config = tfma.EvalConfig(
model_specs=model_specs,
metrics_specs=metrics_specs,
slicing_specs=slicing_specs)
result = tfma.analyze_raw_data(df, eval_config)
tfma.view.render_slicing_metrics(result)
# Example with Fairness Indicators
from tensorflow_model_analysis.addons.fairness.post_export_metrics import
fairness_indicators
from tensorflow_model_analysis.addons.fairness.view import widget_view
add_metrics_callbacks = [
tfma.post_export_metrics.fairness_indicators(thresholds=[0.25, 0.5, 0.75])
]
result = tfma.analyze_raw_data(
data=df,
metrics_specs=metrics_specs,
slicing_specs=slicing_specs,
add_metric_callbacks=add_metrics_callbacks
)
widget_view.render_fairness_indicator(result)
PARAMETER | DESCRIPTION |
---|---|
data
|
A pandas.DataFrame, where rows correspond to examples and columns correspond to features. One column must indicate a row's predicted label, and one column must indicate a row's actual label.
TYPE:
|
eval_config
|
A
TYPE:
|
output_path
|
Path to write EvalResult to. |
extractors
|
Optional list of Extractors to apply to Extracts. Typically these will be added by calling the default_extractors function. If no extractors are provided, default_extractors (non-materialized) will be used. |
evaluators
|
Optional list of Evaluators for evaluating Extracts. Typically these will be added by calling the default_evaluators function. If no evaluators are provided, default_evaluators will be used. |
writers
|
Optional list of Writers for writing Evaluation output. Typically
these will be added by calling the default_writers function. If no writers
are provided, default_writers with |
add_metric_callbacks
|
Optional list of metric callbacks (if used).
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
EvalResult
|
A tfma.EvalResult to extract metrics or generate visualizations from. |
RAISES | DESCRIPTION |
---|---|
KeyError
|
If the prediction or label columns are not found within the DataFrame. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 |
|
default_eval_shared_model
¶
default_eval_shared_model(
eval_saved_model_path: str,
add_metrics_callbacks: Optional[
List[AddMetricsCallbackType]
] = None,
include_default_metrics: Optional[bool] = True,
example_weight_key: Optional[
Union[str, Dict[str, str]]
] = None,
additional_fetches: Optional[List[str]] = None,
blacklist_feature_fetches: Optional[List[str]] = None,
tags: Optional[List[str]] = None,
model_name: str = "",
eval_config: Optional[EvalConfig] = None,
custom_model_loader: Optional[ModelLoader] = None,
rubber_stamp: Optional[bool] = False,
resource_hints: Optional[Dict[str, Any]] = None,
backend_config: Optional[Any] = None,
) -> EvalSharedModel
Returns default EvalSharedModel.
PARAMETER | DESCRIPTION |
---|---|
eval_saved_model_path
|
Path to EvalSavedModel.
TYPE:
|
add_metrics_callbacks
|
Optional list of callbacks for adding additional metrics to the graph (see EvalSharedModel for more information on how to configure additional metrics). Metrics for example count and example weights will be added automatically. Only used if EvalSavedModel used.
TYPE:
|
include_default_metrics
|
DEPRECATED. Use eval_config.options.include_default_metrics. |
example_weight_key
|
DEPRECATED. Use eval_config.model_specs.example_weight_key or eval_config.model_specs.example_weight_keys. |
additional_fetches
|
Optional prefixes of additional tensors stored in signature_def.inputs that should be fetched at prediction time. The "features" and "labels" tensors are handled automatically and should not be included. Only used if EvalSavedModel used. |
blacklist_feature_fetches
|
Optional list of tensor names in the features dictionary which should be excluded from the fetches request. This is useful in scenarios where features are large (e.g. images) and can lead to excessive memory use if stored. Only used if EvalSavedModel used. |
tags
|
Optional model tags (e.g. 'serve' for serving or 'eval' for EvalSavedModel). |
model_name
|
Optional name of the model being created (should match ModelSpecs.name). The name should only be provided if multiple models are being evaluated.
TYPE:
|
eval_config
|
Eval config.
TYPE:
|
custom_model_loader
|
Optional custom model loader for non-TF models.
TYPE:
|
rubber_stamp
|
True when this run is a first run without a baseline model while a baseline is configured, the diff thresholds will be ignored. |
resource_hints
|
The beam resource hints to apply to the PTransform which runs inference for this model. |
backend_config
|
Optional configuration of backend running model inference with some prediction extractors. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 |
|
default_evaluators
¶
default_evaluators(
eval_shared_model: Optional[
MaybeMultipleEvalSharedModels
] = None,
eval_config: Optional[EvalConfig] = None,
schema: Optional[Schema] = None,
compute_confidence_intervals: Optional[bool] = False,
min_slice_size: int = 1,
serialize: bool = False,
random_seed_for_testing: Optional[int] = None,
config_version: Optional[int] = None,
) -> List[Evaluator]
Returns the default evaluators for use in ExtractAndEvaluate.
PARAMETER | DESCRIPTION |
---|---|
eval_shared_model
|
Optional shared model (single-model evaluation) or list of shared models (multi-model evaluation). Only required if there are metrics to be computed in-graph using the model.
TYPE:
|
eval_config
|
Eval config.
TYPE:
|
schema
|
A schema to use for customizing default evaluators.
TYPE:
|
compute_confidence_intervals
|
Deprecated (use eval_config). |
min_slice_size
|
Deprecated (use eval_config).
TYPE:
|
serialize
|
Deprecated.
TYPE:
|
random_seed_for_testing
|
Provide for deterministic tests only. |
config_version
|
Optional config version for this evaluation. This should not be explicitly set by users. It is only intended to be used in cases where the provided eval_config was generated internally, and thus not a reliable indicator of user intent. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
default_extractors
¶
default_extractors(
eval_shared_model: Optional[
MaybeMultipleEvalSharedModels
] = None,
eval_config: Optional[EvalConfig] = None,
slice_spec: Optional[List[SingleSliceSpec]] = None,
materialize: Optional[bool] = None,
tensor_adapter_config: Optional[
TensorAdapterConfig
] = None,
custom_predict_extractor: Optional[Extractor] = None,
config_version: Optional[int] = None,
) -> List[Extractor]
Returns the default extractors for use in ExtractAndEvaluate.
PARAMETER | DESCRIPTION |
---|---|
eval_shared_model
|
Shared model (single-model evaluation) or list of shared models (multi-model evaluation). Required unless the predictions are provided alongside of the features (i.e. model-agnostic evaluations).
TYPE:
|
eval_config
|
Eval config.
TYPE:
|
slice_spec
|
Deprecated (use EvalConfig). |
materialize
|
True to have extractors create materialized output. |
tensor_adapter_config
|
Tensor adapter config which specifies how to obtain tensors from the Arrow RecordBatch. If None, an attempt will be made to create the tensors using default TensorRepresentations.
TYPE:
|
custom_predict_extractor
|
Optional custom predict extractor for non-TF models. |
config_version
|
Optional config version for this evaluation. This should not be explicitly set by users. It is only intended to be used in cases where the provided eval_config was generated internally, and thus not a reliable indicator of user intent. |
RAISES | DESCRIPTION |
---|---|
NotImplementedError
|
If eval_config contains mixed serving and eval models. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 |
|
default_writers
¶
default_writers(
output_path: Optional[str],
eval_shared_model: Optional[
MaybeMultipleEvalSharedModels
] = None,
eval_config: Optional[EvalConfig] = None,
display_only_data_location: Optional[str] = None,
display_only_data_file_format: Optional[str] = None,
output_file_format: str = "tfrecord",
add_metric_callbacks: Optional[
List[AddMetricsCallbackType]
] = None,
) -> List[Writer]
Returns the default writers for use in WriteResults.
Note, sharding will be enabled by default if an output_file_format is
provided. Filenames will be
PARAMETER | DESCRIPTION |
---|---|
output_path
|
Output path. |
eval_shared_model
|
Optional shared model (single-model evaluation) or list of shared models (multi-model evaluation). Required unless the predictions are provided alongside of the features (i.e. model-agnostic evaluations).
TYPE:
|
eval_config
|
Eval config for writing out config along with results. Also used for to check for missing slices.
TYPE:
|
display_only_data_location
|
Optional path indicating where the examples were read from. This is used only for display purposes - data will not actually be read from this path. |
display_only_data_file_format
|
Optional format of the input examples. This is used only for display purposes. |
output_file_format
|
File format to use when saving files. Currently only 'tfrecord' is supported.
TYPE:
|
add_metric_callbacks
|
Optional list of metric callbacks (if used).
TYPE:
|
Source code in tensorflow_model_analysis/api/model_eval_lib.py
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 |
|
is_batched_input
¶
is_batched_input(
eval_shared_model: Optional[
MaybeMultipleEvalSharedModels
] = None,
eval_config: Optional[EvalConfig] = None,
config_version: Optional[int] = None,
) -> bool
Returns true if batched input should be used.
We will keep supporting the legacy unbatched V1 PredictExtractor as it parses the features and labels, and is the only solution currently that allows for slicing on transformed features. Eventually we should have support for transformed features via keras preprocessing layers.
PARAMETER | DESCRIPTION |
---|---|
eval_shared_model
|
Shared model (single-model evaluation) or list of shared models (multi-model evaluation). Required unless the predictions are provided alongside of the features (i.e. model-agnostic evaluations).
TYPE:
|
eval_config
|
Eval config.
TYPE:
|
config_version
|
Optional config version for this evaluation. This should not be explicitly set by users. It is only intended to be used in cases where the provided eval_config was generated internally, and thus not a reliable indicator of user intent. |
RETURNS | DESCRIPTION |
---|---|
bool
|
A boolean indicating if batched extractors should be used. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
is_legacy_estimator
¶
is_legacy_estimator(
eval_shared_model: Optional[
MaybeMultipleEvalSharedModels
] = None,
) -> bool
Returns true if there is a legacy estimator.
PARAMETER | DESCRIPTION |
---|---|
eval_shared_model
|
Shared model (single-model evaluation) or list of shared models (multi-model evaluation). Required unless the predictions are provided alongside of the features (i.e. model-agnostic evaluations).
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
bool
|
A boolean indicating if legacy predict extractor will be used. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
load_attributions
¶
load_attributions(
output_path: str, output_file_format: str = "tfrecord"
) -> Iterator[AttributionsForSlice]
Read and deserialize the AttributionsForSlice records.
Source code in tensorflow_model_analysis/api/model_eval_lib.py
load_eval_result
¶
load_eval_result(
output_path: str,
output_file_format: Optional[str] = "tfrecord",
model_name: Optional[str] = None,
) -> EvalResult
Loads EvalResult object for use with the visualization functions.
PARAMETER | DESCRIPTION |
---|---|
output_path
|
Output directory containing config, metrics, plots, etc.
TYPE:
|
output_file_format
|
Optional file extension to filter files by. |
model_name
|
Optional model name. Required if multi-model evaluation was run. |
RETURNS | DESCRIPTION |
---|---|
EvalResult
|
EvalResult object for use with the visualization functions. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
load_eval_results
¶
load_eval_results(
output_paths: Union[str, List[str]],
output_file_format: Optional[str] = "tfrecord",
mode: str = MODEL_CENTRIC_MODE,
model_name: Optional[str] = None,
) -> EvalResults
Loads results for multiple models or multiple data sets.
PARAMETER | DESCRIPTION |
---|---|
output_paths
|
A single path or list of output paths of completed tfma runs. |
output_file_format
|
Optional file extension to filter files by. |
mode
|
The mode of the evaluation. Currently, tfma.DATA_CENTRIC_MODE and tfma.MODEL_CENTRIC_MODE are supported.
TYPE:
|
model_name
|
Filters to only return results for given model. If unset all models are returned. |
RETURNS | DESCRIPTION |
---|---|
EvalResults
|
An EvalResults containing the evaluation results serialized at output_paths. |
EvalResults
|
This can be used to construct a time series view. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
load_metrics
¶
load_metrics(
output_path: str, output_file_format: str = "tfrecord"
) -> Iterator[MetricsForSlice]
Read and deserialize the MetricsForSlice records.
Source code in tensorflow_model_analysis/api/model_eval_lib.py
load_plots
¶
load_plots(
output_path: str, output_file_format: str = "tfrecord"
) -> Iterator[PlotsForSlice]
Read and deserialize the PlotsForSlice records.
Source code in tensorflow_model_analysis/api/model_eval_lib.py
load_validation_result
¶
load_validation_result(
output_path: str, output_file_format: str = ""
) -> ValidationResult
Read and deserialize the ValidationResult.
Source code in tensorflow_model_analysis/api/model_eval_lib.py
make_eval_results
¶
make_eval_results(
results: List[EvalResult], mode: str
) -> EvalResults
Run model analysis for a single model on multiple data sets.
PARAMETER | DESCRIPTION |
---|---|
results
|
A list of TFMA evaluation results.
TYPE:
|
mode
|
The mode of the evaluation. Currently, tfma.DATA_CENTRIC_MODE and tfma.MODEL_CENTRIC_MODE are supported.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
EvalResults
|
An |
EvalResults
|
can be used to construct a time series view. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
multiple_data_analysis
¶
Run model analysis for a single model on multiple data sets.
PARAMETER | DESCRIPTION |
---|---|
model_location
|
The location of the exported eval saved model.
TYPE:
|
data_locations
|
A list of data set locations. |
**kwargs
|
The args used for evaluation. See tfma.run_model_analysis() for details.
DEFAULT:
|
RETURNS | DESCRIPTION |
---|---|
EvalResults
|
A tfma.EvalResults containing all the evaluation results with the same order |
EvalResults
|
as data_locations. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
multiple_model_analysis
¶
Run model analysis for multiple models on the same data set.
PARAMETER | DESCRIPTION |
---|---|
model_locations
|
A list of paths to the export eval saved model. |
data_location
|
The location of the data files.
TYPE:
|
**kwargs
|
The args used for evaluation. See tfma.single_model_analysis() for details.
DEFAULT:
|
RETURNS | DESCRIPTION |
---|---|
EvalResults
|
A tfma.EvalResults containing all the evaluation results with the same order |
EvalResults
|
as model_locations. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
run_model_analysis
¶
run_model_analysis(
eval_shared_model: Optional[
MaybeMultipleEvalSharedModels
] = None,
eval_config: Optional[EvalConfig] = None,
data_location: str = "",
file_format: str = "tfrecords",
output_path: Optional[str] = None,
extractors: Optional[List[Extractor]] = None,
evaluators: Optional[List[Evaluator]] = None,
writers: Optional[List[Writer]] = None,
pipeline_options: Optional[Any] = None,
slice_spec: Optional[List[SingleSliceSpec]] = None,
write_config: Optional[bool] = True,
compute_confidence_intervals: Optional[bool] = False,
min_slice_size: int = 1,
random_seed_for_testing: Optional[int] = None,
schema: Optional[Schema] = None,
) -> Union[EvalResult, EvalResults]
Runs TensorFlow model analysis.
It runs a Beam pipeline to compute the slicing metrics exported in TensorFlow Eval SavedModel and returns the results.
This is a simplified API for users who want to quickly get something running locally. Users who wish to create their own Beam pipelines can use the Evaluate PTransform instead.
PARAMETER | DESCRIPTION |
---|---|
eval_shared_model
|
Optional shared model (single-model evaluation) or list of shared models (multi-model evaluation). Only required if needed by default extractors, evaluators, or writers.
TYPE:
|
eval_config
|
Eval config.
TYPE:
|
data_location
|
The location of the data files.
TYPE:
|
file_format
|
The file format of the data, can be either 'text' or 'tfrecords' for now. By default, 'tfrecords' will be used.
TYPE:
|
output_path
|
The directory to output metrics and results to. If None, we use a temporary directory. |
extractors
|
Optional list of Extractors to apply to Extracts. Typically these will be added by calling the default_extractors function. If no extractors are provided, default_extractors (non-materialized) will be used. |
evaluators
|
Optional list of Evaluators for evaluating Extracts. Typically these will be added by calling the default_evaluators function. If no evaluators are provided, default_evaluators will be used. |
writers
|
Optional list of Writers for writing Evaluation output. Typically these will be added by calling the default_writers function. If no writers are provided, default_writers will be used. |
pipeline_options
|
Optional arguments to run the Pipeline, for instance whether to run directly. |
slice_spec
|
Deprecated (use EvalConfig). |
write_config
|
Deprecated (use EvalConfig). |
compute_confidence_intervals
|
Deprecated (use EvalConfig). |
min_slice_size
|
Deprecated (use EvalConfig).
TYPE:
|
random_seed_for_testing
|
Provide for deterministic tests only. |
schema
|
Optional tf.Metadata schema of the input data.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Union[EvalResult, EvalResults]
|
An EvalResult that can be used with the TFMA visualization functions. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the file_format is unknown to us. |
Source code in tensorflow_model_analysis/api/model_eval_lib.py
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 |
|