snowflake-ml-python 1.4.0__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 (203) hide show
  1. snowflake/ml/_internal/env_utils.py +11 -1
  2. snowflake/ml/_internal/utils/identifier.py +3 -1
  3. snowflake/ml/_internal/utils/sql_identifier.py +2 -6
  4. snowflake/ml/feature_store/feature_store.py +151 -78
  5. snowflake/ml/feature_store/feature_view.py +12 -24
  6. snowflake/ml/fileset/sfcfs.py +56 -50
  7. snowflake/ml/fileset/stage_fs.py +48 -13
  8. snowflake/ml/model/_client/model/model_version_impl.py +2 -50
  9. snowflake/ml/model/_client/ops/model_ops.py +78 -29
  10. snowflake/ml/model/_client/sql/model.py +23 -2
  11. snowflake/ml/model/_client/sql/model_version.py +22 -1
  12. snowflake/ml/model/_model_composer/model_manifest/model_manifest.py +19 -54
  13. snowflake/ml/model/_model_composer/model_manifest/model_manifest_schema.py +8 -1
  14. snowflake/ml/model/_model_composer/model_method/model_method.py +6 -10
  15. snowflake/ml/model/_packager/model_handlers/catboost.py +206 -0
  16. snowflake/ml/model/_packager/model_handlers/lightgbm.py +218 -0
  17. snowflake/ml/model/_packager/model_handlers/sklearn.py +3 -0
  18. snowflake/ml/model/_packager/model_meta/_core_requirements.py +1 -1
  19. snowflake/ml/model/_packager/model_meta/model_meta.py +36 -6
  20. snowflake/ml/model/_packager/model_meta/model_meta_schema.py +20 -1
  21. snowflake/ml/model/_packager/model_meta_migrator/migrator_plans.py +3 -1
  22. snowflake/ml/model/_packager/model_packager.py +2 -2
  23. snowflake/ml/model/{_model_composer/model_runtime/_runtime_requirements.py → _packager/model_runtime/_snowml_inference_alternative_requirements.py} +1 -1
  24. snowflake/ml/model/_packager/model_runtime/model_runtime.py +137 -0
  25. snowflake/ml/model/type_hints.py +21 -2
  26. snowflake/ml/modeling/_internal/estimator_utils.py +16 -11
  27. snowflake/ml/modeling/_internal/local_implementations/pandas_handlers.py +4 -1
  28. snowflake/ml/modeling/_internal/snowpark_implementations/distributed_hpo_trainer.py +13 -14
  29. snowflake/ml/modeling/_internal/snowpark_implementations/snowpark_handlers.py +5 -5
  30. snowflake/ml/modeling/calibration/calibrated_classifier_cv.py +195 -123
  31. snowflake/ml/modeling/cluster/affinity_propagation.py +195 -123
  32. snowflake/ml/modeling/cluster/agglomerative_clustering.py +195 -123
  33. snowflake/ml/modeling/cluster/birch.py +195 -123
  34. snowflake/ml/modeling/cluster/bisecting_k_means.py +195 -123
  35. snowflake/ml/modeling/cluster/dbscan.py +195 -123
  36. snowflake/ml/modeling/cluster/feature_agglomeration.py +195 -123
  37. snowflake/ml/modeling/cluster/k_means.py +195 -123
  38. snowflake/ml/modeling/cluster/mean_shift.py +195 -123
  39. snowflake/ml/modeling/cluster/mini_batch_k_means.py +195 -123
  40. snowflake/ml/modeling/cluster/optics.py +195 -123
  41. snowflake/ml/modeling/cluster/spectral_biclustering.py +195 -123
  42. snowflake/ml/modeling/cluster/spectral_clustering.py +195 -123
  43. snowflake/ml/modeling/cluster/spectral_coclustering.py +195 -123
  44. snowflake/ml/modeling/compose/column_transformer.py +195 -123
  45. snowflake/ml/modeling/compose/transformed_target_regressor.py +195 -123
  46. snowflake/ml/modeling/covariance/elliptic_envelope.py +195 -123
  47. snowflake/ml/modeling/covariance/empirical_covariance.py +195 -123
  48. snowflake/ml/modeling/covariance/graphical_lasso.py +195 -123
  49. snowflake/ml/modeling/covariance/graphical_lasso_cv.py +195 -123
  50. snowflake/ml/modeling/covariance/ledoit_wolf.py +195 -123
  51. snowflake/ml/modeling/covariance/min_cov_det.py +195 -123
  52. snowflake/ml/modeling/covariance/oas.py +195 -123
  53. snowflake/ml/modeling/covariance/shrunk_covariance.py +195 -123
  54. snowflake/ml/modeling/decomposition/dictionary_learning.py +195 -123
  55. snowflake/ml/modeling/decomposition/factor_analysis.py +195 -123
  56. snowflake/ml/modeling/decomposition/fast_ica.py +195 -123
  57. snowflake/ml/modeling/decomposition/incremental_pca.py +195 -123
  58. snowflake/ml/modeling/decomposition/kernel_pca.py +195 -123
  59. snowflake/ml/modeling/decomposition/mini_batch_dictionary_learning.py +195 -123
  60. snowflake/ml/modeling/decomposition/mini_batch_sparse_pca.py +195 -123
  61. snowflake/ml/modeling/decomposition/pca.py +195 -123
  62. snowflake/ml/modeling/decomposition/sparse_pca.py +195 -123
  63. snowflake/ml/modeling/decomposition/truncated_svd.py +195 -123
  64. snowflake/ml/modeling/discriminant_analysis/linear_discriminant_analysis.py +195 -123
  65. snowflake/ml/modeling/discriminant_analysis/quadratic_discriminant_analysis.py +195 -123
  66. snowflake/ml/modeling/ensemble/ada_boost_classifier.py +195 -123
  67. snowflake/ml/modeling/ensemble/ada_boost_regressor.py +195 -123
  68. snowflake/ml/modeling/ensemble/bagging_classifier.py +195 -123
  69. snowflake/ml/modeling/ensemble/bagging_regressor.py +195 -123
  70. snowflake/ml/modeling/ensemble/extra_trees_classifier.py +195 -123
  71. snowflake/ml/modeling/ensemble/extra_trees_regressor.py +195 -123
  72. snowflake/ml/modeling/ensemble/gradient_boosting_classifier.py +195 -123
  73. snowflake/ml/modeling/ensemble/gradient_boosting_regressor.py +195 -123
  74. snowflake/ml/modeling/ensemble/hist_gradient_boosting_classifier.py +195 -123
  75. snowflake/ml/modeling/ensemble/hist_gradient_boosting_regressor.py +195 -123
  76. snowflake/ml/modeling/ensemble/isolation_forest.py +195 -123
  77. snowflake/ml/modeling/ensemble/random_forest_classifier.py +195 -123
  78. snowflake/ml/modeling/ensemble/random_forest_regressor.py +195 -123
  79. snowflake/ml/modeling/ensemble/stacking_regressor.py +195 -123
  80. snowflake/ml/modeling/ensemble/voting_classifier.py +195 -123
  81. snowflake/ml/modeling/ensemble/voting_regressor.py +195 -123
  82. snowflake/ml/modeling/feature_selection/generic_univariate_select.py +195 -123
  83. snowflake/ml/modeling/feature_selection/select_fdr.py +195 -123
  84. snowflake/ml/modeling/feature_selection/select_fpr.py +195 -123
  85. snowflake/ml/modeling/feature_selection/select_fwe.py +195 -123
  86. snowflake/ml/modeling/feature_selection/select_k_best.py +195 -123
  87. snowflake/ml/modeling/feature_selection/select_percentile.py +195 -123
  88. snowflake/ml/modeling/feature_selection/sequential_feature_selector.py +195 -123
  89. snowflake/ml/modeling/feature_selection/variance_threshold.py +195 -123
  90. snowflake/ml/modeling/framework/_utils.py +8 -1
  91. snowflake/ml/modeling/framework/base.py +9 -1
  92. snowflake/ml/modeling/gaussian_process/gaussian_process_classifier.py +195 -123
  93. snowflake/ml/modeling/gaussian_process/gaussian_process_regressor.py +195 -123
  94. snowflake/ml/modeling/impute/iterative_imputer.py +195 -123
  95. snowflake/ml/modeling/impute/knn_imputer.py +195 -123
  96. snowflake/ml/modeling/impute/missing_indicator.py +195 -123
  97. snowflake/ml/modeling/kernel_approximation/additive_chi2_sampler.py +195 -123
  98. snowflake/ml/modeling/kernel_approximation/nystroem.py +195 -123
  99. snowflake/ml/modeling/kernel_approximation/polynomial_count_sketch.py +195 -123
  100. snowflake/ml/modeling/kernel_approximation/rbf_sampler.py +195 -123
  101. snowflake/ml/modeling/kernel_approximation/skewed_chi2_sampler.py +195 -123
  102. snowflake/ml/modeling/kernel_ridge/kernel_ridge.py +195 -123
  103. snowflake/ml/modeling/lightgbm/lgbm_classifier.py +195 -123
  104. snowflake/ml/modeling/lightgbm/lgbm_regressor.py +195 -123
  105. snowflake/ml/modeling/linear_model/ard_regression.py +195 -123
  106. snowflake/ml/modeling/linear_model/bayesian_ridge.py +195 -123
  107. snowflake/ml/modeling/linear_model/elastic_net.py +195 -123
  108. snowflake/ml/modeling/linear_model/elastic_net_cv.py +195 -123
  109. snowflake/ml/modeling/linear_model/gamma_regressor.py +195 -123
  110. snowflake/ml/modeling/linear_model/huber_regressor.py +195 -123
  111. snowflake/ml/modeling/linear_model/lars.py +195 -123
  112. snowflake/ml/modeling/linear_model/lars_cv.py +195 -123
  113. snowflake/ml/modeling/linear_model/lasso.py +195 -123
  114. snowflake/ml/modeling/linear_model/lasso_cv.py +195 -123
  115. snowflake/ml/modeling/linear_model/lasso_lars.py +195 -123
  116. snowflake/ml/modeling/linear_model/lasso_lars_cv.py +195 -123
  117. snowflake/ml/modeling/linear_model/lasso_lars_ic.py +195 -123
  118. snowflake/ml/modeling/linear_model/linear_regression.py +195 -123
  119. snowflake/ml/modeling/linear_model/logistic_regression.py +195 -123
  120. snowflake/ml/modeling/linear_model/logistic_regression_cv.py +195 -123
  121. snowflake/ml/modeling/linear_model/multi_task_elastic_net.py +195 -123
  122. snowflake/ml/modeling/linear_model/multi_task_elastic_net_cv.py +195 -123
  123. snowflake/ml/modeling/linear_model/multi_task_lasso.py +195 -123
  124. snowflake/ml/modeling/linear_model/multi_task_lasso_cv.py +195 -123
  125. snowflake/ml/modeling/linear_model/orthogonal_matching_pursuit.py +195 -123
  126. snowflake/ml/modeling/linear_model/passive_aggressive_classifier.py +195 -123
  127. snowflake/ml/modeling/linear_model/passive_aggressive_regressor.py +195 -123
  128. snowflake/ml/modeling/linear_model/perceptron.py +195 -123
  129. snowflake/ml/modeling/linear_model/poisson_regressor.py +195 -123
  130. snowflake/ml/modeling/linear_model/ransac_regressor.py +195 -123
  131. snowflake/ml/modeling/linear_model/ridge.py +195 -123
  132. snowflake/ml/modeling/linear_model/ridge_classifier.py +195 -123
  133. snowflake/ml/modeling/linear_model/ridge_classifier_cv.py +195 -123
  134. snowflake/ml/modeling/linear_model/ridge_cv.py +195 -123
  135. snowflake/ml/modeling/linear_model/sgd_classifier.py +195 -123
  136. snowflake/ml/modeling/linear_model/sgd_one_class_svm.py +195 -123
  137. snowflake/ml/modeling/linear_model/sgd_regressor.py +195 -123
  138. snowflake/ml/modeling/linear_model/theil_sen_regressor.py +195 -123
  139. snowflake/ml/modeling/linear_model/tweedie_regressor.py +195 -123
  140. snowflake/ml/modeling/manifold/isomap.py +195 -123
  141. snowflake/ml/modeling/manifold/mds.py +195 -123
  142. snowflake/ml/modeling/manifold/spectral_embedding.py +195 -123
  143. snowflake/ml/modeling/manifold/tsne.py +195 -123
  144. snowflake/ml/modeling/mixture/bayesian_gaussian_mixture.py +195 -123
  145. snowflake/ml/modeling/mixture/gaussian_mixture.py +195 -123
  146. snowflake/ml/modeling/model_selection/grid_search_cv.py +42 -18
  147. snowflake/ml/modeling/model_selection/randomized_search_cv.py +42 -18
  148. snowflake/ml/modeling/multiclass/one_vs_one_classifier.py +195 -123
  149. snowflake/ml/modeling/multiclass/one_vs_rest_classifier.py +195 -123
  150. snowflake/ml/modeling/multiclass/output_code_classifier.py +195 -123
  151. snowflake/ml/modeling/naive_bayes/bernoulli_nb.py +195 -123
  152. snowflake/ml/modeling/naive_bayes/categorical_nb.py +195 -123
  153. snowflake/ml/modeling/naive_bayes/complement_nb.py +195 -123
  154. snowflake/ml/modeling/naive_bayes/gaussian_nb.py +195 -123
  155. snowflake/ml/modeling/naive_bayes/multinomial_nb.py +195 -123
  156. snowflake/ml/modeling/neighbors/k_neighbors_classifier.py +195 -123
  157. snowflake/ml/modeling/neighbors/k_neighbors_regressor.py +195 -123
  158. snowflake/ml/modeling/neighbors/kernel_density.py +195 -123
  159. snowflake/ml/modeling/neighbors/local_outlier_factor.py +195 -123
  160. snowflake/ml/modeling/neighbors/nearest_centroid.py +195 -123
  161. snowflake/ml/modeling/neighbors/nearest_neighbors.py +195 -123
  162. snowflake/ml/modeling/neighbors/neighborhood_components_analysis.py +195 -123
  163. snowflake/ml/modeling/neighbors/radius_neighbors_classifier.py +195 -123
  164. snowflake/ml/modeling/neighbors/radius_neighbors_regressor.py +195 -123
  165. snowflake/ml/modeling/neural_network/bernoulli_rbm.py +195 -123
  166. snowflake/ml/modeling/neural_network/mlp_classifier.py +195 -123
  167. snowflake/ml/modeling/neural_network/mlp_regressor.py +195 -123
  168. snowflake/ml/modeling/pipeline/pipeline.py +4 -4
  169. snowflake/ml/modeling/preprocessing/binarizer.py +1 -5
  170. snowflake/ml/modeling/preprocessing/k_bins_discretizer.py +1 -5
  171. snowflake/ml/modeling/preprocessing/label_encoder.py +1 -5
  172. snowflake/ml/modeling/preprocessing/max_abs_scaler.py +1 -5
  173. snowflake/ml/modeling/preprocessing/min_max_scaler.py +10 -12
  174. snowflake/ml/modeling/preprocessing/normalizer.py +1 -5
  175. snowflake/ml/modeling/preprocessing/one_hot_encoder.py +1 -5
  176. snowflake/ml/modeling/preprocessing/ordinal_encoder.py +1 -5
  177. snowflake/ml/modeling/preprocessing/polynomial_features.py +195 -123
  178. snowflake/ml/modeling/preprocessing/robust_scaler.py +1 -5
  179. snowflake/ml/modeling/preprocessing/standard_scaler.py +11 -11
  180. snowflake/ml/modeling/semi_supervised/label_propagation.py +195 -123
  181. snowflake/ml/modeling/semi_supervised/label_spreading.py +195 -123
  182. snowflake/ml/modeling/svm/linear_svc.py +195 -123
  183. snowflake/ml/modeling/svm/linear_svr.py +195 -123
  184. snowflake/ml/modeling/svm/nu_svc.py +195 -123
  185. snowflake/ml/modeling/svm/nu_svr.py +195 -123
  186. snowflake/ml/modeling/svm/svc.py +195 -123
  187. snowflake/ml/modeling/svm/svr.py +195 -123
  188. snowflake/ml/modeling/tree/decision_tree_classifier.py +195 -123
  189. snowflake/ml/modeling/tree/decision_tree_regressor.py +195 -123
  190. snowflake/ml/modeling/tree/extra_tree_classifier.py +195 -123
  191. snowflake/ml/modeling/tree/extra_tree_regressor.py +195 -123
  192. snowflake/ml/modeling/xgboost/xgb_classifier.py +195 -123
  193. snowflake/ml/modeling/xgboost/xgb_regressor.py +195 -123
  194. snowflake/ml/modeling/xgboost/xgbrf_classifier.py +195 -123
  195. snowflake/ml/modeling/xgboost/xgbrf_regressor.py +195 -123
  196. snowflake/ml/registry/registry.py +1 -1
  197. snowflake/ml/version.py +1 -1
  198. {snowflake_ml_python-1.4.0.dist-info → snowflake_ml_python-1.4.1.dist-info}/METADATA +68 -57
  199. {snowflake_ml_python-1.4.0.dist-info → snowflake_ml_python-1.4.1.dist-info}/RECORD +202 -200
  200. snowflake/ml/model/_model_composer/model_runtime/model_runtime.py +0 -97
  201. {snowflake_ml_python-1.4.0.dist-info → snowflake_ml_python-1.4.1.dist-info}/LICENSE.txt +0 -0
  202. {snowflake_ml_python-1.4.0.dist-info → snowflake_ml_python-1.4.1.dist-info}/WHEEL +0 -0
  203. {snowflake_ml_python-1.4.0.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
@@ -247,12 +246,7 @@ class Nystroem(BaseTransformer):
247
246
  )
