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
@@ -276,12 +275,7 @@ class GraphicalLassoCV(BaseTransformer):
276
275
  )
277
276
  return selected_cols
278
277
 
279
- @telemetry.send_api_usage_telemetry(
280
- project=_PROJECT,
281
- subproject=_SUBPROJECT,
282
- custom_tags=dict([("autogen", True)]),
283
- )
284
- def fit(self, dataset: Union[DataFrame, pd.DataFrame]) -> "GraphicalLassoCV":
278
+ def _fit(self, dataset: Union[DataFrame, pd.DataFrame]) -> "GraphicalLassoCV":
285
279
  """Fit the GraphicalLasso covariance model to X
286
280
  For more details on this function, see [sklearn.covariance.GraphicalLassoCV.fit]
287
281
  (https://scikit-learn.org/stable/modules/generated/sklearn.covariance.GraphicalLassoCV.html#sklearn.covariance.GraphicalLassoCV.fit)
@@ -308,12 +302,14 @@ class GraphicalLassoCV(BaseTransformer):
308
302
 
309
303
  self._snowpark_cols = dataset.select(self.input_cols).columns
310
304
 
311
- # If we are already in a stored procedure, no need to kick off another one.
305
+ # If we are already in a stored procedure, no need to kick off another one.
312
306
  if SNOWML_SPROC_ENV in os.environ:
313
307
  statement_params = telemetry.get_function_usage_statement_params(
314
308
  project=_PROJECT,
315
309
  subproject=_SUBPROJECT,
316
- function_name=telemetry.get_statement_params_full_func_name(inspect.currentframe(), GraphicalLassoCV.__class__.__name__),
310
+ function_name=telemetry.get_statement_params_full_func_name(
311
+ inspect.currentframe(), GraphicalLassoCV.__class__.__name__
312
+ ),
317
313
  api_calls=[Session.call],
318
314
  custom_tags=dict([("autogen", True)]) if self._autogenerated else None,
319
315
  )
@@ -334,7 +330,7 @@ class GraphicalLassoCV(BaseTransformer):
334
330
  )
335
331
  self._sklearn_object = model_trainer.train()
336
332
  self._is_fitted = True
337
- self._get_model_signatures(dataset)
333
+ self._generate_model_signatures(dataset)
338
334
  return self
339
335
 
340
336
  def _batch_inference_validate_snowpark(
@@ -408,7 +404,9 @@ class GraphicalLassoCV(BaseTransformer):
408
404
  # when it is classifier, infer the datatype from label columns
409
405
  if expected_type_inferred == "" and 'predict' in self.model_signatures:
410
406
  # Batch inference takes a single expected output column type. Use the first columns type for now.
411
- label_cols_signatures = [row for row in self.model_signatures['predict'].outputs if row.name in self.output_cols]
407
+ label_cols_signatures = [
408
+ row for row in self.model_signatures['predict'].outputs if row.name in self.output_cols
409
+ ]
412
410
  if len(label_cols_signatures) == 0:
413
411
  error_str = f"Output columns {self.output_cols} do not match model signatures {self.model_signatures['predict'].outputs}."
414
412
  raise exceptions.SnowflakeMLException(
@@ -416,25 +414,22 @@ class GraphicalLassoCV(BaseTransformer):
416
414
  original_exception=ValueError(error_str),
417
415
  )
418
416
 
419
- expected_type_inferred = convert_sp_to_sf_type(
420
- label_cols_signatures[0].as_snowpark_type()
421
- )
417
+ expected_type_inferred = convert_sp_to_sf_type(label_cols_signatures[0].as_snowpark_type())
422
418
 
423
419
  self._deps = self._batch_inference_validate_snowpark(dataset=dataset, inference_method=inference_method)
424
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
420
+ assert isinstance(
421
+ dataset._session, Session
422
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
425
423
 
426
424
  transform_kwargs = dict(
427
- session = dataset._session,
428
- dependencies = self._deps,
429
- drop_input_cols = self._drop_input_cols,
430
- expected_output_cols_type = expected_type_inferred,
425
+ session=dataset._session,
426
+ dependencies=self._deps,
427
+ drop_input_cols=self._drop_input_cols,
428
+ expected_output_cols_type=expected_type_inferred,
431
429
  )
432
430
 
433
431
  elif isinstance(dataset, pd.DataFrame):
434
- transform_kwargs = dict(
435
- snowpark_input_cols = self._snowpark_cols,
436
- drop_input_cols = self._drop_input_cols
437
- )
432
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
438
433
 
439
434
  transform_handlers = ModelTransformerBuilder.build(
440
435
  dataset=dataset,
@@ -474,7 +469,7 @@ class GraphicalLassoCV(BaseTransformer):
474
469
  Transformed dataset.
475
470
  """
