code: def to_scalar(
      tensor: Optional[
          Union[types.TensorValue, tf.compat.v1.SparseTensorValue]
      ],
      tensor_name: str = "unknown",
  ) -> Optional[Union[float, int, str]]:
      """Returns value as a scalar or raises ValueError."""
      if tensor is None:
          return None
      if util.is_sparse_or_ragged_tensor_value(tensor):
          tensor = tensor.values
      if tensor.size != 1:
          raise ValueError(
              f'"{tensor_name}" should have exactly 1 value, but found '
              f"{tensor.size} instead: values={tensor}"
          )
      return tensor.item()
  
imports: import inspect
  import math
  from typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Tuple, Union
  import numpy
  import tensorflow
  from tensorflow_model_analysis import constants
  from tensorflow_model_analysis.api import types
  from tensorflow_model_analysis.metrics import metric_types
  from tensorflow_model_analysis.proto import config_pb2
  from tensorflow_model_analysis.utils import util
  from tensorflow_metadata.proto.v0 import schema_pb2
label_desc: Use image node_id 11 for calling a global function with example usage: to_scalar(tensor, tensor_name) and returns: tensor, None