248
247
  return selected_cols
249
248
 
250
- @telemetry.send_api_usage_telemetry(
251
- project=_PROJECT,
252
- subproject=_SUBPROJECT,
253
- custom_tags=dict([("autogen", True)]),
254
- )
255
- def fit(self, dataset: Union[DataFrame, pd.DataFrame]) -> "Nystroem":
249
+ def _fit(self, dataset: Union[DataFrame, pd.DataFrame]) -> "Nystroem":
256
250
  """Fit estimator to data
257
251
  For more details on this function, see [sklearn.kernel_approximation.Nystroem.fit]
258
252
  (https://scikit-learn.org/stable/modules/generated/sklearn.kernel_approximation.Nystroem.html#sklearn.kernel_approximation.Nystroem.fit)
@@ -279,12 +273,14 @@ class Nystroem(BaseTransformer):
279
273
 
280
274
  self._snowpark_cols = dataset.select(self.input_cols).columns
281
275
 
282
- # If we are already in a stored procedure, no need to kick off another one.
276
+ # If we are already in a stored procedure, no need to kick off another one.
283
277
  if SNOWML_SPROC_ENV in os.environ:
284
278
  statement_params = telemetry.get_function_usage_statement_params(
285
279
  project=_PROJECT,
286
280
  subproject=_SUBPROJECT,
287
- function_name=telemetry.get_statement_params_full_func_name(inspect.currentframe(), Nystroem.__class__.__name__),
281
+ function_name=telemetry.get_statement_params_full_func_name(
282
+ inspect.currentframe(), Nystroem.__class__.__name__
283
+ ),
288
284
  api_calls=[Session.call],
289
285
  custom_tags=dict([("autogen", True)]) if self._autogenerated else None,
290
286
  )
@@ -305,7 +301,7 @@ class Nystroem(BaseTransformer):
305
301
  )
306
302
  self._sklearn_object = model_trainer.train()
307
303
  self._is_fitted = True
308
- self._get_model_signatures(dataset)
304
+ self._generate_model_signatures(dataset)
309
305
  return self
310
306
 
311
307
  def _batch_inference_validate_snowpark(
@@ -379,7 +375,9 @@ class Nystroem(BaseTransformer):
379
375
  # when it is classifier, infer the datatype from label columns
380
376
  if expected_type_inferred == "" and 'predict' in self.model_signatures:
381
377
  # Batch inference takes a single expected output column type. Use the first columns type for now.
382
- label_cols_signatures = [row for row in self.model_signatures['predict'].outputs if row.name in self.output_cols]
378
+ label_cols_signatures = [
379
+ row for row in self.model_signatures['predict'].outputs if row.name in self.output_cols
380
+ ]
383
381
  if len(label_cols_signatures) == 0:
384
382
  error_str = f"Output columns {self.output_cols} do not match model signatures {self.model_signatures['predict'].outputs}."
385
383
  raise exceptions.SnowflakeMLException(
@@ -387,25 +385,22 @@ class Nystroem(BaseTransformer):
387
385
  original_exception=ValueError(error_str),
388
386
  )
389
387
 
390
- expected_type_inferred = convert_sp_to_sf_type(
391
- label_cols_signatures[0].as_snowpark_type()
392
- )
388
+ expected_type_inferred = convert_sp_to_sf_type(label_cols_signatures[0].as_snowpark_type())
393
389
 
394
390
  self._deps = self._batch_inference_validate_snowpark(dataset=dataset, inference_method=inference_method)
395
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
391
+ assert isinstance(
392
+ dataset._session, Session
393
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
396
394
 
397
395
  transform_kwargs = dict(
398
- session = dataset._session,
399
- dependencies = self._deps,
400
- drop_input_cols = self._drop_input_cols,
401
- expected_output_cols_type = expected_type_inferred,
396
+ session=dataset._session,
397
+ dependencies=self._deps,
398
+ drop_input_cols=self._drop_input_cols,
399
+ expected_output_cols_type=expected_type_inferred,
402
400
  )
403
401
 
404
402
  elif isinstance(dataset, pd.DataFrame):
405
- transform_kwargs = dict(
406
- snowpark_input_cols = self._snowpark_cols,
407
- drop_input_cols = self._drop_input_cols
408
- )
403
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
409
404
 
410
405
  transform_handlers = ModelTransformerBuilder.build(
411
406
  dataset=dataset,
@@ -447,7 +442,7 @@ class Nystroem(BaseTransformer):
447
442
  Transformed dataset.
448
443
  """
