snowflake-ml-python 1.3.1__py3-none-any.whl → 1.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. snowflake/ml/_internal/env_utils.py +11 -1
  2. snowflake/ml/_internal/human_readable_id/adjectives.txt +128 -0
  3. snowflake/ml/_internal/human_readable_id/animals.txt +128 -0
  4. snowflake/ml/_internal/human_readable_id/hrid_generator.py +40 -0
  5. snowflake/ml/_internal/human_readable_id/hrid_generator_base.py +135 -0
  6. snowflake/ml/_internal/utils/formatting.py +1 -1
  7. snowflake/ml/_internal/utils/identifier.py +3 -1
  8. snowflake/ml/_internal/utils/sql_identifier.py +2 -6
  9. snowflake/ml/feature_store/feature_store.py +166 -184
  10. snowflake/ml/feature_store/feature_view.py +12 -24
  11. snowflake/ml/fileset/sfcfs.py +56 -50
  12. snowflake/ml/fileset/stage_fs.py +48 -13
  13. snowflake/ml/model/_client/model/model_version_impl.py +6 -49
  14. snowflake/ml/model/_client/ops/model_ops.py +78 -29
  15. snowflake/ml/model/_client/sql/model.py +23 -2
  16. snowflake/ml/model/_client/sql/model_version.py +22 -1
  17. snowflake/ml/model/_deploy_client/image_builds/server_image_builder.py +1 -3
  18. snowflake/ml/model/_deploy_client/snowservice/deploy.py +5 -2
  19. snowflake/ml/model/_model_composer/model_composer.py +7 -5
  20. snowflake/ml/model/_model_composer/model_manifest/model_manifest.py +19 -54
  21. snowflake/ml/model/_model_composer/model_manifest/model_manifest_schema.py +8 -1
  22. snowflake/ml/model/_model_composer/model_method/infer_table_function.py_template +1 -1
  23. snowflake/ml/model/_model_composer/model_method/model_method.py +6 -10
  24. snowflake/ml/model/_packager/model_handlers/catboost.py +206 -0
  25. snowflake/ml/model/_packager/model_handlers/lightgbm.py +218 -0
  26. snowflake/ml/model/_packager/model_handlers/sklearn.py +3 -0
  27. snowflake/ml/model/_packager/model_handlers/snowmlmodel.py +13 -1
  28. snowflake/ml/model/_packager/model_handlers/xgboost.py +1 -1
  29. snowflake/ml/model/_packager/model_meta/_core_requirements.py +1 -1
  30. snowflake/ml/model/_packager/model_meta/model_meta.py +36 -6
  31. snowflake/ml/model/_packager/model_meta/model_meta_schema.py +20 -1
  32. snowflake/ml/model/_packager/model_meta_migrator/migrator_plans.py +3 -1
  33. snowflake/ml/model/_packager/model_packager.py +2 -2
  34. snowflake/ml/model/{_model_composer/model_runtime/_runtime_requirements.py → _packager/model_runtime/_snowml_inference_alternative_requirements.py} +1 -1
  35. snowflake/ml/model/_packager/model_runtime/model_runtime.py +137 -0
  36. snowflake/ml/model/custom_model.py +3 -1
  37. snowflake/ml/model/type_hints.py +21 -2
  38. snowflake/ml/modeling/_internal/estimator_utils.py +16 -11
  39. snowflake/ml/modeling/_internal/local_implementations/pandas_handlers.py +4 -1
  40. snowflake/ml/modeling/_internal/model_specifications.py +3 -1
  41. snowflake/ml/modeling/_internal/snowpark_implementations/distributed_hpo_trainer.py +545 -0
  42. snowflake/ml/modeling/_internal/snowpark_implementations/snowpark_handlers.py +8 -5
  43. snowflake/ml/modeling/calibration/calibrated_classifier_cv.py +195 -123
  44. snowflake/ml/modeling/cluster/affinity_propagation.py +195 -123
  45. snowflake/ml/modeling/cluster/agglomerative_clustering.py +195 -123
  46. snowflake/ml/modeling/cluster/birch.py +195 -123
  47. snowflake/ml/modeling/cluster/bisecting_k_means.py +195 -123
  48. snowflake/ml/modeling/cluster/dbscan.py +195 -123
  49. snowflake/ml/modeling/cluster/feature_agglomeration.py +195 -123
  50. snowflake/ml/modeling/cluster/k_means.py +195 -123
  51. snowflake/ml/modeling/cluster/mean_shift.py +195 -123
  52. snowflake/ml/modeling/cluster/mini_batch_k_means.py +195 -123
  53. snowflake/ml/modeling/cluster/optics.py +195 -123
  54. snowflake/ml/modeling/cluster/spectral_biclustering.py +195 -123
  55. snowflake/ml/modeling/cluster/spectral_clustering.py +195 -123
  56. snowflake/ml/modeling/cluster/spectral_coclustering.py +195 -123
  57. snowflake/ml/modeling/compose/column_transformer.py +195 -123
  58. snowflake/ml/modeling/compose/transformed_target_regressor.py +195 -123
  59. snowflake/ml/modeling/covariance/elliptic_envelope.py +195 -123
  60. snowflake/ml/modeling/covariance/empirical_covariance.py +195 -123
  61. snowflake/ml/modeling/covariance/graphical_lasso.py +195 -123
  62. snowflake/ml/modeling/covariance/graphical_lasso_cv.py +195 -123
  63. snowflake/ml/modeling/covariance/ledoit_wolf.py +195 -123
  64. snowflake/ml/modeling/covariance/min_cov_det.py +195 -123
  65. snowflake/ml/modeling/covariance/oas.py +195 -123
  66. snowflake/ml/modeling/covariance/shrunk_covariance.py +195 -123
  67. snowflake/ml/modeling/decomposition/dictionary_learning.py +195 -123
  68. snowflake/ml/modeling/decomposition/factor_analysis.py +195 -123
  69. snowflake/ml/modeling/decomposition/fast_ica.py +195 -123
  70. snowflake/ml/modeling/decomposition/incremental_pca.py +195 -123
  71. snowflake/ml/modeling/decomposition/kernel_pca.py +195 -123
  72. snowflake/ml/modeling/decomposition/mini_batch_dictionary_learning.py +195 -123
  73. snowflake/ml/modeling/decomposition/mini_batch_sparse_pca.py +195 -123
  74. snowflake/ml/modeling/decomposition/pca.py +195 -123
  75. snowflake/ml/modeling/decomposition/sparse_pca.py +195 -123
  76. snowflake/ml/modeling/decomposition/truncated_svd.py +195 -123
  77. snowflake/ml/modeling/discriminant_analysis/linear_discriminant_analysis.py +195 -123
  78. snowflake/ml/modeling/discriminant_analysis/quadratic_discriminant_analysis.py +195 -123
  79. snowflake/ml/modeling/ensemble/ada_boost_classifier.py +195 -123
  80. snowflake/ml/modeling/ensemble/ada_boost_regressor.py +195 -123
  81. snowflake/ml/modeling/ensemble/bagging_classifier.py +195 -123
  82. snowflake/ml/modeling/ensemble/bagging_regressor.py +195 -123
  83. snowflake/ml/modeling/ensemble/extra_trees_classifier.py +195 -123
  84. snowflake/ml/modeling/ensemble/extra_trees_regressor.py +195 -123
  85. snowflake/ml/modeling/ensemble/gradient_boosting_classifier.py +195 -123
  86. snowflake/ml/modeling/ensemble/gradient_boosting_regressor.py +195 -123
  87. snowflake/ml/modeling/ensemble/hist_gradient_boosting_classifier.py +195 -123
  88. snowflake/ml/modeling/ensemble/hist_gradient_boosting_regressor.py +195 -123
  89. snowflake/ml/modeling/ensemble/isolation_forest.py +195 -123
  90. snowflake/ml/modeling/ensemble/random_forest_classifier.py +195 -123
  91. snowflake/ml/modeling/ensemble/random_forest_regressor.py +195 -123
  92. snowflake/ml/modeling/ensemble/stacking_regressor.py +195 -123
  93. snowflake/ml/modeling/ensemble/voting_classifier.py +195 -123
  94. snowflake/ml/modeling/ensemble/voting_regressor.py +195 -123
  95. snowflake/ml/modeling/feature_selection/generic_univariate_select.py +195 -123
  96. snowflake/ml/modeling/feature_selection/select_fdr.py +195 -123
  97. snowflake/ml/modeling/feature_selection/select_fpr.py +195 -123
  98. snowflake/ml/modeling/feature_selection/select_fwe.py +195 -123
  99. snowflake/ml/modeling/feature_selection/select_k_best.py +195 -123
  100. snowflake/ml/modeling/feature_selection/select_percentile.py +195 -123
  101. snowflake/ml/modeling/feature_selection/sequential_feature_selector.py +195 -123
  102. snowflake/ml/modeling/feature_selection/variance_threshold.py +195 -123
  103. snowflake/ml/modeling/framework/_utils.py +8 -1
  104. snowflake/ml/modeling/framework/base.py +24 -6
  105. snowflake/ml/modeling/gaussian_process/gaussian_process_classifier.py +195 -123
  106. snowflake/ml/modeling/gaussian_process/gaussian_process_regressor.py +195 -123
  107. snowflake/ml/modeling/impute/iterative_imputer.py +195 -123
  108. snowflake/ml/modeling/impute/knn_imputer.py +195 -123
  109. snowflake/ml/modeling/impute/missing_indicator.py +195 -123
  110. snowflake/ml/modeling/impute/simple_imputer.py +4 -15
  111. snowflake/ml/modeling/kernel_approximation/additive_chi2_sampler.py +195 -123
  112. snowflake/ml/modeling/kernel_approximation/nystroem.py +195 -123
  113. snowflake/ml/modeling/kernel_approximation/polynomial_count_sketch.py +195 -123
  114. snowflake/ml/modeling/kernel_approximation/rbf_sampler.py +195 -123
  115. snowflake/ml/modeling/kernel_approximation/skewed_chi2_sampler.py +195 -123
  116. snowflake/ml/modeling/kernel_ridge/kernel_ridge.py +195 -123
  117. snowflake/ml/modeling/lightgbm/lgbm_classifier.py +198 -125
  118. snowflake/ml/modeling/lightgbm/lgbm_regressor.py +198 -125
  119. snowflake/ml/modeling/linear_model/ard_regression.py +195 -123
  120. snowflake/ml/modeling/linear_model/bayesian_ridge.py +195 -123
  121. snowflake/ml/modeling/linear_model/elastic_net.py +195 -123
  122. snowflake/ml/modeling/linear_model/elastic_net_cv.py +195 -123
  123. snowflake/ml/modeling/linear_model/gamma_regressor.py +195 -123
  124. snowflake/ml/modeling/linear_model/huber_regressor.py +195 -123
  125. snowflake/ml/modeling/linear_model/lars.py +195 -123
  126. snowflake/ml/modeling/linear_model/lars_cv.py +195 -123
  127. snowflake/ml/modeling/linear_model/lasso.py +195 -123
  128. snowflake/ml/modeling/linear_model/lasso_cv.py +195 -123
  129. snowflake/ml/modeling/linear_model/lasso_lars.py +195 -123
  130. snowflake/ml/modeling/linear_model/lasso_lars_cv.py +195 -123
  131. snowflake/ml/modeling/linear_model/lasso_lars_ic.py +195 -123
  132. snowflake/ml/modeling/linear_model/linear_regression.py +195 -123
  133. snowflake/ml/modeling/linear_model/logistic_regression.py +195 -123
  134. snowflake/ml/modeling/linear_model/logistic_regression_cv.py +195 -123
  135. snowflake/ml/modeling/linear_model/multi_task_elastic_net.py +195 -123
  136. snowflake/ml/modeling/linear_model/multi_task_elastic_net_cv.py +195 -123
  137. snowflake/ml/modeling/linear_model/multi_task_lasso.py +195 -123
  138. snowflake/ml/modeling/linear_model/multi_task_lasso_cv.py +195 -123
  139. snowflake/ml/modeling/linear_model/orthogonal_matching_pursuit.py +195 -123
  140. snowflake/ml/modeling/linear_model/passive_aggressive_classifier.py +195 -123
  141. snowflake/ml/modeling/linear_model/passive_aggressive_regressor.py +195 -123
  142. snowflake/ml/modeling/linear_model/perceptron.py +195 -123
  143. snowflake/ml/modeling/linear_model/poisson_regressor.py +195 -123
  144. snowflake/ml/modeling/linear_model/ransac_regressor.py +195 -123
  145. snowflake/ml/modeling/linear_model/ridge.py +195 -123
  146. snowflake/ml/modeling/linear_model/ridge_classifier.py +195 -123
  147. snowflake/ml/modeling/linear_model/ridge_classifier_cv.py +195 -123
  148. snowflake/ml/modeling/linear_model/ridge_cv.py +195 -123
  149. snowflake/ml/modeling/linear_model/sgd_classifier.py +195 -123
  150. snowflake/ml/modeling/linear_model/sgd_one_class_svm.py +195 -123
  151. snowflake/ml/modeling/linear_model/sgd_regressor.py +195 -123
  152. snowflake/ml/modeling/linear_model/theil_sen_regressor.py +195 -123
  153. snowflake/ml/modeling/linear_model/tweedie_regressor.py +195 -123
  154. snowflake/ml/modeling/manifold/isomap.py +195 -123
  155. snowflake/ml/modeling/manifold/mds.py +195 -123
  156. snowflake/ml/modeling/manifold/spectral_embedding.py +195 -123
  157. snowflake/ml/modeling/manifold/tsne.py +195 -123
  158. snowflake/ml/modeling/mixture/bayesian_gaussian_mixture.py +195 -123
  159. snowflake/ml/modeling/mixture/gaussian_mixture.py +195 -123
  160. snowflake/ml/modeling/model_selection/grid_search_cv.py +42 -18
  161. snowflake/ml/modeling/model_selection/randomized_search_cv.py +42 -18
  162. snowflake/ml/modeling/multiclass/one_vs_one_classifier.py +195 -123
  163. snowflake/ml/modeling/multiclass/one_vs_rest_classifier.py +195 -123
  164. snowflake/ml/modeling/multiclass/output_code_classifier.py +195 -123
  165. snowflake/ml/modeling/naive_bayes/bernoulli_nb.py +195 -123
  166. snowflake/ml/modeling/naive_bayes/categorical_nb.py +195 -123
  167. snowflake/ml/modeling/naive_bayes/complement_nb.py +195 -123
  168. snowflake/ml/modeling/naive_bayes/gaussian_nb.py +195 -123
  169. snowflake/ml/modeling/naive_bayes/multinomial_nb.py +195 -123
  170. snowflake/ml/modeling/neighbors/k_neighbors_classifier.py +195 -123
  171. snowflake/ml/modeling/neighbors/k_neighbors_regressor.py +195 -123
  172. snowflake/ml/modeling/neighbors/kernel_density.py +195 -123
  173. snowflake/ml/modeling/neighbors/local_outlier_factor.py +195 -123
  174. snowflake/ml/modeling/neighbors/nearest_centroid.py +195 -123
  175. snowflake/ml/modeling/neighbors/nearest_neighbors.py +195 -123
  176. snowflake/ml/modeling/neighbors/neighborhood_components_analysis.py +195 -123
  177. snowflake/ml/modeling/neighbors/radius_neighbors_classifier.py +195 -123
  178. snowflake/ml/modeling/neighbors/radius_neighbors_regressor.py +195 -123
  179. snowflake/ml/modeling/neural_network/bernoulli_rbm.py +195 -123
  180. snowflake/ml/modeling/neural_network/mlp_classifier.py +195 -123
  181. snowflake/ml/modeling/neural_network/mlp_regressor.py +195 -123
  182. snowflake/ml/modeling/pipeline/pipeline.py +4 -4
  183. snowflake/ml/modeling/preprocessing/binarizer.py +1 -5
  184. snowflake/ml/modeling/preprocessing/k_bins_discretizer.py +1 -5
  185. snowflake/ml/modeling/preprocessing/label_encoder.py +1 -5
  186. snowflake/ml/modeling/preprocessing/max_abs_scaler.py +1 -5
  187. snowflake/ml/modeling/preprocessing/min_max_scaler.py +10 -12
  188. snowflake/ml/modeling/preprocessing/normalizer.py +1 -5
  189. snowflake/ml/modeling/preprocessing/one_hot_encoder.py +1 -5
  190. snowflake/ml/modeling/preprocessing/ordinal_encoder.py +1 -5
  191. snowflake/ml/modeling/preprocessing/polynomial_features.py +195 -123
  192. snowflake/ml/modeling/preprocessing/robust_scaler.py +1 -5
  193. snowflake/ml/modeling/preprocessing/standard_scaler.py +11 -11
  194. snowflake/ml/modeling/semi_supervised/label_propagation.py +195 -123
  195. snowflake/ml/modeling/semi_supervised/label_spreading.py +195 -123
  196. snowflake/ml/modeling/svm/linear_svc.py +195 -123
  197. snowflake/ml/modeling/svm/linear_svr.py +195 -123
  198. snowflake/ml/modeling/svm/nu_svc.py +195 -123
  199. snowflake/ml/modeling/svm/nu_svr.py +195 -123
  200. snowflake/ml/modeling/svm/svc.py +195 -123
  201. snowflake/ml/modeling/svm/svr.py +195 -123
  202. snowflake/ml/modeling/tree/decision_tree_classifier.py +195 -123
  203. snowflake/ml/modeling/tree/decision_tree_regressor.py +195 -123
  204. snowflake/ml/modeling/tree/extra_tree_classifier.py +195 -123
  205. snowflake/ml/modeling/tree/extra_tree_regressor.py +195 -123
  206. snowflake/ml/modeling/xgboost/xgb_classifier.py +195 -123
  207. snowflake/ml/modeling/xgboost/xgb_regressor.py +195 -123
  208. snowflake/ml/modeling/xgboost/xgbrf_classifier.py +195 -123
  209. snowflake/ml/modeling/xgboost/xgbrf_regressor.py +195 -123
  210. snowflake/ml/registry/_manager/model_manager.py +5 -1
  211. snowflake/ml/registry/model_registry.py +99 -26
  212. snowflake/ml/registry/registry.py +3 -2
  213. snowflake/ml/version.py +1 -1
  214. {snowflake_ml_python-1.3.1.dist-info → snowflake_ml_python-1.4.1.dist-info}/METADATA +94 -55
  215. {snowflake_ml_python-1.3.1.dist-info → snowflake_ml_python-1.4.1.dist-info}/RECORD +218 -212
  216. snowflake/ml/model/_model_composer/model_runtime/model_runtime.py +0 -97
  217. {snowflake_ml_python-1.3.1.dist-info → snowflake_ml_python-1.4.1.dist-info}/LICENSE.txt +0 -0
  218. {snowflake_ml_python-1.3.1.dist-info → snowflake_ml_python-1.4.1.dist-info}/WHEEL +0 -0
  219. {snowflake_ml_python-1.3.1.dist-info → snowflake_ml_python-1.4.1.dist-info}/top_level.txt +0 -0