476
471
  super()._check_dataset_type(dataset)
477
- inference_method="transform"
472
+ inference_method = "transform"
478
473
 
479
474
  # This dictionary contains optional kwargs for batch inference. These kwargs
480
475
  # are specific to the type of dataset used.
@@ -511,17 +506,14 @@ class GraphicalLassoCV(BaseTransformer):
511
506
  assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
512
507
 
513
508
  transform_kwargs = dict(
514
- session = dataset._session,
515
- dependencies = self._deps,
516
- drop_input_cols = self._drop_input_cols,
517
- expected_output_cols_type = expected_dtype,
509
+ session=dataset._session,
510
+ dependencies=self._deps,
511
+ drop_input_cols=self._drop_input_cols,
512
+ expected_output_cols_type=expected_dtype,
518
513
  )
519
514
 
520
515
  elif isinstance(dataset, pd.DataFrame):
521
- transform_kwargs = dict(
522
- snowpark_input_cols = self._snowpark_cols,
523
- drop_input_cols = self._drop_input_cols
524
- )
516
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
525
517
 
526
518
  transform_handlers = ModelTransformerBuilder.build(
527
519
  dataset=dataset,
@@ -540,7 +532,11 @@ class GraphicalLassoCV(BaseTransformer):
540
532
  return output_df
541
533
 
542
534
  @available_if(original_estimator_has_callable("fit_predict")) # type: ignore[misc]
543
- def fit_predict(self, dataset: Union[DataFrame, pd.DataFrame], output_cols_prefix: str = "fit_predict_",) -> Union[DataFrame, pd.DataFrame]:
535
+ def fit_predict(
536
+ self,
537
+ dataset: Union[DataFrame, pd.DataFrame],
538
+ output_cols_prefix: str = "fit_predict_",
539
+ ) -> Union[DataFrame, pd.DataFrame]:
544
540
  """ Method not supported for this class.
545
541
 
546
542
 
@@ -565,7 +561,9 @@ class GraphicalLassoCV(BaseTransformer):
565
561
  )
566
562
  output_result, fitted_estimator = model_trainer.train_fit_predict(
567
563
  drop_input_cols=self._drop_input_cols,
568
- expected_output_cols_list=self.output_cols if self.output_cols else self._get_output_column_names(output_cols_prefix),
564
+ expected_output_cols_list=(
565
+ self.output_cols if self.output_cols else self._get_output_column_names(output_cols_prefix)
566
+ ),
569
567
  )
570
568
  self._sklearn_object = fitted_estimator
571
569
  self._is_fitted = True
@@ -582,6 +580,62 @@ class GraphicalLassoCV(BaseTransformer):
582
580
  assert self._sklearn_object is not None
583
581
  return self._sklearn_object.embedding_
584
582
 
583
+
584
+ def _get_output_column_names(self, output_cols_prefix: str, output_cols: Optional[List[str]] = None) -> List[str]:
585
+ """ Returns the list of output columns for predict_proba(), decision_function(), etc.. functions.
586
+ Returns a list with output_cols_prefix as the only element if the estimator is not a classifier.
587
+ """
588
+ output_cols_prefix = identifier.resolve_identifier(output_cols_prefix)
589
+ # The following condition is introduced for kneighbors methods, and not used in other methods
590
+ if output_cols:
591
+ output_cols = [
592
+ identifier.concat_names([output_cols_prefix, identifier.resolve_identifier(c)])
593
+ for c in output_cols
594
+ ]
595
+ elif getattr(self._sklearn_object, "classes_", None) is None:
596
+ output_cols = [output_cols_prefix]
597
+ elif self._sklearn_object is not None:
598
+ classes = self._sklearn_object.classes_
599
+ if isinstance(classes, numpy.ndarray):
600
+ output_cols = [f'{output_cols_prefix}{str(c)}' for c in classes.tolist()]
601
+ elif isinstance(classes, list) and len(classes) > 0 and isinstance(classes[0], numpy.ndarray):
602
+ # If the estimator is a multioutput estimator, classes_ will be a list of ndarrays.
603
+ output_cols = []
604
+ for i, cl in enumerate(classes):
605
+ # For binary classification, there is only one output column for each class
606
+ # ndarray as the two classes are complementary.
607
+ if len(cl) == 2:
608
+ output_cols.append(f'{output_cols_prefix}{i}_{cl[0]}')
609
+ else:
610
+ output_cols.extend([
611
+ f'{output_cols_prefix}{i}_{c}' for c in cl.tolist()
612
+ ])
613
+ else:
614
+ output_cols = []
615
+
616
+ # Make sure column names are valid snowflake identifiers.
617
+ assert output_cols is not None # Make MyPy happy
618
+ rv = [identifier.rename_to_valid_snowflake_identifier(c) for c in output_cols]
619
+
620
+ return rv
621
+
622
+ def _align_expected_output_names(
623
+ self, method: str, dataset: DataFrame, expected_output_cols_list: List[str], output_cols_prefix: str
624
+ ) -> List[str]:
625
+ # in case the inferred output column names dimension is different
626
+ # we use one line of snowpark dataframe and put it into sklearn estimator using pandas
627
+ output_df_pd = getattr(self, method)(dataset.limit(1).to_pandas(), output_cols_prefix)
628
+ output_df_columns = list(output_df_pd.columns)
629
+ output_df_columns_set: Set[str] = set(output_df_columns) - set(dataset.columns)
630
+ if self.sample_weight_col:
631
+ output_df_columns_set -= set(self.sample_weight_col)
632
+ # if the dimension of inferred output column names is correct; use it
633
+ if len(expected_output_cols_list) == len(output_df_columns_set):
634
+ return expected_output_cols_list
635
+ # otherwise, use the sklearn estimator's output
636
+ else:
637
+ return sorted(list(output_df_columns_set), key=lambda x: output_df_columns.index(x))
638
+
585
639
  @available_if(original_estimator_has_callable("predict_proba")) # type: ignore[misc]
586
640
  @telemetry.send_api_usage_telemetry(
587
641
  project=_PROJECT,
@@ -612,24 +666,28 @@ class GraphicalLassoCV(BaseTransformer):
612
666
  # are specific to the type of dataset used.
613
667
  transform_kwargs: BatchInferenceKwargsTypedDict = dict()
614
668
 
669
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
670
+
615
671
  if isinstance(dataset, DataFrame):
616
672
  self._deps = self._batch_inference_validate_snowpark(
617
673
  dataset=dataset,
618
674
  inference_method=inference_method,
619
675
  )
620
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
676
+ assert isinstance(
677
+ dataset._session, Session
678
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
621
679
  transform_kwargs = dict(
622
680
  session=dataset._session,
623
681
  dependencies=self._deps,
624
- drop_input_cols = self._drop_input_cols,
682
+ drop_input_cols=self._drop_input_cols,
625
683
  expected_output_cols_type="float",
626
684
  )
685
+ expected_output_cols = self._align_expected_output_names(
686
+ inference_method, dataset, expected_output_cols, output_cols_prefix
687
+ )
627
688
 
628
689
  elif isinstance(dataset, pd.DataFrame):
629
- transform_kwargs = dict(
630
- snowpark_input_cols = self._snowpark_cols,
631
- drop_input_cols = self._drop_input_cols
632
- )
690
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
633
691
 
634
692
  transform_handlers = ModelTransformerBuilder.build(
635
693
  dataset=dataset,
@@ -641,7 +699,7 @@ class GraphicalLassoCV(BaseTransformer):
641
699
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
642
700
  inference_method=inference_method,
643
701
  input_cols=self.input_cols,
644
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
702
+ expected_output_cols=expected_output_cols,
645
703
  **transform_kwargs
646
704
  )
647
705
  return output_df
@@ -671,7 +729,8 @@ class GraphicalLassoCV(BaseTransformer):
671
729
  Output dataset with log probability of the sample for each class in the model.
672
730
  """
673
731
  super()._check_dataset_type(dataset)
674
- inference_method="predict_log_proba"
732
+ inference_method = "predict_log_proba"
733
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
675
734
 
676
735
  # This dictionary contains optional kwargs for batch inference. These kwargs
677
736
  # are specific to the type of dataset used.
@@ -682,18 +741,20 @@ class GraphicalLassoCV(BaseTransformer):
682
741
  dataset=dataset,
683
742
  inference_method=inference_method,
684
743
  )