449
444
  super()._check_dataset_type(dataset)
450
- inference_method="transform"
445
+ inference_method = "transform"
451
446
 
452
447
  # This dictionary contains optional kwargs for batch inference. These kwargs
453
448
  # are specific to the type of dataset used.
@@ -484,17 +479,14 @@ class Nystroem(BaseTransformer):
484
479
  assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
485
480
 
486
481
  transform_kwargs = dict(
487
- session = dataset._session,
488
- dependencies = self._deps,
489
- drop_input_cols = self._drop_input_cols,
490
- expected_output_cols_type = expected_dtype,
482
+ session=dataset._session,
483
+ dependencies=self._deps,
484
+ drop_input_cols=self._drop_input_cols,
485
+ expected_output_cols_type=expected_dtype,
491
486
  )
492
487
 
493
488
  elif isinstance(dataset, pd.DataFrame):
494
- transform_kwargs = dict(
495
- snowpark_input_cols = self._snowpark_cols,
496
- drop_input_cols = self._drop_input_cols
497
- )
489
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
498
490
 
499
491
  transform_handlers = ModelTransformerBuilder.build(
500
492
  dataset=dataset,
@@ -513,7 +505,11 @@ class Nystroem(BaseTransformer):
513
505
  return output_df
514
506
 
515
507
  @available_if(original_estimator_has_callable("fit_predict")) # type: ignore[misc]
516
- def fit_predict(self, dataset: Union[DataFrame, pd.DataFrame], output_cols_prefix: str = "fit_predict_",) -> Union[DataFrame, pd.DataFrame]:
508
+ def fit_predict(
509
+ self,
510
+ dataset: Union[DataFrame, pd.DataFrame],
511
+ output_cols_prefix: str = "fit_predict_",
512
+ ) -> Union[DataFrame, pd.DataFrame]:
517
513
  """ Method not supported for this class.
518
514
 
519
515
 
@@ -538,7 +534,9 @@ class Nystroem(BaseTransformer):
538
534
  )
539
535
  output_result, fitted_estimator = model_trainer.train_fit_predict(
540
536
  drop_input_cols=self._drop_input_cols,
541
- expected_output_cols_list=self.output_cols if self.output_cols else self._get_output_column_names(output_cols_prefix),
537
+ expected_output_cols_list=(
538
+ self.output_cols if self.output_cols else self._get_output_column_names(output_cols_prefix)
539
+ ),
542
540
  )
543
541
  self._sklearn_object = fitted_estimator
544
542
  self._is_fitted = True
@@ -555,6 +553,62 @@ class Nystroem(BaseTransformer):
555
553
  assert self._sklearn_object is not None
556
554
  return self._sklearn_object.embedding_
557
555
 
556
+
557
+ def _get_output_column_names(self, output_cols_prefix: str, output_cols: Optional[List[str]] = None) -> List[str]:
558
+ """ Returns the list of output columns for predict_proba(), decision_function(), etc.. functions.
559
+ Returns a list with output_cols_prefix as the only element if the estimator is not a classifier.
560
+ """
561
+ output_cols_prefix = identifier.resolve_identifier(output_cols_prefix)
562
+ # The following condition is introduced for kneighbors methods, and not used in other methods
563
+ if output_cols:
564
+ output_cols = [
565
+ identifier.concat_names([output_cols_prefix, identifier.resolve_identifier(c)])
566
+ for c in output_cols
567
+ ]
568
+ elif getattr(self._sklearn_object, "classes_", None) is None:
569
+ output_cols = [output_cols_prefix]
570
+ elif self._sklearn_object is not None:
571
+ classes = self._sklearn_object.classes_
572
+ if isinstance(classes, numpy.ndarray):
573
+ output_cols = [f'{output_cols_prefix}{str(c)}' for c in classes.tolist()]
574
+ elif isinstance(classes, list) and len(classes) > 0 and isinstance(classes[0], numpy.ndarray):
575
+ # If the estimator is a multioutput estimator, classes_ will be a list of ndarrays.
576
+ output_cols = []
577
+ for i, cl in enumerate(classes):
578
+ # For binary classification, there is only one output column for each class
579
+ # ndarray as the two classes are complementary.
580
+ if len(cl) == 2:
581
+ output_cols.append(f'{output_cols_prefix}{i}_{cl[0]}')
582
+ else:
583
+ output_cols.extend([
584
+ f'{output_cols_prefix}{i}_{c}' for c in cl.tolist()
585
+ ])
586
+ else:
587
+ output_cols = []
588
+
589
+ # Make sure column names are valid snowflake identifiers.
590
+ assert output_cols is not None # Make MyPy happy
591
+ rv = [identifier.rename_to_valid_snowflake_identifier(c) for c in output_cols]
592
+
593
+ return rv
594
+
595
+ def _align_expected_output_names(
596
+ self, method: str, dataset: DataFrame, expected_output_cols_list: List[str], output_cols_prefix: str
597
+ ) -> List[str]:
598
+ # in case the inferred output column names dimension is different
599
+ # we use one line of snowpark dataframe and put it into sklearn estimator using pandas
600
+ output_df_pd = getattr(self, method)(dataset.limit(1).to_pandas(), output_cols_prefix)
601
+ output_df_columns = list(output_df_pd.columns)
602
+ output_df_columns_set: Set[str] = set(output_df_columns) - set(dataset.columns)
603
+ if self.sample_weight_col:
604
+ output_df_columns_set -= set(self.sample_weight_col)
605
+ # if the dimension of inferred output column names is correct; use it
606
+ if len(expected_output_cols_list) == len(output_df_columns_set):
607
+ return expected_output_cols_list
608
+ # otherwise, use the sklearn estimator's output
609
+ else:
610
+ return sorted(list(output_df_columns_set), key=lambda x: output_df_columns.index(x))
611
+
558
612
  @available_if(original_estimator_has_callable("predict_proba")) # type: ignore[misc]
559
613
  @telemetry.send_api_usage_telemetry(
560
614
  project=_PROJECT,
@@ -585,24 +639,28 @@ class Nystroem(BaseTransformer):
585
639
  # are specific to the type of dataset used.
586
640
  transform_kwargs: BatchInferenceKwargsTypedDict = dict()
587
641
 
642
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
643
+
588
644
  if isinstance(dataset, DataFrame):
589
645
  self._deps = self._batch_inference_validate_snowpark(
590
646
  dataset=dataset,
591
647
  inference_method=inference_method,
592
648
  )
593
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
649
+ assert isinstance(
650
+ dataset._session, Session
651
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
594
652
  transform_kwargs = dict(
595
653
  session=dataset._session,
596
654
  dependencies=self._deps,
597
- drop_input_cols = self._drop_input_cols,
655
+ drop_input_cols=self._drop_input_cols,
598
656
  expected_output_cols_type="float",
599
657
  )
658
+ expected_output_cols = self._align_expected_output_names(
659
+ inference_method, dataset, expected_output_cols, output_cols_prefix
660
+ )
600
661
 
601
662
  elif isinstance(dataset, pd.DataFrame):
602
- transform_kwargs = dict(
603
- snowpark_input_cols = self._snowpark_cols,
604
- drop_input_cols = self._drop_input_cols
605
- )
663
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
606
664
 
607
665
  transform_handlers = ModelTransformerBuilder.build(
608
666
  dataset=dataset,
@@ -614,7 +672,7 @@ class Nystroem(BaseTransformer):
614
672
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
615
673
  inference_method=inference_method,
616
674
  input_cols=self.input_cols,
617
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
675
+ expected_output_cols=expected_output_cols,
618
676
  **transform_kwargs
619
677
  )
620
678
  return output_df
@@ -644,7 +702,8 @@ class Nystroem(BaseTransformer):
644
702
  Output dataset with log probability of the sample for each class in the model.
645
703
  """
646
704
  super()._check_dataset_type(dataset)
647
- inference_method="predict_log_proba"
705
+ inference_method = "predict_log_proba"
706
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
648
707
 
649
708
  # This dictionary contains optional kwargs for batch inference. These kwargs
650
709
  # are specific to the type of dataset used.
@@ -655,18 +714,20 @@ class Nystroem(BaseTransformer):
655
714
  dataset=dataset,
656
715
  inference_method=inference_method,
657
716
  )