@@ -33,6 +33,15 @@ from snowflake.ml.modeling._internal.transformer_protocols import (
33
33
  BatchInferenceKwargsTypedDict,
34
34
  ScoreKwargsTypedDict
35
35
  )
36
+ from snowflake.ml.model._signatures import utils as model_signature_utils
37
+ from snowflake.ml.model.model_signature import (
38
+ BaseFeatureSpec,
39
+ DataType,
40
+ FeatureSpec,
41
+ ModelSignature,
42
+ _infer_signature,
43
+ _rename_signature_with_snowflake_identifiers,
44
+ )
36
45
 
37
46
  from snowflake.ml.modeling._internal.model_transformer_builder import ModelTransformerBuilder
38
47
 
@@ -43,16 +52,6 @@ from snowflake.ml.modeling._internal.estimator_utils import (
43
52
  validate_sklearn_args,
44
53
  )
45
54
 
46
- from snowflake.ml.model.model_signature import (
47
- DataType,
48
- FeatureSpec,
49
- ModelSignature,
50
- _infer_signature,
51
- _rename_signature_with_snowflake_identifiers,
52
- BaseFeatureSpec,
53
- )
54
- from snowflake.ml.model._signatures import utils as model_signature_utils
55
-
56
55
  _PROJECT = "ModelDevelopment"