685
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
744
+ assert isinstance(
745
+ dataset._session, Session
746
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
686
747
  transform_kwargs = dict(
687
748
  session=dataset._session,
688
749
  dependencies=self._deps,
689
- drop_input_cols = self._drop_input_cols,
750
+ drop_input_cols=self._drop_input_cols,
690
751
  expected_output_cols_type="float",
691
752
  )
753
+ expected_output_cols = self._align_expected_output_names(
754
+ inference_method, dataset, expected_output_cols, output_cols_prefix
755
+ )
692
756
  elif isinstance(dataset, pd.DataFrame):
693
- transform_kwargs = dict(
694
- snowpark_input_cols = self._snowpark_cols,
695
- drop_input_cols = self._drop_input_cols
696
- )
757
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
697
758
 
698
759
  transform_handlers = ModelTransformerBuilder.build(
699
760
  dataset=dataset,
@@ -706,7 +767,7 @@ class GraphicalLassoCV(BaseTransformer):
706
767
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
707
768
  inference_method=inference_method,
708
769
  input_cols=self.input_cols,
709
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
770
+ expected_output_cols=expected_output_cols,
710
771
  **transform_kwargs
711
772
  )
712
773
  return output_df
@@ -732,30 +793,34 @@ class GraphicalLassoCV(BaseTransformer):
732
793
  Output dataset with results of the decision function for the samples in input dataset.
733
794
  """
734
795
  super()._check_dataset_type(dataset)
735
- inference_method="decision_function"
796
+ inference_method = "decision_function"
736
797
 
737
798
  # This dictionary contains optional kwargs for batch inference. These kwargs
738
799
  # are specific to the type of dataset used.
739
800
  transform_kwargs: BatchInferenceKwargsTypedDict = dict()
740
801
 
802
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
803
+
741
804
  if isinstance(dataset, DataFrame):
742
805
  self._deps = self._batch_inference_validate_snowpark(
743
806
  dataset=dataset,
744
807
  inference_method=inference_method,
745
808
  )
746
- assert isinstance(dataset._session, Session) # mypy does not recognize the check in _batch_inference_validate_snowpark()
809
+ assert isinstance(
810
+ dataset._session, Session
811
+ ) # mypy does not recognize the check in _batch_inference_validate_snowpark()
747
812
  transform_kwargs = dict(
748
813
  session=dataset._session,
749
814
  dependencies=self._deps,
750
- drop_input_cols = self._drop_input_cols,
815
+ drop_input_cols=self._drop_input_cols,
751
816
  expected_output_cols_type="float",
752
817
  )
818
+ expected_output_cols = self._align_expected_output_names(
819
+ inference_method, dataset, expected_output_cols, output_cols_prefix
820
+ )
753
821
 
754
822
  elif isinstance(dataset, pd.DataFrame):
755
- transform_kwargs = dict(
756
- snowpark_input_cols = self._snowpark_cols,
757
- drop_input_cols = self._drop_input_cols
758
- )
823
+ transform_kwargs = dict(snowpark_input_cols=self._snowpark_cols, drop_input_cols=self._drop_input_cols)
759
824
 
760
825
  transform_handlers = ModelTransformerBuilder.build(
761
826
  dataset=dataset,
@@ -768,7 +833,7 @@ class GraphicalLassoCV(BaseTransformer):
768
833
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
769
834
  inference_method=inference_method,
770
835
  input_cols=self.input_cols,
771
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
836
+ expected_output_cols=expected_output_cols,
772
837
  **transform_kwargs
773
838
  )
774
839
  return output_df
@@ -797,12 +862,14 @@ class GraphicalLassoCV(BaseTransformer):
797
862
  Output dataset with probability of the sample for each class in the model.
798
863
  """
799
864
  super()._check_dataset_type(dataset)
800
- inference_method="score_samples"
865
+ inference_method = "score_samples"
801
866
 
802
867
  # This dictionary contains optional kwargs for batch inference. These kwargs
803
868
  # are specific to the type of dataset used.
804
869
  transform_kwargs: BatchInferenceKwargsTypedDict = dict()
805
870
 
871
+ expected_output_cols = self._get_output_column_names(output_cols_prefix)
872
+
806
873
  if isinstance(dataset, DataFrame):
807
874
  self._deps = self._batch_inference_validate_snowpark(
808
875
  dataset=dataset,
@@ -815,6 +882,9 @@ class GraphicalLassoCV(BaseTransformer):
815
882
  drop_input_cols = self._drop_input_cols,
816
883
  expected_output_cols_type="float",
817
884
  )
885
+ expected_output_cols = self._align_expected_output_names(
886
+ inference_method, dataset, expected_output_cols, output_cols_prefix
887
+ )
818
888
 
819
889
  elif isinstance(dataset, pd.DataFrame):
820
890
  transform_kwargs = dict(
@@ -833,7 +903,7 @@ class GraphicalLassoCV(BaseTransformer):
833
903
  output_df: DATAFRAME_TYPE = transform_handlers.batch_inference(
834
904
  inference_method=inference_method,
835
905
  input_cols=self.input_cols,
836
- expected_output_cols=self._get_output_column_names(output_cols_prefix),
906
+ expected_output_cols=expected_output_cols,
837
907
  **transform_kwargs
838
908
  )
839
909
  return output_df
@@ -980,50 +1050,84 @@ class GraphicalLassoCV(BaseTransformer):
980
1050
  )
981
1051
  return output_df
982
1052
 
1053
+
1054
+
1055
+ def to_sklearn(self) -> Any:
1056
+ """Get sklearn.covariance.GraphicalLassoCV object.
1057
+ """
1058
+ if self._sklearn_object is None:
1059
+ self._sklearn_object = self._create_sklearn_object()
1060
+ return self._sklearn_object
1061
+
1062
+ def to_xgboost(self) -> Any:
1063
+ raise exceptions.SnowflakeMLException(
1064
+ error_code=error_codes.METHOD_NOT_ALLOWED,
1065
+ original_exception=AttributeError(
1066
+ modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1067
+ "to_xgboost()",
1068
+ "to_sklearn()"
1069
+ )
1070
+ ),
1071
+ )
1072
+
1073
+ def to_lightgbm(self) -> Any:
1074
+ raise exceptions.SnowflakeMLException(
1075
+ error_code=error_codes.METHOD_NOT_ALLOWED,
1076
+ original_exception=AttributeError(
1077
+ modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1078
+ "to_lightgbm()",
1079
+ "to_sklearn()"
1080
+ )
1081
+ ),
1082
+ )
983
1083
 