658
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
717
+ assert isinstance(
718
+ dataset._session, Session
719
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
659
720
  transform_kwargs = dict(
660
721
  session=dataset._session,
661
722
  dependencies=self._deps,
662
- drop_input_cols = self._drop_input_cols,
723
+ drop_input_cols=self._drop_input_cols,
663
724
  expected_output_cols_type="float",
664
725
  )
726
+ expected_output_cols = self._align_expected_output_names(
727
+ inference_method, dataset, expected_output_cols, output_cols_prefix
728
+ )
665
729
  elif isinstance(dataset, pd.DataFrame):
666
- transform_kwargs = dict(
667
- snowpark_input_cols = self._snowpark_cols,
668
- drop_input_cols = self._drop_input_cols
669
- )
730
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
670
731
 
671
732
  transform_handlers = ModelTransformerBuilder.build(
672
733
  dataset=dataset,
@@ -679,7 +740,7 @@ class Nystroem(BaseTransformer):
679
740
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
680
741
  inference_method=inference_method,
681
742
  input_cols=self.input_cols,
682
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
743
+ expected_output_cols=expected_output_cols,
683
744
  **transform_kwargs
684
745
  )
685
746
  return output_df
@@ -705,30 +766,34 @@ class Nystroem(BaseTransformer):
705
766
  Output dataset with results of the decision function for the samples in input dataset.
706
767
  """
707
768
  super()._check_dataset_type(dataset)
708
- inference_method="decision_function"
769
+ inference_method = "decision_function"
709
770
 
710
771
  # This dictionary contains optional kwargs for batch inference. These kwargs
711
772
  # are specific to the type of dataset used.
712
773
  transform_kwargs: BatchInferenceKwargsTypedDict = dict()
713
774
 
775
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
776
+
714
777
  if isinstance(dataset, DataFrame):
715
778
  self._deps = self._batch_inference_validate_snowpark(
716
779
  dataset=dataset,
717
780
  inference_method=inference_method,
718
781
  )
719
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
782
+ assert isinstance(
783
+ dataset._session, Session
784
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
720
785
  transform_kwargs = dict(
721
786
  session=dataset._session,
722
787
  dependencies=self._deps,
723
- drop_input_cols = self._drop_input_cols,
788
+ drop_input_cols=self._drop_input_cols,
724
789
  expected_output_cols_type="float",
725
790
  )
791
+ expected_output_cols = self._align_expected_output_names(
792
+ inference_method, dataset, expected_output_cols, output_cols_prefix
793
+ )
726
794
 
727
795
  elif isinstance(dataset, pd.DataFrame):
728
- transform_kwargs = dict(
729
- snowpark_input_cols = self._snowpark_cols,
730
- drop_input_cols = self._drop_input_cols
731
- )
796
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
732
797
 
733
798
  transform_handlers = ModelTransformerBuilder.build(
734
799
  dataset=dataset,
@@ -741,7 +806,7 @@ class Nystroem(BaseTransformer):
741
806
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
742
807
  inference_method=inference_method,
743
808
  input_cols=self.input_cols,
744
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
809
+ expected_output_cols=expected_output_cols,
745
810
  **transform_kwargs
746
811
  )
747
812
  return output_df
@@ -770,12 +835,14 @@ class Nystroem(BaseTransformer):
770
835
  Output dataset with probability of the sample for each class in the model.
771
836
  """
772
837
  super()._check_dataset_type(dataset)
773
- inference_method="score_samples"
838
+ inference_method = "score_samples"
774
839
 
775
840
  # This dictionary contains optional kwargs for batch inference. These kwargs
776
841
  # are specific to the type of dataset used.
777
842
  transform_kwargs: BatchInferenceKwargsTypedDict = dict()
778
843
 
844
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
845
+
779
846
  if isinstance(dataset, DataFrame):
780
847
  self._deps = self._batch_inference_validate_snowpark(
781
848
  dataset=dataset,
@@ -788,6 +855,9 @@ class Nystroem(BaseTransformer):
788
855
  drop_input_cols = self._drop_input_cols,
789
856
  expected_output_cols_type="float",
790
857
  )
858
+ expected_output_cols = self._align_expected_output_names(
859
+ inference_method, dataset, expected_output_cols, output_cols_prefix
860
+ )
791
861
 
792
862
  elif isinstance(dataset, pd.DataFrame):
793
863
  transform_kwargs = dict(
@@ -806,7 +876,7 @@ class Nystroem(BaseTransformer):
806
876
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
807
877
  inference_method=inference_method,
808
878
  input_cols=self.input_cols,
809
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
879
+ expected_output_cols=expected_output_cols,
810
880
  **transform_kwargs
811
881
  )
812
882
  return output_df
@@ -951,50 +1021,84 @@ class Nystroem(BaseTransformer):
951
1021
  )