57
56
  # Derive subproject from module name by removing "sklearn"
58
57
  # and converting module name from underscore to CamelCase
@@ -273,12 +272,7 @@ class KNeighborsClassifier(BaseTransformer):
273
272
  )
274
273
  return selected_cols
275
274
 
276
- @telemetry.send_api_usage_telemetry(
277
- project=_PROJECT,
278
- subproject=_SUBPROJECT,
279
- custom_tags=dict([("autogen", True)]),
280
- )
281
- def fit(self, dataset: Union[DataFrame, pd.DataFrame]) -> "KNeighborsClassifier":
275
+ def _fit(self, dataset: Union[DataFrame, pd.DataFrame]) -> "KNeighborsClassifier":
282
276
  """Fit the k-nearest neighbors classifier from the training dataset
283
277
  For more details on this function, see [sklearn.neighbors.KNeighborsClassifier.fit]
284
278
  (https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier.fit)
@@ -305,12 +299,14 @@ class KNeighborsClassifier(BaseTransformer):
305
299
 
306
300
  self._snowpark_cols = dataset.select(self.input_cols).columns
307
301
 
308
- # If we are already in a stored procedure, no need to kick off another one.
302
+ # If we are already in a stored procedure, no need to kick off another one.
309
303
  if SNOWML_SPROC_ENV in os.environ:
310
304
  statement_params = telemetry.get_function_usage_statement_params(
311
305
  project=_PROJECT,
312
306
  subproject=_SUBPROJECT,
313
- function_name=telemetry.get_statement_params_full_func_name(inspect.currentframe(), KNeighborsClassifier.__class__.__name__),
307
+ function_name=telemetry.get_statement_params_full_func_name(
308
+ inspect.currentframe(), KNeighborsClassifier.__class__.__name__
309
+ ),
314
310
  api_calls=[Session.call],
315
311
  custom_tags=dict([("autogen", True)]) if self._autogenerated else None,
316
312
  )
@@ -331,7 +327,7 @@ class KNeighborsClassifier(BaseTransformer):
331
327
  )
332
328
  self._sklearn_object = model_trainer.train()
333
329
  self._is_fitted = True
334
- self._get_model_signatures(dataset)
330
+ self._generate_model_signatures(dataset)
335
331
  return self
336
332
 
337
333
  def _batch_inference_validate_snowpark(
@@ -407,7 +403,9 @@ class KNeighborsClassifier(BaseTransformer):
407
403
  # when it is classifier, infer the datatype from label columns
408
404
  if expected_type_inferred == "" and 'predict' in self.model_signatures:
409
405
  # Batch inference takes a single expected output column type. Use the first columns type for now.
410
- label_cols_signatures = [row for row in self.model_signatures['predict'].outputs if row.name in self.output_cols]
406
+ label_cols_signatures = [
407
+ row for row in self.model_signatures['predict'].outputs if row.name in self.output_cols
408
+ ]
411
409
  if len(label_cols_signatures) == 0:
412
410
  error_str = f"Output columns {self.output_cols} do not match model signatures {self.model_signatures['predict'].outputs}."
413
411
  raise exceptions.SnowflakeMLException(
@@ -415,25 +413,22 @@ class KNeighborsClassifier(BaseTransformer):
415
413
  original_exception=ValueError(error_str),
416
414
  )
417
415
 
418
- expected_type_inferred = convert_sp_to_sf_type(
419
- label_cols_signatures[0].as_snowpark_type()
420
- )
416
+ expected_type_inferred = convert_sp_to_sf_type(label_cols_signatures[0].as_snowpark_type())
421
417
 
422
418
  self._deps = self._batch_inference_validate_snowpark(dataset=dataset, inference_method=inference_method)
423
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
419
+ assert isinstance(
420
+ dataset._session, Session
421
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
424
422
 
425
423
  transform_kwargs = dict(
426
- session = dataset._session,
427
- dependencies = self._deps,
428
- drop_input_cols = self._drop_input_cols,
429
- expected_output_cols_type = expected_type_inferred,
424
+ session=dataset._session,
425
+ dependencies=self._deps,
426
+ drop_input_cols=self._drop_input_cols,
427
+ expected_output_cols_type=expected_type_inferred,
430
428
  )
431
429
 
432
430
  elif isinstance(dataset, pd.DataFrame):
433
- transform_kwargs = dict(
434
- snowpark_input_cols = self._snowpark_cols,
435
- drop_input_cols = self._drop_input_cols
436
- )
431
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
437
432
 
438
433
  transform_handlers = ModelTransformerBuilder.build(
439
434
  dataset=dataset,
@@ -473,7 +468,7 @@ class KNeighborsClassifier(BaseTransformer):
473
468
  Transformed dataset.
474
469
  """