984
- def _get_model_signatures(self, dataset: Union[DataFrame, pd.DataFrame]) -> None:
1084
+ def _get_dependencies(self) -> List[str]:
1085
+ return self._deps
1086
+
1087
+
1088
+ def _generate_model_signatures(self, dataset: Union[DataFrame, pd.DataFrame]) -> None:
985
1089
  self._model_signature_dict = dict()
986
1090
 
987
1091
  PROB_FUNCTIONS = ["predict_log_proba", "predict_proba", "decision_function"]
988
1092
 
989
- inputs = list(_infer_signature(dataset[self.input_cols], "input"))
1093
+ inputs = list(_infer_signature(dataset[self.input_cols], "input", use_snowflake_identifiers=True))
990
1094
  outputs: List[BaseFeatureSpec] = []
991
1095
  if hasattr(self, "predict"):
992
1096
  # keep mypy happy
993
- assert self._sklearn_object is not None and hasattr(self._sklearn_object, "_estimator_type")
1097
+ assert self._sklearn_object is not None and hasattr(self._sklearn_object, "_estimator_type")
994
1098
  # For classifier, the type of predict is the same as the type of label
995
- if self._sklearn_object._estimator_type == 'classifier':
996
- # label columns is the desired type for output
1099
+ if self._sklearn_object._estimator_type == "classifier":
1100
+ # label columns is the desired type for output
997
1101
  outputs = list(_infer_signature(dataset[self.label_cols], "output", use_snowflake_identifiers=True))
