forked from tensorflow/model-analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Separate the PredictionsExtractor into two extractors.
PiperOrigin-RevId: 462483630
- Loading branch information
1 parent
eaed36b
commit 47a6bda
Showing
9 changed files
with
249 additions
and
151 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
78 changes: 78 additions & 0 deletions
78
tensorflow_model_analysis/extractors/materialized_predictions_extractor.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
# Copyright 2020 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
"""Batched materialized predictions extractor.""" | ||
|
||
import copy | ||
|
||
import apache_beam as beam | ||
from tensorflow_model_analysis import constants | ||
from tensorflow_model_analysis import types | ||
from tensorflow_model_analysis.extractors import extractor | ||
from tensorflow_model_analysis.proto import config_pb2 | ||
from tensorflow_model_analysis.utils import model_util | ||
|
||
_MATERIALIZED_PREDICTIONS_EXTRACTOR_STAGE_NAME = 'ExtractMaterializedPredictions' | ||
|
||
|
||
def MaterializedPredictionsExtractor( | ||
eval_config: config_pb2.EvalConfig) -> extractor.Extractor: | ||
"""Creates an extractor for rekeying preexisting predictions. | ||
The extractor's PTransform uses the config's ModelSpec.prediction_key(s) | ||
to lookup the associated prediction values stored as features under the | ||
tfma.FEATURES_KEY in extracts. The resulting values are then added to the | ||
extracts under the key tfma.PREDICTIONS_KEY. | ||
Args: | ||
eval_config: Eval config. | ||
Returns: | ||
Extractor for rekeying preexisting predictions. | ||
""" | ||
# pylint: disable=no-value-for-parameter | ||
return extractor.Extractor( | ||
stage_name=_MATERIALIZED_PREDICTIONS_EXTRACTOR_STAGE_NAME, | ||
ptransform=_ExtractMaterializedPredictions(eval_config=eval_config)) | ||
|
||
|
||
@beam.ptransform_fn | ||
@beam.typehints.with_input_types(types.Extracts) | ||
@beam.typehints.with_output_types(types.Extracts) | ||
def _ExtractMaterializedPredictions( # pylint: disable=invalid-name | ||
extracts: beam.pvalue.PCollection, | ||
eval_config: config_pb2.EvalConfig) -> beam.pvalue.PCollection: | ||
"""A PTransform that populates the predictions key in the extracts. | ||
Args: | ||
extracts: PCollection of extracts containing model inputs keyed by | ||
tfma.FEATURES_KEY (if model inputs are named) or tfma.INPUTS_KEY (if model | ||
takes raw tf.Examples as input). | ||
eval_config: Eval config. | ||
Returns: | ||
PCollection of Extracts updated with the predictions. | ||
""" | ||
|
||
def rekey_predictions( # pylint: disable=invalid-name | ||
batched_extracts: types.Extracts) -> types.Extracts: | ||
"""Extract predictions from extracts containing features.""" | ||
result = copy.copy(batched_extracts) | ||
predictions = model_util.get_feature_values_for_model_spec_field( | ||
list(eval_config.model_specs), 'prediction_key', 'prediction_keys', | ||
result) | ||
if predictions is not None: | ||
result[constants.PREDICTIONS_KEY] = predictions | ||
return result | ||
|
||
return extracts | 'RekeyPredictions' >> beam.Map(rekey_predictions) |
129 changes: 129 additions & 0 deletions
129
tensorflow_model_analysis/extractors/materialized_predictions_extractor_test.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
# Copyright 2020 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
"""Test for batched materialized predictions extractor.""" | ||
|
||
import apache_beam as beam | ||
from apache_beam.testing import util | ||
import numpy as np | ||
import tensorflow as tf | ||
from tensorflow_model_analysis import constants | ||
from tensorflow_model_analysis.api import model_eval_lib | ||
from tensorflow_model_analysis.eval_saved_model import testutil | ||
from tensorflow_model_analysis.extractors import features_extractor | ||
from tensorflow_model_analysis.extractors import materialized_predictions_extractor | ||
from tensorflow_model_analysis.proto import config_pb2 | ||
from tfx_bsl.tfxio import tensor_adapter | ||
from tfx_bsl.tfxio import test_util | ||
|
||
from google.protobuf import text_format | ||
from tensorflow_metadata.proto.v0 import schema_pb2 | ||
|
||
|
||
class MaterializedPredictionsExtractorTest( | ||
testutil.TensorflowModelAnalysisTest): | ||
|
||
def test_rekey_predictions_in_features(self): | ||
model_spec1 = config_pb2.ModelSpec( | ||
name='model1', prediction_key='prediction') | ||
model_spec2 = config_pb2.ModelSpec( | ||
name='model2', | ||
prediction_keys={ | ||
'output1': 'prediction1', | ||
'output2': 'prediction2' | ||
}) | ||
eval_config = config_pb2.EvalConfig(model_specs=[model_spec1, model_spec2]) | ||
schema = text_format.Parse( | ||
""" | ||
tensor_representation_group { | ||
key: "" | ||
value { | ||
tensor_representation { | ||
key: "fixed_int" | ||
value { | ||
dense_tensor { | ||
column_name: "fixed_int" | ||
} | ||
} | ||
} | ||
} | ||
} | ||
feature { | ||
name: "prediction" | ||
type: FLOAT | ||
} | ||
feature { | ||
name: "prediction1" | ||
type: FLOAT | ||
} | ||
feature { | ||
name: "prediction2" | ||
type: FLOAT | ||
} | ||
feature { | ||
name: "fixed_int" | ||
type: INT | ||
} | ||
""", schema_pb2.Schema()) | ||
tfx_io = test_util.InMemoryTFExampleRecord( | ||
schema=schema, raw_record_column_name=constants.ARROW_INPUT_COLUMN) | ||
tensor_adapter_config = tensor_adapter.TensorAdapterConfig( | ||
arrow_schema=tfx_io.ArrowSchema(), | ||
tensor_representations=tfx_io.TensorRepresentations()) | ||
feature_extractor = features_extractor.FeaturesExtractor( | ||
eval_config=eval_config, | ||
tensor_representations=tensor_adapter_config.tensor_representations) | ||
prediction_extractor = materialized_predictions_extractor.MaterializedPredictionsExtractor( | ||
eval_config) | ||
|
||
examples = [ | ||
self._makeExample( | ||
prediction=1.0, prediction1=1.0, prediction2=0.0, fixed_int=1), | ||
self._makeExample( | ||
prediction=1.0, prediction1=1.0, prediction2=1.0, fixed_int=1) | ||
] | ||
|
||
with beam.Pipeline() as pipeline: | ||
# pylint: disable=no-value-for-parameter | ||
result = ( | ||
pipeline | ||
| 'Create' >> beam.Create([e.SerializeToString() for e in examples], | ||
reshuffle=False) | ||
| 'BatchExamples' >> tfx_io.BeamSource(batch_size=2) | ||
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts() | ||
| feature_extractor.stage_name >> feature_extractor.ptransform | ||
| prediction_extractor.stage_name >> prediction_extractor.ptransform) | ||
|
||
# pylint: enable=no-value-for-parameter | ||
|
||
def check_result(got): | ||
try: | ||
self.assertLen(got, 1) | ||
for model_name in ('model1', 'model2'): | ||
self.assertIn(model_name, got[0][constants.PREDICTIONS_KEY]) | ||
self.assertAllClose(got[0][constants.PREDICTIONS_KEY]['model1'], | ||
np.array([1.0, 1.0])) | ||
self.assertAllClose(got[0][constants.PREDICTIONS_KEY]['model2'], { | ||
'output1': np.array([1.0, 1.0]), | ||
'output2': np.array([0.0, 1.0]) | ||
}) | ||
|
||
except AssertionError as err: | ||
raise util.BeamAssertException(err) | ||
|
||
util.assert_that(result, check_result, label='result') | ||
|
||
|
||
if __name__ == '__main__': | ||
tf.compat.v1.enable_v2_behavior() | ||
tf.test.main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.