475
470
  super()._check_dataset_type(dataset)
476
- inference_method="transform"
471
+ inference_method = "transform"
477
472
 
478
473
  # This dictionary contains optional kwargs for batch inference. These kwargs
479
474
  # are specific to the type of dataset used.
@@ -510,17 +505,14 @@ class KNeighborsClassifier(BaseTransformer):
510
505
  assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
511
506
 
512
507
  transform_kwargs = dict(
513
- session = dataset._session,
514
- dependencies = self._deps,
515
- drop_input_cols = self._drop_input_cols,
516
- expected_output_cols_type = expected_dtype,
508
+ session=dataset._session,
509
+ dependencies=self._deps,
510
+ drop_input_cols=self._drop_input_cols,
511
+ expected_output_cols_type=expected_dtype,
517
512
  )
518
513
 
519
514
  elif isinstance(dataset, pd.DataFrame):
520
- transform_kwargs = dict(
521
- snowpark_input_cols = self._snowpark_cols,
522
- drop_input_cols = self._drop_input_cols
523
- )
515
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
524
516
 
525
517
  transform_handlers = ModelTransformerBuilder.build(
526
518
  dataset=dataset,
@@ -539,7 +531,11 @@ class KNeighborsClassifier(BaseTransformer):
539
531
  return output_df
540
532
 
541
533
  @available_if(original_estimator_has_callable("fit_predict")) # type: ignore[misc]
542
- def fit_predict(self, dataset: Union[DataFrame, pd.DataFrame], output_cols_prefix: str = "fit_predict_",) -> Union[DataFrame, pd.DataFrame]:
534
+ def fit_predict(
535
+ self,
536
+ dataset: Union[DataFrame, pd.DataFrame],
537
+ output_cols_prefix: str = "fit_predict_",
538
+ ) -> Union[DataFrame, pd.DataFrame]:
543
539
  """ Method not supported for this class.
544
540
 
545
541
 
@@ -564,7 +560,9 @@ class KNeighborsClassifier(BaseTransformer):
564
560
  )
565
561
  output_result, fitted_estimator = model_trainer.train_fit_predict(
566
562
  drop_input_cols=self._drop_input_cols,
567
- expected_output_cols_list=self.output_cols if self.output_cols else self._get_output_column_names(output_cols_prefix),
563
+ expected_output_cols_list=(
564
+ self.output_cols if self.output_cols else self._get_output_column_names(output_cols_prefix)
565
+ ),
568
566
  )
569
567
  self._sklearn_object = fitted_estimator
570
568
  self._is_fitted = True
@@ -581,6 +579,62 @@ class KNeighborsClassifier(BaseTransformer):
581
579
  assert self._sklearn_object is not None
582
580
  return self._sklearn_object.embedding_
583
581
 
582
+
583
+ def _get_output_column_names(self, output_cols_prefix: str, output_cols: Optional[List[str]] = None) -> List[str]:
584
+ """ Returns the list of output columns for predict_proba(), decision_function(), etc.. functions.
585
+ Returns a list with output_cols_prefix as the only element if the estimator is not a classifier.
586
+ """
587
+ output_cols_prefix = identifier.resolve_identifier(output_cols_prefix)
588
+ # The following condition is introduced for kneighbors methods, and not used in other methods
589
+ if output_cols:
590
+ output_cols = [
591
+ identifier.concat_names([output_cols_prefix, identifier.resolve_identifier(c)])
592
+ for c in output_cols
593
+ ]
594
+ elif getattr(self._sklearn_object, "classes_", None) is None:
595
+ output_cols = [output_cols_prefix]
596
+ elif self._sklearn_object is not None:
597
+ classes = self._sklearn_object.classes_
598
+ if isinstance(classes, numpy.ndarray):
599
+ output_cols = [f'{output_cols_prefix}{str(c)}' for c in classes.tolist()]
600
+ elif isinstance(classes, list) and len(classes) > 0 and isinstance(classes[0], numpy.ndarray):
601
+ # If the estimator is a multioutput estimator, classes_ will be a list of ndarrays.
602
+ output_cols = []
603
+ for i, cl in enumerate(classes):
604
+ # For binary classification, there is only one output column for each class
605
+ # ndarray as the two classes are complementary.
606
+ if len(cl) == 2:
607
+ output_cols.append(f'{output_cols_prefix}{i}_{cl[0]}')
608
+ else:
609
+ output_cols.extend([
610
+ f'{output_cols_prefix}{i}_{c}' for c in cl.tolist()
611
+ ])
612
+ else:
613
+ output_cols = []
614
+
615
+ # Make sure column names are valid snowflake identifiers.
616
+ assert output_cols is not None # Make MyPy happy
617
+ rv = [identifier.rename_to_valid_snowflake_identifier(c) for c in output_cols]
618
+
619
+ return rv
620
+
621
+ def _align_expected_output_names(
622
+ self, method: str, dataset: DataFrame, expected_output_cols_list: List[str], output_cols_prefix: str
623
+ ) -> List[str]:
624
+ # in case the inferred output column names dimension is different
625
+ # we use one line of snowpark dataframe and put it into sklearn estimator using pandas
626
+ output_df_pd = getattr(self, method)(dataset.limit(1).to_pandas(), output_cols_prefix)
627
+ output_df_columns = list(output_df_pd.columns)
628
+ output_df_columns_set: Set[str] = set(output_df_columns) - set(dataset.columns)
629
+ if self.sample_weight_col:
630
+ output_df_columns_set -= set(self.sample_weight_col)
631
+ # if the dimension of inferred output column names is correct; use it
632
+ if len(expected_output_cols_list) == len(output_df_columns_set):
633
+ return expected_output_cols_list
634
+ # otherwise, use the sklearn estimator's output
635
+ else:
636
+ return sorted(list(output_df_columns_set), key=lambda x: output_df_columns.index(x))
637
+
584
638
  @available_if(original_estimator_has_callable("predict_proba")) # type: ignore[misc]
585
639
  @telemetry.send_api_usage_telemetry(
586
640
  project=_PROJECT,
@@ -613,24 +667,28 @@ class KNeighborsClassifier(BaseTransformer):
613
667
  # are specific to the type of dataset used.
614
668
  transform_kwargs: BatchInferenceKwargsTypedDict = dict()
615
669
 
670
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
671
+
616
672
  if isinstance(dataset, DataFrame):
617
673
  self._deps = self._batch_inference_validate_snowpark(
618
674
  dataset=dataset,
619
675
  inference_method=inference_method,
620
676
  )
621
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
677
+ assert isinstance(
678
+ dataset._session, Session
679
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
622
680
  transform_kwargs = dict(
623
681
  session=dataset._session,
624
682
  dependencies=self._deps,
625
- drop_input_cols = self._drop_input_cols,
683
+ drop_input_cols=self._drop_input_cols,
626
684
  expected_output_cols_type="float",
627
685
  )
686
+ expected_output_cols = self._align_expected_output_names(
687
+ inference_method, dataset, expected_output_cols, output_cols_prefix
688
+ )
628
689
 
629
690
  elif isinstance(dataset, pd.DataFrame):
630
- transform_kwargs = dict(
631
- snowpark_input_cols = self._snowpark_cols,
632
- drop_input_cols = self._drop_input_cols
633
- )
691
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
634
692
 
635
693
  transform_handlers = ModelTransformerBuilder.build(
636
694
  dataset=dataset,
@@ -642,7 +700,7 @@ class KNeighborsClassifier(BaseTransformer):
642
700
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
643
701
  inference_method=inference_method,
644
702
  input_cols=self.input_cols,
645
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
703
+ expected_output_cols=expected_output_cols,
646
704
  **transform_kwargs
647
705
  )
648
706
  return output_df
@@ -674,7 +732,8 @@ class KNeighborsClassifier(BaseTransformer):
674
732
  Output dataset with log probability of the sample for each class in the model.
675
733
  """
676
734
  super()._check_dataset_type(dataset)
677
- inference_method="predict_log_proba"
735
+ inference_method = "predict_log_proba"
736
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
678
737
 
679
738
  # This dictionary contains optional kwargs for batch inference. These kwargs
680
739
  # are specific to the type of dataset used.
@@ -685,18 +744,20 @@ class KNeighborsClassifier(BaseTransformer):
685
744
  dataset=dataset,
686
745
  inference_method=inference_method,
687
746
  )
