code: def _convert_k_neighbors_classifier(model, input_name, output_name):
      """Convert the scikit KNeighborsClassifier to CoreML. Assumes initial validation of the scikit model has been done."""
  
      spec = coremltools.proto.Model_pb2.Model()
      spec.specificationVersion = coremltools.SPECIFICATION_VERSION
  
      spec.kNearestNeighborsClassifier.numberOfNeighbors.defaultValue = (
          model.n_neighbors
      )
      spec.kNearestNeighborsClassifier.numberOfNeighbors.range.minValue = (
          1
      )
      spec.kNearestNeighborsClassifier.numberOfNeighbors.range.maxValue = _number_of_samples(
          model, spec
      )  # is there a better heuristic to use here?
  
      number_of_dimensions = 0
      if _is_algorithm_brute(model):
          number_of_dimensions = model._fit_X.shape[1]
          spec.kNearestNeighborsClassifier.nearestNeighborsIndex.linearIndex.MergeFromString(
              b""
          )
      elif _is_algorithm_kd_tree(model):
          npdata = np.asarray(model._tree.data)
          number_of_dimensions = get_input_dimension(model)
          spec.kNearestNeighborsClassifier.nearestNeighborsIndex.singleKdTreeIndex.leafSize = (
              model.leaf_size
          )
      else:
          raise TypeError(
              "KNeighbors algorithm not supported for CoreML conversion: {}".format(
                  model.algorithm
              )
          )
      spec.kNearestNeighborsClassifier.nearestNeighborsIndex.numberOfDimensions = (
          number_of_dimensions
      )
  
      # Make sure the distance function is set
      spec.kNearestNeighborsClassifier.nearestNeighborsIndex.squaredEuclideanDistance.MergeFromString(
          b""
      )
  
      input_features = spec.description.input.add()
      input_features.name = input_name[0][0]
      input_features.type.multiArrayType.shape.extend(
          [number_of_dimensions]
      )
      input_features.type.multiArrayType.dataType = (
          FeatureTypes_pb2.ArrayFeatureType.FLOAT32
      )
  
      output_label = spec.description.output.add()
      output_label.name = output_name[0][0]
  
      # predictedFeatureName is required since KNN is a classifier and it should be same as outputName.
      spec.description.predictedFeatureName = output_label.name
  
      # Need to confirm if scikit only accepts integer labels
      output_label.type.int64Type.MergeFromString(b"")
      spec.kNearestNeighborsClassifier.uniformWeighting.MergeFromString(
          b""
      )
  
      _extract_training_data(model, spec)
  
      return spec
  
imports: from ..._deps import _HAS_SKLEARN
  from ...models import MLModel
  import coremltools
  from coremltools.proto import FeatureTypes_pb2
  import numpy
  import scipy
  import six
label_desc: Use image node_id 4 for calling a global function with example usage: _convert_k_neighbors_classifier(model, input_name, output_name) and returns: spec