952
1022
  return output_df
953
1023
 
1024
+
1025
+
1026
+ def to_sklearn(self) -> Any:
1027
+ """Get sklearn.kernel_approximation.Nystroem object.
1028
+ """
1029
+ if self._sklearn_object is None:
1030
+ self._sklearn_object = self._create_sklearn_object()
1031
+ return self._sklearn_object
1032
+
1033
+ def to_xgboost(self) -> Any:
1034
+ raise exceptions.SnowflakeMLException(
1035
+ error_code=error_codes.METHOD_NOT_ALLOWED,
1036
+ original_exception=AttributeError(
1037
+ modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1038
+ "to_xgboost()",
1039
+ "to_sklearn()"
1040
+ )
1041
+ ),
1042
+ )
1043
+
1044
+ def to_lightgbm(self) -> Any:
1045
+ raise exceptions.SnowflakeMLException(
1046
+ error_code=error_codes.METHOD_NOT_ALLOWED,
1047
+ original_exception=AttributeError(
1048
+ modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1049
+ "to_lightgbm()",
1050
+ "to_sklearn()"
1051
+ )
1052
+ ),
1053
+ )
954
1054
 
955
- def _get_model_signatures(self, dataset: Union[DataFrame, pd.DataFrame]) -> None:
1055
+ def _get_dependencies(self) -> List[str]:
1056
+ return self._deps
1057
+
1058
+
1059
+ def _generate_model_signatures(self, dataset: Union[DataFrame, pd.DataFrame]) -> None:
956
1060
  self._model_signature_dict = dict()
