Search code examples
pythonprotocol-buffersgoogle-cloud-vertex-ai

Cannot construct an Explanation object


Trying to construct an Explanation object for a unit test, but can't seem to get it to work. Here's what I'm trying:

from google.cloud import aiplatform

aiplatform.compat.types.explanation_v1.Explanation(
    attributions=aiplatform.compat.types.explanation_v1.Attribution(
        {
            "approximation_error": 0.010399332817679649,
            "baseline_output_value": 0.9280818700790405,
            "feature_attributions": {
                "feature_1": -0.0410824716091156,
                "feature_2": 0.01155053575833639,
            },
            "instance_output_value": 0.6717480421066284,
            "output_display_name": "true",
            "output_index": [0],
            "output_name": "scores",
        }
    )
)

which gives:

".venv/lib/python3.7/site-packages/proto/message.py", line 521, in __init__
    super().__setattr__("_pb", self._meta.pb(**params))
TypeError: Value must be iterable

I found this on github, but I'm not sure how to apply that workaround here.


Solution

  • As the error mentioned value to be passed at attributions should be iterable. See Explanation attributes documentation.

    I tried your code and placed the Attribution object in a list and the error is gone. I assigned your objects in variables just so the code is readable.

    See code and testing below:

    from google.cloud import aiplatform
    
    test = {
                "approximation_error": 0.010399332817679649,
                "baseline_output_value": 0.9280818700790405,
                "feature_attributions": {
                    "feature_1": -0.0410824716091156,
                    "feature_2": 0.01155053575833639,
                },
                "instance_output_value": 0.6717480421066284,
                "output_display_name": "true",
                "output_index": [0],
                "output_name": "scores",
            }
    
    attributions=aiplatform.compat.types.explanation_v1.Attribution(test)
    x  = aiplatform.compat.types.explanation_v1.Explanation(
        attributions=[attributions]
    )
    print(x)
    

    Output:

    attributions {
      baseline_output_value: 0.9280818700790405
      instance_output_value: 0.6717480421066284
      feature_attributions {
        struct_value {
          fields {
            key: "feature_1"
            value {
              number_value: -0.0410824716091156
            }
          }
          fields {
            key: "feature_2"
            value {
              number_value: 0.01155053575833639
            }
          }
        }
      }
      output_index: 0
      output_display_name: "true"
      approximation_error: 0.010399332817679649
      output_name: "scores"
    }