998
1102
  # rename the output columns
999
1103
  outputs = list(model_signature_utils.rename_features(outputs, self.output_cols))
1000
- self._model_signature_dict["predict"] = ModelSignature(inputs,
1001
- ([] if self._drop_input_cols else inputs)
1002
- + outputs)
1104
+ self._model_signature_dict["predict"] = ModelSignature(
1105
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1106
+ )
1003
1107
  # For mixture models that use the density mixin, `predict` returns the argmax of the log prob.
1004
1108
  # For outlier models, returns -1 for outliers and 1 for inliers.
1005
- # Clusterer returns int64 cluster labels.
1109
+ # Clusterer returns int64 cluster labels.
1006
1110
  elif self._sklearn_object._estimator_type in ["DensityEstimator", "clusterer", "outlier_detector"]:
1007
1111
  outputs = [FeatureSpec(dtype=DataType.INT64, name=c) for c in self.output_cols]
1008
- self._model_signature_dict["predict"] = ModelSignature(inputs,
1009
- ([] if self._drop_input_cols else inputs)
1010
- + outputs)
1011
-
1112
+ self._model_signature_dict["predict"] = ModelSignature(
1113
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1114
+ )
1115
+
1012
1116
  # For regressor, the type of predict is float64
1013
- elif self._sklearn_object._estimator_type == 'regressor':
1117
+ elif self._sklearn_object._estimator_type == "regressor":
1014
1118
  outputs = [FeatureSpec(dtype=DataType.DOUBLE, name=c) for c in self.output_cols]