957
1061
 
958
1062
  PROB_FUNCTIONS = ["predict_log_proba", "predict_proba", "decision_function"]
959
1063
 
960
- inputs = list(_infer_signature(dataset[self.input_cols], "input"))
1064
+ inputs = list(_infer_signature(dataset[self.input_cols], "input", use_snowflake_identifiers=True))
961
1065
  outputs: List[BaseFeatureSpec] = []
962
1066
  if hasattr(self, "predict"):
963
1067
  # keep mypy happy
964
- assert self._sklearn_object is not None and hasattr(self._sklearn_object, "_estimator_type")
1068
+ assert self._sklearn_object is not None and hasattr(self._sklearn_object, "_estimator_type")
965
1069
  # For classifier, the type of predict is the same as the type of label
966
- if self._sklearn_object._estimator_type == 'classifier':
967
- # label columns is the desired type for output
1070
+ if self._sklearn_object._estimator_type == "classifier":
1071
+ # label columns is the desired type for output
968
1072
  outputs = list(_infer_signature(dataset[self.label_cols], "output", use_snowflake_identifiers=True))
969
1073
  # rename the output columns
970
1074
  outputs = list(model_signature_utils.rename_features(outputs, self.output_cols))
971
- self._model_signature_dict["predict"] = ModelSignature(inputs,
972
- ([] if self._drop_input_cols else inputs)
973
- + outputs)
1075
+ self._model_signature_dict["predict"] = ModelSignature(
1076
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1077
+ )
974
1078
  # For mixture models that use the density mixin, `predict` returns the argmax of the log prob.