688
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
747
+ assert isinstance(
748
+ dataset._session, Session
749
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
689
750
  transform_kwargs = dict(
690
751
  session=dataset._session,
691
752
  dependencies=self._deps,
692
- drop_input_cols = self._drop_input_cols,
753
+ drop_input_cols=self._drop_input_cols,
693
754
  expected_output_cols_type="float",
694
755
  )
756
+ expected_output_cols = self._align_expected_output_names(
757
+ inference_method, dataset, expected_output_cols, output_cols_prefix
758
+ )
695
759
  elif isinstance(dataset, pd.DataFrame):
696
- transform_kwargs = dict(
697
- snowpark_input_cols = self._snowpark_cols,
698
- drop_input_cols = self._drop_input_cols
699
- )
760
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
700
761
 
701
762
  transform_handlers = ModelTransformerBuilder.build(
702
763
  dataset=dataset,
@@ -709,7 +770,7 @@ class KNeighborsClassifier(BaseTransformer):
709
770
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
710
771
  inference_method=inference_method,
711
772
  input_cols=self.input_cols,
712
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
773
+ expected_output_cols=expected_output_cols,
713
774
  **transform_kwargs
714
775
  )
715
776
  return output_df
@@ -735,30 +796,34 @@ class KNeighborsClassifier(BaseTransformer):
735
796
  Output dataset with results of the decision function for the samples in input dataset.
736
797
  """
737
798
  super()._check_dataset_type(dataset)
738
- inference_method="decision_function"
799
+ inference_method = "decision_function"
739
800
 
740
801
  # This dictionary contains optional kwargs for batch inference. These kwargs
741
802
  # are specific to the type of dataset used.
742
803
  transform_kwargs: BatchInferenceKwargsTypedDict = dict()
743
804
 
805
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
806
+
744
807
  if isinstance(dataset, DataFrame):
745
808
  self._deps = self._batch_inference_validate_snowpark(
746
809
  dataset=dataset,
747
810
  inference_method=inference_method,
748
811
  )
749
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
812
+ assert isinstance(
813
+ dataset._session, Session
814
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
750
815
  transform_kwargs = dict(
751
816
  session=dataset._session,
752
817
  dependencies=self._deps,
753
- drop_input_cols = self._drop_input_cols,
818
+ drop_input_cols=self._drop_input_cols,
754
819
  expected_output_cols_type="float",
755
820
  )
821
+ expected_output_cols = self._align_expected_output_names(
822
+ inference_method, dataset, expected_output_cols, output_cols_prefix
823
+ )
756
824
 
757
825
  elif isinstance(dataset, pd.DataFrame):
758
- transform_kwargs = dict(
759
- snowpark_input_cols = self._snowpark_cols,
760
- drop_input_cols = self._drop_input_cols
761
- )
826
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
762
827
 
763
828
  transform_handlers = ModelTransformerBuilder.build(
764
829
  dataset=dataset,
@@ -771,7 +836,7 @@ class KNeighborsClassifier(BaseTransformer):
771
836
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
772
837
  inference_method=inference_method,
773
838
  input_cols=self.input_cols,
774
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
839
+ expected_output_cols=expected_output_cols,
775
840
  **transform_kwargs
776
841
  )
777
842
  return output_df
@@ -800,12 +865,14 @@ class KNeighborsClassifier(BaseTransformer):
800
865
  Output dataset with probability of the sample for each class in the model.
801
866
  """
802
867
  super()._check_dataset_type(dataset)
803
- inference_method="score_samples"
868
+ inference_method = "score_samples"
804
869
 
805
870
  # This dictionary contains optional kwargs for batch inference. These kwargs
806
871
  # are specific to the type of dataset used.
807
872
  transform_kwargs: BatchInferenceKwargsTypedDict = dict()
808
873
 
874
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
875
+
809
876
  if isinstance(dataset, DataFrame):
810
877
  self._deps = self._batch_inference_validate_snowpark(
811
878
  dataset=dataset,
@@ -818,6 +885,9 @@ class KNeighborsClassifier(BaseTransformer):
818
885
  drop_input_cols = self._drop_input_cols,
819
886
  expected_output_cols_type="float",
820
887
  )
888
+ expected_output_cols = self._align_expected_output_names(
889
+ inference_method, dataset, expected_output_cols, output_cols_prefix
890
+ )
821
891
 
822
892
  elif isinstance(dataset, pd.DataFrame):
823
893
  transform_kwargs = dict(
@@ -836,7 +906,7 @@ class KNeighborsClassifier(BaseTransformer):
836
906
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
837
907
  inference_method=inference_method,
838
908
  input_cols=self.input_cols,
839
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
909
+ expected_output_cols=expected_output_cols,
840
910
  **transform_kwargs
841
911
  )
842
912
  return output_df
@@ -985,50 +1055,84 @@ class KNeighborsClassifier(BaseTransformer):
985
1055
  )