1015
- self._model_signature_dict["predict"] = ModelSignature(inputs,
1016
- ([] if self._drop_input_cols else inputs)
1017
- + outputs)
1018
-
1119
+ self._model_signature_dict["predict"] = ModelSignature(
1120
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1121
+ )
1122
+
1019
1123
  for prob_func in PROB_FUNCTIONS:
1020
1124
  if hasattr(self, prob_func):
1021
1125
  output_cols_prefix: str = f"{prob_func}_"
1022
1126
  output_column_names = self._get_output_column_names(output_cols_prefix)
1023
1127
  outputs = [FeatureSpec(dtype=DataType.DOUBLE, name=c) for c in output_column_names]
1024
- self._model_signature_dict[prob_func] = ModelSignature(inputs,
1025
- ([] if self._drop_input_cols else inputs)
1026
- + outputs)
1128
+ self._model_signature_dict[prob_func] = ModelSignature(
1129
+ inputs, ([] if self._drop_input_cols else inputs) + outputs
1130
+ )
1027
1131
 
1028
1132
  # Output signature names may still need to be renamed, since they were not created with `_infer_signature`.
1029
1133
  items = list(self._model_signature_dict.items())
@@ -1036,10 +1140,10 @@ class GraphicalLassoCV(BaseTransformer):
1036
1140
  """Returns model signature of current class.
1037
1141
 
1038
1142
  Raises:
1039
- exceptions.SnowflakeMLException: If estimator is not fitted, then model signature cannot be inferred
1143
+ SnowflakeMLException: If estimator is not fitted, then model signature cannot be inferred
1040
1144
 
1041
1145
  Returns:
1042
- Dict[str, ModelSignature]: each method and its input output signature
1146
+ Dict with each method and its input output signature
1043
1147
  """
1044
1148
  if self._model_signature_dict is None:
1045
1149
  raise exceptions.SnowflakeMLException(
@@ -1047,35 +1151,3 @@ class GraphicalLassoCV(BaseTransformer):
1047
1151
  original_exception=RuntimeError("Estimator not fitted before accessing property model_signatures!"),
1048
1152
  )
1049
1153
  return self._model_signature_dict
1050
-
1051
- def to_sklearn(self) -> Any:
1052
- """Get sklearn.covariance.GraphicalLassoCV object.
1053
- """
1054
- if self._sklearn_object is None:
1055
- self._sklearn_object = self._create_sklearn_object()
1056
- return self._sklearn_object
1057
-
1058
- def to_xgboost(self) -> Any:
1059
- raise exceptions.SnowflakeMLException(
1060
- error_code=error_codes.METHOD_NOT_ALLOWED,
1061
- original_exception=AttributeError(
1062
- modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1063
- "to_xgboost()",
1064
- "to_sklearn()"
1065
- )
1066
- ),
1067
- )
1068
-
1069
- def to_lightgbm(self) -> Any:
1070
- raise exceptions.SnowflakeMLException(
1071
- error_code=error_codes.METHOD_NOT_ALLOWED,
1072
- original_exception=AttributeError(
1073
- modeling_error_messages.UNSUPPORTED_MODEL_CONVERSION.format(
1074
- "to_lightgbm()",
1075
- "to_sklearn()"
1076
- )
1077
- ),
1078
- )
1079
-
1080
- def _get_dependencies(self) -> List[str]:
1081
- return self._deps