code: def _infer_schema(data: Any) -> Schema:
      """
      Infer an MLflow schema from a dataset.
  
      Data inputted as a numpy array or a dictionary is represented by :py:class:`TensorSpec`.
      All other inputted data types are specified by :py:class:`ColSpec`.
  
      A `TensorSpec` captures the data shape (default variable axis is 0), the data type (numpy.dtype)
      and an optional name for each individual tensor of the dataset.
      A `ColSpec` captures the data type (defined in :py:class:`DataType`) and an optional name for
      each individual column of the dataset.
  
      This method will raise an exception if the user data contains incompatible types or is not
      passed in one of the supported formats (containers).
  
      The input should be one of these:
        - pandas.DataFrame
        - pandas.Series
        - numpy.ndarray
        - dictionary of (name -> numpy.ndarray)
        - pyspark.sql.DataFrame
        - scipy.sparse.csr_matrix/csc_matrix
        - DataType
        - List[DataType]
        - Dict[str, Union[DataType, List, Dict]]
        - List[Dict[str, Union[DataType, List, Dict]]]
  
      The element types should be mappable to one of :py:class:`mlflow.models.signature.DataType` for
      dataframes and to one of numpy types for tensors.
  
      Args:
          data: Dataset to infer from.
  
      Returns:
          Schema
      """
      from scipy.sparse import csc_matrix, csr_matrix
  
      # List[Dict[str, Union[DataType, List, Dict]]]
      # e.g.
      # [{'output': 'some sentence', 'ids': ['id1', 'id2'], 'dict': {'key': 'value'}},
      #  {'output': 'some sentence', 'ids': ['id1', 'id2'], 'dict':
      # {'key': 'value', 'key2': 'value2'}}]
      # The corresponding pandas DataFrame representation should be `pd.DataFrame(data)`
      #           output         ids                                dict
      # 0  some sentence  [id1, id2]                    {'key': 'value'}
      # 1  some sentence  [id1, id2]  {'key': 'value', 'key2': 'value2'}
      # inferred schema -->
      # Schema([ColSpec(type=DataType.string, name='output'),
      #        ColSpec(type=Array(dtype=DataType.string), name='ids'),
      #        ColSpec(type=Object([Property(name='key', dtype=DataType.string),
      #                             Property(name='key2', dtype=DataType.string, required=False)]
      #               ), name='dict')])
      if isinstance(data, dict) and any(
          not isinstance(value, str) for value in data.values()
      ):
          # TODO: Add a link to docs/examples
          _logger.info(
              "MLflow 2.9.0 introduces model signature with new data types for "
              "lists and dictionaries. For input such as "
              "Dict[str, Union[scalars, List, Dict]], we infer dictionary values "
              "types as `List -> Array` and `Dict -> Object`. "
          )
  
      # To keep backward compatibility with < 2.9.0, an empty list is inferred as string.
      #   ref: https://github.com/mlflow/mlflow/pull/10125#discussion_r1372751487
      if isinstance(data, list) and data == []:
          return Schema([ColSpec(DataType.string)])
  
      if isinstance(data, list) and all(
          isinstance(value, dict) for value in data
      ):
          col_data_mapping = defaultdict(list)
          for item in data:
              for k, v in item.items():
                  col_data_mapping[k].append(v)
          requiredness = {}
          for col in col_data_mapping:
              requiredness[col] = (
                  False
                  if any(col not in item for item in data)
                  else True
              )
  
          schema = Schema(
              [
                  ColSpec(
                      _infer_colspec_type(values).dtype,
                      name=name,
                      required=requiredness[name],
                  )
                  for name, values in col_data_mapping.items()
              ]
          )
  
      elif isinstance(data, dict):
          # dictionary of (name -> numpy.ndarray)
          if all(
              isinstance(values, np.ndarray) for values in data.values()
          ):
              schema = Schema(
                  [
                      TensorSpec(
                          type=clean_tensor_type(ndarray.dtype),
                          shape=_get_tensor_shape(ndarray),
                          name=name,
                      )
                      for name, ndarray in data.items()
                  ]
              )
          # Dict[str, Union[DataType, List, Dict]]
          else:
              if any(not isinstance(key, str) for key in data):
                  raise MlflowException(
                      "The dictionary keys are not all strings."
                  )
              schema = Schema(
                  [
                      ColSpec(
                          _infer_colspec_type(value),
                          name=name,
                          required=_infer_required(value),
                      )
                      for name, value in data.items()
                  ]
              )
      # pandas.Series
      elif isinstance(data, pd.Series):
          name = getattr(data, "name", None)
          schema = Schema(
              [
                  ColSpec(
                      type=_infer_pandas_column(data),
                      name=name,
                      required=_infer_required(data),
                  )
              ]
          )
      # pandas.DataFrame
      elif isinstance(data, pd.DataFrame):
          schema = Schema(
              [
                  ColSpec(
                      type=_infer_pandas_column(data[col]),
                      name=col,
                      required=_infer_required(data[col]),
                  )
                  for col in data.columns
              ]
          )
      # numpy.ndarray
      elif isinstance(data, np.ndarray):
          schema = Schema(
              [
                  TensorSpec(
                      type=clean_tensor_type(data.dtype),
                      shape=_get_tensor_shape(data),
                  )
              ]
          )
      # scipy.sparse.csr_matrix/csc_matrix
      elif isinstance(data, (csc_matrix, csr_matrix)):
          schema = Schema(
              [
                  TensorSpec(
                      type=clean_tensor_type(data.data.dtype),
                      shape=_get_tensor_shape(data),
                  )
              ]
          )
      # pyspark.sql.DataFrame
      elif _is_spark_df(data):
          schema = Schema(
              [
                  ColSpec(
                      type=_infer_spark_type(
                          field.dataType, data, field.name
                      ),
                      name=field.name,
                      # Avoid setting required field for spark dataframe
                      # as the default value for spark df nullable is True
                      # which counterparts to default required=True in ColSpec
                  )
                  for field in data.schema.fields
              ]
          )
      elif isinstance(data, list):
          # Assume list as a single column
          # List[DataType]
          # e.g. ['some sentence', 'some sentence'] -> Schema([ColSpec(type=DataType.string)])
          # The corresponding pandas DataFrame representation should be pd.DataFrame(data)
          # We set required=True as unnamed optional inputs is not allowed
          schema = Schema([ColSpec(_infer_colspec_type(data).dtype)])
      else:
          # DataType
          # e.g. "some sentence" -> Schema([ColSpec(type=DataType.string)])
          try:
              # We set required=True as unnamed optional inputs is not allowed
              schema = Schema([ColSpec(_infer_colspec_type(data))])
          except MlflowException as e:
              raise MlflowException.invalid_parameter_value(
                  "Failed to infer schema. Expected one of the following types:\n"
                  "- pandas.DataFrame\n"
                  "- pandas.Series\n"
                  "- numpy.ndarray\n"
                  "- dictionary of (name -> numpy.ndarray)\n"
                  "- pyspark.sql.DataFrame\n"
                  "- scipy.sparse.csr_matrix\n"
                  "- scipy.sparse.csc_matrix\n"
                  "- DataType\n"
                  "- List[DataType]\n"
                  "- Dict[str, Union[DataType, List, Dict]]\n"
                  "- List[Dict[str, Union[DataType, List, Dict]]]\n"
                  f"but got '{data}'.\n"
                  f"Error: {e}",
              )
      if not schema.is_tensor_spec() and any(
          t in (DataType.integer, DataType.long)
          for t in schema.input_types()
      ):
          warnings.warn(
              "Hint: Inferred schema contains integer column(s). Integer columns in "
              "Python cannot represent missing values. If your input data contains "
              "missing values at inference time, it will be encoded as floats and will "
              "cause a schema enforcement error. The best way to avoid this problem is "
              "to infer the model schema based on a realistic data sample (training "
              "dataset) that includes missing values. Alternatively, you can declare "
              "integer columns as doubles (float64) whenever these columns may have "
              "missing values. See `Handling Integers With Missing Values "
              "<https://www.mlflow.org/docs/latest/models.html#"
              "handling-integers-with-missing-values>`_ for more details."
          )
      return schema
  
imports: import logging
  import warnings
  from collections import defaultdict
  from typing import Any, Dict, List, Optional, Union
  import numpy
  import pandas
  from mlflow.exceptions import MlflowException
  from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
  from mlflow.types import DataType
  from mlflow.types.schema import Array, ColSpec, Object, ParamSchema, ParamSpec, Property, Schema, TensorSpec
label_desc: Use image node_id 7 for calling a global function with example usage: _infer_schema(data) and returns: schema, Schema