986
1056
  return output_df
987
1057
 
1058
+
1059
+
1060
+ def to_sklearn(self) -> Any:
1061
+ """Get sklearn.neighbors.KNeighborsClassifier object.
1062
+ """
1063
+ if self._sklearn_object is None:
1064
+ self._sklearn_object = self._create_sklearn_object()
1065
+ return self._sklearn_object
1066
+
1067
+ def to_xgboost(self) -> Any:
1068
+ raise exceptions.SnowflakeMLException(
1069
+ error_code=error_codes.METHOD_NOT_ALLOWED,
1070
+ original_exception=AttributeError(
1071
+ modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1072
+ "to_xgboost()",
1073
+ "to_sklearn()"
1074
+ )
1075
+ ),
1076
+ )
1077
+
1078
+ def to_lightgbm(self) -> Any:
1079
+ raise exceptions.SnowflakeMLException(
1080
+ error_code=error_codes.METHOD_NOT_ALLOWED,
1081
+ original_exception=AttributeError(
1082
+ modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1083
+ "to_lightgbm()",
1084
+ "to_sklearn()"
1085
+ )
1086
+ ),
1087
+ )
988
1088
 
989
- def _get_model_signatures(self, dataset: Union[DataFrame, pd.DataFrame]) -> None:
1089
+ def _get_dependencies(self) -> List[str]:
1090
+ return self._deps
1091
+
1092
+
1093
+ def _generate_model_signatures(self, dataset: Union[DataFrame, pd.DataFrame]) -> None:
990
1094
  self._model_signature_dict = dict()