975
1079
  # For outlier models, returns -1 for outliers and 1 for inliers.
976
- # Clusterer returns int64 cluster labels.
1080
+ # Clusterer returns int64 cluster labels.
977
1081
  elif self._sklearn_object._estimator_type in ["DensityEstimator", "clusterer", "outlier_detector"]:
978
1082
  outputs = [FeatureSpec(dtype=DataType.INT64, name=c) for c in self.output_cols]
979
- self._model_signature_dict["predict"] = ModelSignature(inputs,
980
- ([] if self._drop_input_cols else inputs)
981
- + outputs)
982
-
1083
+ self._model_signature_dict["predict"] = ModelSignature(
1084
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1085
+ )
1086
+
983
1087
  # For regressor, the type of predict is float64
984
- elif self._sklearn_object._estimator_type == 'regressor':
1088
+ elif self._sklearn_object._estimator_type == "regressor":
985
1089
  outputs = [FeatureSpec(dtype=DataType.DOUBLE, name=c) for c in self.output_cols]
986
- self._model_signature_dict["predict"] = ModelSignature(inputs,
987
- ([] if self._drop_input_cols else inputs)
988
- + outputs)
989
-
1090
+ self._model_signature_dict["predict"] = ModelSignature(
1091
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1092
+ )
1093
+
990
1094
  for prob_func in PROB_FUNCTIONS:
991
1095
  if hasattr(self, prob_func):
992
1096
  output_cols_prefix: str = f"{prob_func}_"
993
1097
  output_column_names = self._get_output_column_names(output_cols_prefix)
994
1098
  outputs = [FeatureSpec(dtype=DataType.DOUBLE, name=c) for c in output_column_names]
995
- self._model_signature_dict[prob_func] = ModelSignature(inputs,
996
- ([] if self._drop_input_cols else inputs)
997
- + outputs)
1099
+ self._model_signature_dict[prob_func] = ModelSignature(
1100
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1101
+ )
998
1102
 
999
1103
  # Output signature names may still need to be renamed, since they were not created with `_infer_signature`.
1000
1104
  items = list(self._model_signature_dict.items())
@@ -1007,10 +1111,10 @@ class Nystroem(BaseTransformer):
1007
1111
  """Returns model signature of current class.
1008
1112
 
1009
1113
  Raises:
1010
- exceptions.SnowflakeMLException: If estimator is not fitted, then model signature cannot be inferred
1114
+ SnowflakeMLException: If estimator is not fitted, then model signature cannot be inferred
1011
1115
 
1012
1116
  Returns:
1013
- Dict[str, ModelSignature]: each method and its input output signature
1117
+ Dict with each method and its input output signature
1014
1118
  """
1015
1119
  if self._model_signature_dict is None:
1016
1120
  raise exceptions.SnowflakeMLException(
@@ -1018,35 +1122,3 @@ class Nystroem(BaseTransformer):
1018
1122
  original_exception=RuntimeError("Estimator not fitted before accessing property model_signatures!"),
1019
1123
  )
1020
1124
  return self._model_signature_dict
1021
-
1022
- def to_sklearn(self) -> Any:
1023
- """Get sklearn.kernel_approximation.Nystroem object.
1024
- """
1025
- if self._sklearn_object is None:
1026
- self._sklearn_object = self._create_sklearn_object()
1027
- return self._sklearn_object
1028
-
1029
- def to_xgboost(self) -> Any:
1030
- raise exceptions.SnowflakeMLException(
1031
- error_code=error_codes.METHOD_NOT_ALLOWED,
1032
- original_exception=AttributeError(
1033
- modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1034
- "to_xgboost()",
1035
- "to_sklearn()"
1036
- )
1037
- ),
1038
- )
1039
-
1040
- def to_lightgbm(self) -> Any:
1041
- raise exceptions.SnowflakeMLException(
1042
- error_code=error_codes.METHOD_NOT_ALLOWED,
1043
- original_exception=AttributeError(
1044
- modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1045
- "to_lightgbm()",
1046
- "to_sklearn()"
1047
- )
1048
- ),
1049
- )
1050
-
1051
- def _get_dependencies(self) -> List[str]:
1052
- return self._deps