991
1095
 
992
1096
  PROB_FUNCTIONS = ["predict_log_proba", "predict_proba", "decision_function"]
993
1097
 
994
- inputs = list(_infer_signature(dataset[self.input_cols], "input"))
1098
+ inputs = list(_infer_signature(dataset[self.input_cols], "input", use_snowflake_identifiers=True))
995
1099
  outputs: List[BaseFeatureSpec] = []
996
1100
  if hasattr(self, "predict"):
997
1101
  # keep mypy happy
998
- assert self._sklearn_object is not None and hasattr(self._sklearn_object, "_estimator_type")
1102
+ assert self._sklearn_object is not None and hasattr(self._sklearn_object, "_estimator_type")
999
1103
  # For classifier, the type of predict is the same as the type of label
1000
- if self._sklearn_object._estimator_type == 'classifier':
1001
- # label columns is the desired type for output
1104
+ if self._sklearn_object._estimator_type == "classifier":
1105
+ # label columns is the desired type for output
1002
1106
  outputs = list(_infer_signature(dataset[self.label_cols], "output", use_snowflake_identifiers=True))
1003
1107
  # rename the output columns
1004
1108
  outputs = list(model_signature_utils.rename_features(outputs, self.output_cols))
1005
- self._model_signature_dict["predict"] = ModelSignature(inputs,
1006
- ([] if self._drop_input_cols else inputs)
1007
- + outputs)
1109
+ self._model_signature_dict["predict"] = ModelSignature(
1110
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1111
+ )
1008
1112
  # For mixture models that use the density mixin, `predict` returns the argmax of the log prob.
1009
1113
  # For outlier models, returns -1 for outliers and 1 for inliers.
1010
- # Clusterer returns int64 cluster labels.
1114
+ # Clusterer returns int64 cluster labels.
1011
1115
  elif self._sklearn_object._estimator_type in ["DensityEstimator", "clusterer", "outlier_detector"]:
1012
1116
  outputs = [FeatureSpec(dtype=DataType.INT64, name=c) for c in self.output_cols]
1013
- self._model_signature_dict["predict"] = ModelSignature(inputs,
1014
- ([] if self._drop_input_cols else inputs)
1015
- + outputs)
1016
-
1117
+ self._model_signature_dict["predict"] = ModelSignature(
1118
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1119
+ )
1120
+
1017
1121
  # For regressor, the type of predict is float64
1018
- elif self._sklearn_object._estimator_type == 'regressor':
1122
+ elif self._sklearn_object._estimator_type == "regressor":
1019
1123
  outputs = [FeatureSpec(dtype=DataType.DOUBLE, name=c) for c in self.output_cols]
1020
- self._model_signature_dict["predict"] = ModelSignature(inputs,
1021
- ([] if self._drop_input_cols else inputs)
1022
- + outputs)
1023
-
1124
+ self._model_signature_dict["predict"] = ModelSignature(
1125
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1126
+ )
1127
+
1024
1128
  for prob_func in PROB_FUNCTIONS:
1025
1129
  if hasattr(self, prob_func):
1026
1130
  output_cols_prefix: str = f"{prob_func}_"
1027
1131
  output_column_names = self._get_output_column_names(output_cols_prefix)
1028
1132
  outputs = [FeatureSpec(dtype=DataType.DOUBLE, name=c) for c in output_column_names]
1029
- self._model_signature_dict[prob_func] = ModelSignature(inputs,
1030
- ([] if self._drop_input_cols else inputs)
1031
- + outputs)
1133
+ self._model_signature_dict[prob_func] = ModelSignature(
1134
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1135
+ )
1032
1136
 
1033
1137
  # Output signature names may still need to be renamed, since they were not created with `_infer_signature`.
1034
1138
  items = list(self._model_signature_dict.items())
@@ -1041,10 +1145,10 @@ class KNeighborsClassifier(BaseTransformer):
1041
1145
  """Returns model signature of current class.
1042
1146
 
1043
1147
  Raises:
1044
- exceptions.SnowflakeMLException: If estimator is not fitted, then model signature cannot be inferred
1148
+ SnowflakeMLException: If estimator is not fitted, then model signature cannot be inferred
1045
1149
 
1046
1150
  Returns:
1047
- Dict[str, ModelSignature]: each method and its input output signature
1151
+ Dict with each method and its input output signature
1048
1152
  """
1049
1153
  if self._model_signature_dict is None:
1050
1154
  raise exceptions.SnowflakeMLException(
@@ -1052,35 +1156,3 @@ class KNeighborsClassifier(BaseTransformer):
1052
1156
  original_exception=RuntimeError("Estimator not fitted before accessing property model_signatures!"),
1053
1157
  )
1054
1158
  return self._model_signature_dict
1055
-
1056
- def to_sklearn(self) -> Any:
1057
- """Get sklearn.neighbors.KNeighborsClassifier object.
1058
- """
1059
- if self._sklearn_object is None:
1060
- self._sklearn_object = self._create_sklearn_object()
1061
- return self._sklearn_object
1062
-
1063
- def to_xgboost(self) -> Any:
1064
- raise exceptions.SnowflakeMLException(
1065
- error_code=error_codes.METHOD_NOT_ALLOWED,
1066
- original_exception=AttributeError(
1067
- modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1068
- "to_xgboost()",
1069
- "to_sklearn()"
1070
- )
1071
- ),
1072
- )
1073
-
1074
- def to_lightgbm(self) -> Any:
1075
- raise exceptions.SnowflakeMLException(
1076
- error_code=error_codes.METHOD_NOT_ALLOWED,
1077
- original_exception=AttributeError(
1078
- modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1079
- "to_lightgbm()",
1080
- "to_sklearn()"
1081
- )
1082
- ),
1083
- )
1084
-
1085
- def _get_dependencies(self) -> List[str]:
1086
- return self._deps