forked from mlflow/mlflow
-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_sklearn_autolog.py
1913 lines (1476 loc) · 70.8 KB
/
test_sklearn_autolog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import inspect
from unittest import mock
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pytest
import re
from packaging.version import Version
import sklearn
import sklearn.base
import sklearn.cluster
import sklearn.datasets
import sklearn.pipeline
import sklearn.model_selection
from scipy.stats import uniform
from scipy.sparse import csr_matrix, csc_matrix
from mlflow.exceptions import MlflowException
from mlflow.models import Model
from mlflow.models.signature import infer_signature
from mlflow.models.utils import _read_example
import mlflow.sklearn
from mlflow.entities import RunStatus
from mlflow.sklearn.utils import (
_is_supported_version,
_is_metric_supported,
_is_plotting_supported,
_get_arg_names,
_log_child_runs_info,
)
from mlflow.utils import _truncate_dict
from mlflow.utils.mlflow_tags import MLFLOW_AUTOLOGGING
from mlflow.utils.validation import (
MAX_PARAMS_TAGS_PER_BATCH,
MAX_METRICS_PER_BATCH,
MAX_PARAM_VAL_LENGTH,
MAX_ENTITY_KEY_LENGTH,
)
FIT_FUNC_NAMES = ["fit", "fit_transform", "fit_predict"]
TRAINING_SCORE = "training_score"
ESTIMATOR_CLASS = "estimator_class"
ESTIMATOR_NAME = "estimator_name"
MODEL_DIR = "model"
pytestmark = pytest.mark.large
def get_iris():
iris = sklearn.datasets.load_iris()
return iris.data[:, :2], iris.target
def fit_model(model, X, y, fit_func_name):
if fit_func_name == "fit":
model.fit(X, y)
if fit_func_name == "fit_transform":
model.fit_transform(X, y)
if fit_func_name == "fit_predict":
model.fit_predict(X, y)
if fit_func_name == "fake":
if isinstance(model, sklearn.linear_model.LinearRegression):
model.coef_ = np.random.random(size=np.shape(X)[-1])
model.intercept_ = 0
return model
def get_run(run_id):
return mlflow.tracking.MlflowClient().get_run(run_id)
def get_run_data(run_id):
client = mlflow.tracking.MlflowClient()
data = client.get_run(run_id).data
# Ignore tags mlflow logs by default (e.g. "mlflow.user")
tags = {k: v for k, v in data.tags.items() if not k.startswith("mlflow.")}
artifacts = [f.path for f in client.list_artifacts(run_id)]
return data.params, data.metrics, tags, artifacts
def load_model_by_run_id(run_id):
return mlflow.sklearn.load_model("runs:/{}/{}".format(run_id, MODEL_DIR))
def get_model_conf(artifact_uri, model_subpath=MODEL_DIR):
model_conf_path = os.path.join(artifact_uri, model_subpath, "MLmodel")
return Model.load(model_conf_path)
def stringify_dict_values(d):
return {k: str(v) for k, v in d.items()}
def truncate_dict(d):
return _truncate_dict(d, MAX_ENTITY_KEY_LENGTH, MAX_PARAM_VAL_LENGTH)
def get_expected_class_tags(model):
return {
ESTIMATOR_NAME: model.__class__.__name__,
ESTIMATOR_CLASS: model.__class__.__module__ + "." + model.__class__.__name__,
}
def assert_predict_equal(left, right, X):
np.testing.assert_array_equal(left.predict(X), right.predict(X))
@pytest.fixture(params=FIT_FUNC_NAMES)
def fit_func_name(request):
return request.param
def test_autolog_preserves_original_function_attributes():
def get_func_attrs(f):
attrs = {}
for attr_name in ["__doc__", "__name__"]:
if hasattr(f, attr_name):
attrs[attr_name] = getattr(f, attr_name)
attrs["__signature__"] = inspect.signature(f)
return attrs
def get_cls_attrs(cls):
attrs = {}
for method_name in FIT_FUNC_NAMES:
if hasattr(cls, method_name):
attr = getattr(cls, method_name)
if isinstance(attr, property):
continue
attrs[method_name] = get_func_attrs(attr)
return attrs
before = [get_cls_attrs(cls) for _, cls in mlflow.sklearn.utils._all_estimators()]
mlflow.sklearn.autolog()
after = [get_cls_attrs(cls) for _, cls in mlflow.sklearn.utils._all_estimators()]
for b, a in zip(before, after):
assert b == a
def test_autolog_throws_error_with_negative_max_tuning_runs():
with pytest.raises(
MlflowException, match="`max_tuning_runs` must be non-negative, instead got -1."
):
mlflow.sklearn.autolog(max_tuning_runs=-1)
@pytest.mark.parametrize(
"max_tuning_runs, total_runs, output_statment",
[
(0, 4, "Logging no runs, all will be omitted"),
(0, 1, "Logging no runs, one run will be omitted"),
(1, 1, "Logging the best run, no runs will be omitted"),
(5, 4, "Logging all runs, no runs will be omitted"),
(4, 4, "Logging all runs, no runs will be omitted"),
(2, 5, "Logging the 2 best runs, 3 runs will be omitted"),
],
)
def test_autolog_max_tuning_runs_logs_info_correctly(max_tuning_runs, total_runs, output_statment):
with mock.patch("mlflow.sklearn.utils._logger.info") as mock_info:
_log_child_runs_info(max_tuning_runs, total_runs)
mock_info.assert_called_once()
mock_info.called_once_with(output_statment)
@pytest.mark.skipif(
_is_supported_version(), reason="This test fails on supported versions of sklearn"
)
def test_autolog_emits_warning_on_unsupported_versions_of_sklearn():
with pytest.warns(
UserWarning, match="Autologging utilities may not work properly on scikit-learn"
):
mlflow.sklearn.autolog()
def test_autolog_does_not_terminate_active_run():
mlflow.sklearn.autolog()
mlflow.start_run()
sklearn.cluster.KMeans().fit(*get_iris())
assert mlflow.active_run() is not None
mlflow.end_run()
def test_estimator(fit_func_name):
mlflow.sklearn.autolog()
# use `KMeans` because it implements `fit`, `fit_transform`, and `fit_predict`.
model = sklearn.cluster.KMeans()
X, y = get_iris()
with mlflow.start_run() as run:
model = fit_model(model, X, y, fit_func_name)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
assert params == truncate_dict(stringify_dict_values(model.get_params(deep=True)))
assert {TRAINING_SCORE: model.score(X, y)}.items() <= metrics.items()
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
loaded_model = load_model_by_run_id(run_id)
assert_predict_equal(loaded_model, model, X)
def test_classifier_binary():
mlflow.sklearn.autolog()
# use RandomForestClassifier that has method [predict_proba], so that we can test
# logging of (1) log_loss and (2) roc_auc_score.
model = sklearn.ensemble.RandomForestClassifier(max_depth=2, random_state=0, n_estimators=10)
# use binary datasets to cover the test for roc curve & precision recall curve
X, y_true = sklearn.datasets.load_breast_cancer(return_X_y=True)
with mlflow.start_run() as run:
model = fit_model(model, X, y_true, "fit")
y_pred = model.predict(X)
y_pred_prob = model.predict_proba(X)
# For binary classification, y_score only accepts the probability of greater label
y_pred_prob_roc = y_pred_prob[:, 1]
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
assert params == truncate_dict(stringify_dict_values(model.get_params(deep=True)))
expected_metrics = {
TRAINING_SCORE: model.score(X, y_true),
"training_accuracy_score": sklearn.metrics.accuracy_score(y_true, y_pred),
"training_precision_score": sklearn.metrics.precision_score(
y_true, y_pred, average="weighted"
),
"training_recall_score": sklearn.metrics.recall_score(y_true, y_pred, average="weighted"),
"training_f1_score": sklearn.metrics.f1_score(y_true, y_pred, average="weighted"),
"training_log_loss": sklearn.metrics.log_loss(y_true, y_pred_prob),
}
if _is_metric_supported("roc_auc_score"):
expected_metrics["training_roc_auc_score"] = sklearn.metrics.roc_auc_score(
y_true, y_score=y_pred_prob_roc, average="weighted", multi_class="ovo",
)
assert metrics == expected_metrics
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
client = mlflow.tracking.MlflowClient()
artifacts = [x.path for x in client.list_artifacts(run_id)]
plot_names = []
if _is_plotting_supported():
plot_names.extend(
[
"{}.png".format("training_confusion_matrix"),
"{}.png".format("training_roc_curve"),
"{}.png".format("training_precision_recall_curve"),
]
)
assert all(x in artifacts for x in plot_names)
loaded_model = load_model_by_run_id(run_id)
assert_predict_equal(loaded_model, model, X)
# verify no figure is open
assert len(plt.get_fignums()) == 0
def test_classifier_multi_class():
mlflow.sklearn.autolog()
# use RandomForestClassifier that has method [predict_proba], so that we can test
# logging of (1) log_loss and (2) roc_auc_score.
model = sklearn.ensemble.RandomForestClassifier(max_depth=2, random_state=0, n_estimators=10)
# use multi-class datasets to verify that roc curve & precision recall curve care not recorded
X, y_true = get_iris()
with mlflow.start_run() as run:
model = fit_model(model, X, y_true, "fit")
y_pred = model.predict(X)
y_pred_prob = model.predict_proba(X)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
assert params == truncate_dict(stringify_dict_values(model.get_params(deep=True)))
expected_metrics = {
TRAINING_SCORE: model.score(X, y_true),
"training_accuracy_score": sklearn.metrics.accuracy_score(y_true, y_pred),
"training_precision_score": sklearn.metrics.precision_score(
y_true, y_pred, average="weighted"
),
"training_recall_score": sklearn.metrics.recall_score(y_true, y_pred, average="weighted"),
"training_f1_score": sklearn.metrics.f1_score(y_true, y_pred, average="weighted"),
"training_log_loss": sklearn.metrics.log_loss(y_true, y_pred_prob),
}
if _is_metric_supported("roc_auc_score"):
expected_metrics["training_roc_auc_score"] = sklearn.metrics.roc_auc_score(
y_true, y_score=y_pred_prob, average="weighted", multi_class="ovo",
)
assert metrics == expected_metrics
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
client = mlflow.tracking.MlflowClient()
artifacts = [x.path for x in client.list_artifacts(run_id)]
plot_names = []
if _is_plotting_supported():
plot_names = ["{}.png".format("training_confusion_matrix")]
assert all(x in artifacts for x in plot_names)
loaded_model = load_model_by_run_id(run_id)
assert_predict_equal(loaded_model, model, X)
def test_regressor():
mlflow.sklearn.autolog()
# use simple `LinearRegression`, which only implements `fit`.
model = sklearn.linear_model.LinearRegression()
X, y_true = get_iris()
with mlflow.start_run() as run:
model = fit_model(model, X, y_true, "fit")
y_pred = model.predict(X)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
assert params == truncate_dict(stringify_dict_values(model.get_params(deep=True)))
assert metrics == {
TRAINING_SCORE: model.score(X, y_true),
"training_mse": sklearn.metrics.mean_squared_error(y_true, y_pred),
"training_rmse": np.sqrt(sklearn.metrics.mean_squared_error(y_true, y_pred)),
"training_mae": sklearn.metrics.mean_absolute_error(y_true, y_pred),
"training_r2_score": sklearn.metrics.r2_score(y_true, y_pred),
}
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
loaded_model = load_model_by_run_id(run_id)
assert_predict_equal(loaded_model, model, X)
def test_meta_estimator():
mlflow.sklearn.autolog()
estimators = [
("std_scaler", sklearn.preprocessing.StandardScaler()),
("svc", sklearn.svm.SVC()),
]
model = sklearn.pipeline.Pipeline(estimators)
X, y = get_iris()
with mlflow.start_run() as run:
model.fit(X, y)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
assert params == truncate_dict(stringify_dict_values(model.get_params(deep=True)))
assert {TRAINING_SCORE: model.score(X, y)}.items() <= metrics.items()
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
assert_predict_equal(load_model_by_run_id(run_id), model, X)
def test_get_params_returns_dict_that_has_more_keys_than_max_params_tags_per_batch():
mlflow.sklearn.autolog()
large_params = {str(i): str(i) for i in range(MAX_PARAMS_TAGS_PER_BATCH + 1)}
X, y = get_iris()
with mock.patch("sklearn.cluster.KMeans.get_params", return_value=large_params):
with mlflow.start_run() as run:
model = sklearn.cluster.KMeans()
model.fit(X, y)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run.info.run_id)
assert params == large_params
assert {TRAINING_SCORE: model.score(X, y)}.items() <= metrics.items()
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
loaded_model = load_model_by_run_id(run_id)
assert_predict_equal(loaded_model, model, X)
@pytest.mark.parametrize(
"long_params, messages",
[
# key exceeds the limit
({("a" * (MAX_ENTITY_KEY_LENGTH + 1)): "b"}, ["Truncated the key"]),
# value exceeds the limit
({"a": "b" * (MAX_PARAM_VAL_LENGTH + 1)}, ["Truncated the value"]),
# both key and value exceed the limit
(
{("a" * (MAX_ENTITY_KEY_LENGTH + 1)): "b" * (MAX_PARAM_VAL_LENGTH + 1)},
["Truncated the key", "Truncated the value"],
),
],
)
def test_get_params_returns_dict_whose_key_or_value_exceeds_length_limit(long_params, messages):
mlflow.sklearn.autolog()
X, y = get_iris()
with mock.patch("sklearn.cluster.KMeans.get_params", return_value=long_params), mock.patch(
"mlflow.utils._logger.warning"
) as mock_warning, mlflow.start_run() as run:
model = sklearn.cluster.KMeans()
model.fit(X, y)
for idx, msg in enumerate(messages):
assert mock_warning.call_args_list[idx].startswith(msg)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run.info.run_id)
assert params == truncate_dict(long_params)
assert {TRAINING_SCORE: model.score(X, y)}.items() <= metrics.items()
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
loaded_model = load_model_by_run_id(run_id)
assert_predict_equal(loaded_model, model, X)
@pytest.mark.parametrize("Xy_passed_as", ["only_y_kwarg", "both_kwarg", "both_kwargs_swapped"])
def test_fit_takes_Xy_as_keyword_arguments(Xy_passed_as):
mlflow.sklearn.autolog()
model = sklearn.cluster.KMeans()
X, y = get_iris()
with mlflow.start_run() as run:
if Xy_passed_as == "only_y_kwarg":
model.fit(X, y=y)
elif Xy_passed_as == "both_kwarg":
model.fit(X=X, y=y)
elif Xy_passed_as == "both_kwargs_swapped":
model.fit(y=y, X=X)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
assert params == truncate_dict(stringify_dict_values(model.get_params(deep=True)))
assert {TRAINING_SCORE: model.score(X, y)}.items() <= metrics.items()
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
assert_predict_equal(load_model_by_run_id(run_id), model, X)
def test_call_fit_with_arguments_score_does_not_accept():
mlflow.sklearn.autolog()
from sklearn.linear_model import SGDRegressor
assert "intercept_init" in _get_arg_names(SGDRegressor.fit)
assert "intercept_init" not in _get_arg_names(SGDRegressor.score)
mock_obj = mock.Mock()
def mock_score(self, X, y, sample_weight=None): # pylint: disable=unused-argument
mock_obj(X, y, sample_weight)
return 0
assert inspect.signature(SGDRegressor.score) == inspect.signature(mock_score)
SGDRegressor.score = mock_score
model = SGDRegressor()
X, y = get_iris()
with mlflow.start_run() as run:
model.fit(X, y, intercept_init=0)
mock_obj.assert_called_once_with(X, y, None)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
assert params == truncate_dict(stringify_dict_values(model.get_params(deep=True)))
assert {TRAINING_SCORE: model.score(X, y)}.items() <= metrics.items()
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
assert_predict_equal(load_model_by_run_id(run_id), model, X)
@pytest.mark.parametrize("sample_weight_passed_as", ["positional", "keyword"])
def test_both_fit_and_score_contain_sample_weight(sample_weight_passed_as):
mlflow.sklearn.autolog()
from sklearn.linear_model import SGDRegressor
# ensure that we use an appropriate model for this test
assert "sample_weight" in _get_arg_names(SGDRegressor.fit)
assert "sample_weight" in _get_arg_names(SGDRegressor.score)
mock_obj = mock.Mock()
def mock_score(self, X, y, sample_weight=None): # pylint: disable=unused-argument
mock_obj(X, y, sample_weight)
return 0
assert inspect.signature(SGDRegressor.score) == inspect.signature(mock_score)
SGDRegressor.score = mock_score
model = SGDRegressor()
X, y = get_iris()
sample_weight = abs(np.random.randn(len(X)))
with mlflow.start_run() as run:
if sample_weight_passed_as == "positional":
model.fit(X, y, None, None, sample_weight)
elif sample_weight_passed_as == "keyword":
model.fit(X, y, sample_weight=sample_weight)
mock_obj.assert_called_once_with(X, y, sample_weight)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
assert params == truncate_dict(stringify_dict_values(model.get_params(deep=True)))
assert {TRAINING_SCORE: model.score(X, y)}.items() <= metrics.items()
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
assert_predict_equal(load_model_by_run_id(run_id), model, X)
def test_only_fit_contains_sample_weight():
mlflow.sklearn.autolog()
from sklearn.linear_model import RANSACRegressor
assert "sample_weight" in _get_arg_names(RANSACRegressor.fit)
assert "sample_weight" not in _get_arg_names(RANSACRegressor.score)
mock_obj = mock.Mock()
def mock_score(self, X, y): # pylint: disable=unused-argument
mock_obj(X, y)
return 0
assert inspect.signature(RANSACRegressor.score) == inspect.signature(mock_score)
RANSACRegressor.score = mock_score
model = RANSACRegressor()
X, y = get_iris()
with mlflow.start_run() as run:
model.fit(X, y)
mock_obj.assert_called_once_with(X, y)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
assert params == truncate_dict(stringify_dict_values(model.get_params(deep=True)))
assert {TRAINING_SCORE: model.score(X, y)}.items() <= metrics.items()
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
assert_predict_equal(load_model_by_run_id(run_id), model, X)
def test_only_score_contains_sample_weight():
mlflow.sklearn.autolog()
from sklearn.gaussian_process import GaussianProcessRegressor
assert "sample_weight" not in _get_arg_names(GaussianProcessRegressor.fit)
assert "sample_weight" in _get_arg_names(GaussianProcessRegressor.score)
mock_obj = mock.Mock()
def mock_score(self, X, y, sample_weight=None): # pylint: disable=unused-argument
mock_obj(X, y, sample_weight)
return 0
assert inspect.signature(GaussianProcessRegressor.score) == inspect.signature(mock_score)
GaussianProcessRegressor.score = mock_score
model = GaussianProcessRegressor()
X, y = get_iris()
with mlflow.start_run() as run:
model.fit(X, y)
mock_obj.assert_called_once_with(X, y, None)
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
assert params == truncate_dict(stringify_dict_values(model.get_params(deep=True)))
assert {TRAINING_SCORE: model.score(X, y)}.items() <= metrics.items()
assert tags == get_expected_class_tags(model)
assert MODEL_DIR in artifacts
assert_predict_equal(load_model_by_run_id(run_id), model, X)
def test_autolog_terminates_run_when_active_run_does_not_exist_and_fit_fails():
mlflow.sklearn.autolog()
with pytest.raises(ValueError, match="Penalty term must be positive"):
sklearn.svm.LinearSVC(C=-1).fit(*get_iris())
latest_run = mlflow.search_runs().iloc[0]
assert mlflow.active_run() is None
assert latest_run.status == "FAILED"
def test_autolog_does_not_terminate_run_when_active_run_exists_and_fit_fails():
mlflow.sklearn.autolog()
run = mlflow.start_run()
with pytest.raises(ValueError, match="Penalty term must be positive"):
sklearn.svm.LinearSVC(C=-1).fit(*get_iris())
assert mlflow.active_run() is not None
assert mlflow.active_run() is run
mlflow.end_run()
def test_autolog_emits_warning_message_when_score_fails():
mlflow.sklearn.autolog()
model = sklearn.cluster.KMeans()
@functools.wraps(model.score)
def throwing_score(X, y=None, sample_weight=None): # pylint: disable=unused-argument
raise Exception("EXCEPTION")
model.score = throwing_score
with mlflow.start_run(), mock.patch("mlflow.sklearn.utils._logger.warning") as mock_warning:
model.fit(*get_iris())
mock_warning.assert_called_once()
mock_warning.called_once_with(
"KMeans.score failed. The 'training_score' metric will not be recorded. "
"Scoring error: EXCEPTION"
)
def test_autolog_emits_warning_message_when_metric_fails():
"""
Take precision_score metric from SVC as an example to test metric logging failure
"""
mlflow.sklearn.autolog()
model = sklearn.svm.SVC()
@functools.wraps(sklearn.metrics.precision_score)
def throwing_metrics(y_true, y_pred): # pylint: disable=unused-argument
raise Exception("EXCEPTION")
with mlflow.start_run(), mock.patch(
"mlflow.sklearn.utils._logger.warning"
) as mock_warning, mock.patch("sklearn.metrics.precision_score", side_effect=throwing_metrics):
model.fit(*get_iris())
mock_warning.assert_called_once()
mock_warning.called_once_with(
"SVC.precision_score failed. "
"The 'precision_score' metric will not be recorded. "
"Metric error: EXCEPTION"
)
def test_autolog_emits_warning_message_when_model_prediction_fails():
"""
Take GridSearchCV as an example, whose base class is "classifier" and will go
through classifier's metric logging. When refit=False, the model will never get
refitted, while during the metric logging what ".predict()" expects is a fitted model.
Thus, a warning will be logged.
"""
from sklearn.exceptions import NotFittedError
mlflow.sklearn.autolog()
metrics_size = 2
metrics_to_log = {
"score_{}".format(i): sklearn.metrics.make_scorer(lambda y, y_pred, **kwargs: 10)
for i in range(metrics_size)
}
with mlflow.start_run(), mock.patch("mlflow.sklearn.utils._logger.warning") as mock_warning:
svc = sklearn.svm.SVC()
cv_model = sklearn.model_selection.GridSearchCV(
svc, {"C": [1]}, n_jobs=1, scoring=metrics_to_log, refit=False
)
cv_model.fit(*get_iris())
# Ensure `cv_model.predict` fails with `NotFittedError` or `AttributeError`
err = (
NotFittedError if Version(sklearn.__version__) <= Version("0.24.2") else AttributeError
)
match = r"This GridSearchCV instance.+refit=False.+predict"
with pytest.raises(err, match=match):
cv_model.predict([[0, 0, 0, 0]])
# Count how many times `mock_warning` has been called on not-fitted `predict` failure
call_count = len(
[args for args in mock_warning.call_args_list if re.search(match, args[0][0])]
)
# If `_is_plotting_supported` returns True (meaning sklearn version is >= 0.22.0),
# `mock_warning` should have been called twice, once for metrics, once for artifacts.
# Otherwise, only once for metrics.
call_count_expected = 2 if mlflow.sklearn.utils._is_plotting_supported() else 1
assert call_count == call_count_expected
@pytest.mark.parametrize(
"cv_class, search_space",
[
(sklearn.model_selection.GridSearchCV, {"kernel": ("linear", "rbf"), "C": [1, 5, 10]}),
(sklearn.model_selection.RandomizedSearchCV, {"C": uniform(loc=0, scale=4)}),
],
)
@pytest.mark.parametrize("backend", [None, "threading", "loky"])
@pytest.mark.parametrize("max_tuning_runs", [None, 3])
def test_parameter_search_estimators_produce_expected_outputs(
cv_class, search_space, backend, max_tuning_runs
):
mlflow.sklearn.autolog(
log_input_examples=True, log_model_signatures=True, max_tuning_runs=max_tuning_runs,
)
svc = sklearn.svm.SVC()
cv_model = cv_class(svc, search_space, n_jobs=5, return_train_score=True)
X, y = get_iris()
def train_cv_model():
if backend is None:
cv_model.fit(X, y)
else:
with sklearn.utils.parallel_backend(backend=backend):
cv_model.fit(X, y)
with mlflow.start_run() as run:
train_cv_model()
run_id = run.info.run_id
params, metrics, tags, artifacts = get_run_data(run_id)
expected_cv_params = truncate_dict(stringify_dict_values(cv_model.get_params(deep=False)))
expected_cv_params.update(
{
"best_{}".format(param_name): str(param_value)
for param_name, param_value in cv_model.best_params_.items()
}
)
assert params == expected_cv_params
assert {
TRAINING_SCORE: cv_model.score(X, y),
"best_cv_score": cv_model.best_score_,
}.items() <= metrics.items()
assert tags == get_expected_class_tags(cv_model)
assert MODEL_DIR in artifacts
assert "best_estimator" in artifacts
assert "cv_results.csv" in artifacts
best_estimator = mlflow.sklearn.load_model("runs:/{}/best_estimator".format(run_id))
assert isinstance(best_estimator, sklearn.svm.SVC)
cv_model = mlflow.sklearn.load_model("runs:/{}/{}".format(run_id, MODEL_DIR))
assert isinstance(cv_model, cv_class)
# Ensure that a signature and input example are produced for the best estimator
best_estimator_conf = get_model_conf(run.info.artifact_uri, "best_estimator")
assert best_estimator_conf.signature == infer_signature(X, best_estimator.predict(X[:5]))
best_estimator_path = os.path.join(run.info.artifact_uri, "best_estimator")
input_example = _read_example(best_estimator_conf, best_estimator_path)
best_estimator.predict(input_example) # Ensure that input example evaluation succeeds
client = mlflow.tracking.MlflowClient()
child_runs = client.search_runs(
run.info.experiment_id, "tags.`mlflow.parentRunId` = '{}'".format(run_id)
)
cv_results = pd.DataFrame.from_dict(cv_model.cv_results_)
num_total_results = len(cv_results)
if max_tuning_runs is None:
cv_results_best_n_df = cv_results
cv_results_rest_df = pd.DataFrame()
else:
num_rest = max(0, num_total_results - max_tuning_runs)
cv_results_best_n_df = cv_results.nsmallest(max_tuning_runs, "rank_test_score")
cv_results_rest_df = cv_results.nlargest(num_rest, "rank_test_score", keep="last")
# We expect to have created a child run for each point in the parameter search space
# up to max_tuning_runs.
assert len(child_runs) == max_tuning_runs
assert len(child_runs) + num_rest == num_total_results
# Verify that the best max_tuning_runs of parameter search results
# have a corresponding MLflow run with the expected data
for _, result in cv_results_best_n_df.iterrows():
result_params = result.get("params", {})
params_search_clause = " and ".join(
["params.`{}` = '{}'".format(key, value) for key, value in result_params.items()]
)
search_filter = "tags.`mlflow.parentRunId` = '{}' and {}".format(
run_id, params_search_clause
)
child_runs = client.search_runs(run.info.experiment_id, search_filter)
assert len(child_runs) == 1
child_run = child_runs[0]
assert child_run.info.status == RunStatus.to_string(RunStatus.FINISHED)
_, child_metrics, child_tags, _ = get_run_data(child_run.info.run_id)
assert child_tags == get_expected_class_tags(svc)
assert child_run.data.tags.get(MLFLOW_AUTOLOGGING) == mlflow.sklearn.FLAVOR_NAME
assert "mean_test_score" in child_metrics.keys()
assert "std_test_score" in child_metrics.keys()
# Ensure that we do not capture separate metrics for each cross validation split, which
# would produce very noisy metrics results
assert len([metric for metric in child_metrics.keys() if metric.startswith("split")]) == 0
# Verify that the rest of the parameter search results do not have
# a corresponding MLflow run.
for _, result in cv_results_rest_df.iterrows():
result_params = result.get("params", {})
params_search_clause = " and ".join(
["params.`{}` = '{}'".format(key, value) for key, value in result_params.items()]
)
search_filter = "tags.`mlflow.parentRunId` = '{}' and {}".format(
run_id, params_search_clause
)
child_runs = client.search_runs(run.info.experiment_id, search_filter)
assert len(child_runs) == 0
def test_parameter_search_handles_large_volume_of_metric_outputs():
mlflow.sklearn.autolog()
metrics_size = MAX_METRICS_PER_BATCH + 10
metrics_to_log = {
"score_{}".format(i): sklearn.metrics.make_scorer(lambda y, y_pred, **kwargs: 10)
for i in range(metrics_size)
}
with mlflow.start_run() as run:
svc = sklearn.svm.SVC()
cv_model = sklearn.model_selection.GridSearchCV(
svc, {"C": [1]}, n_jobs=1, scoring=metrics_to_log, refit=False
)
cv_model.fit(*get_iris())
run_id = run.info.run_id
client = mlflow.tracking.MlflowClient()
child_runs = client.search_runs(
run.info.experiment_id, "tags.`mlflow.parentRunId` = '{}'".format(run_id)
)
assert len(child_runs) == 1
child_run = child_runs[0]
assert len(child_run.data.metrics) >= metrics_size
@pytest.mark.parametrize("data_type", [pd.DataFrame, np.array, csr_matrix, csc_matrix])
def test_autolog_logs_signature_and_input_example(data_type):
mlflow.sklearn.autolog(log_input_examples=True, log_model_signatures=True)
X, y = get_iris()
X = data_type(X)
if data_type in [csr_matrix, csc_matrix]:
y = np.array(y)
else:
y = data_type(y)
model = sklearn.linear_model.LinearRegression()
with mlflow.start_run() as run:
model.fit(X, y)
model_path = os.path.join(run.info.artifact_uri, MODEL_DIR)
model_conf = get_model_conf(run.info.artifact_uri)
input_example = _read_example(model_conf, model_path)
pyfunc_model = mlflow.pyfunc.load_model(model_path)
assert model_conf.signature == infer_signature(X, model.predict(X[:5]))
# On GitHub Actions, `pyfunc_model.predict` and `model.predict` sometimes return
# slightly different results:
#
# >>> pyfunc_model.predict(input_example)
# [[0.171504346208176 ]
# [0.34346150441640155] <- diff
# [0.06895096846585114] <- diff
# [0.05925789882165455]
# [0.03424907823290102]]
#
# >>> model.predict(X[:5])
# [[0.171504346208176 ]
# [0.3434615044164018 ] <- diff
# [0.06895096846585136] <- diff
# [0.05925789882165455]
# [0.03424907823290102]]
#
# As a workaround, use `assert_array_almost_equal` instead of `assert_array_equal`
np.testing.assert_array_almost_equal(pyfunc_model.predict(input_example), model.predict(X[:5]))
def test_autolog_does_not_throw_when_failing_to_sample_X():
class ArrayThatThrowsWhenSliced(np.ndarray):
def __new__(cls, input_array):
return np.asarray(input_array).view(cls)
def __getitem__(self, key):
if isinstance(key, slice):
raise IndexError("DO NOT SLICE ME")
return super().__getitem__(key)
X, y = get_iris()
throwing_X = ArrayThatThrowsWhenSliced(X)
# ensure throwing_X throws when sliced
with pytest.raises(IndexError, match="DO NOT SLICE ME"):
_ = throwing_X[:5]
mlflow.sklearn.autolog()
model = sklearn.linear_model.LinearRegression()
with mlflow.start_run() as run, mock.patch("mlflow.sklearn._logger.warning") as mock_warning:
model.fit(throwing_X, y)
model_conf = get_model_conf(run.info.artifact_uri)
mock_warning.assert_called_once()
mock_warning.call_args[0][0].endswith("DO NOT SLICE ME")
assert "signature" not in model_conf.to_dict()
assert "saved_input_example_info" not in model_conf.to_dict()
def test_autolog_logs_signature_only_when_estimator_defines_predict():
from sklearn.cluster import AgglomerativeClustering
mlflow.sklearn.autolog(log_model_signatures=True)
X, y = get_iris()
model = AgglomerativeClustering()
assert not hasattr(model, "predict")
with mlflow.start_run() as run:
model.fit(X, y)
model_conf = get_model_conf(run.info.artifact_uri)
assert "signature" not in model_conf.to_dict()
def test_autolog_does_not_throw_when_predict_fails():
X, y = get_iris()
mlflow.sklearn.autolog(log_input_examples=True, log_model_signatures=True)
# Note that `mock_warning` will be called twice because if `predict` throws, `score` also throws
with mlflow.start_run() as run, mock.patch(
"sklearn.linear_model.LinearRegression.predict", side_effect=Exception("Failed")
), mock.patch("mlflow.sklearn._logger.warning") as mock_warning:
model = sklearn.linear_model.LinearRegression()
model.fit(X, y)
mock_warning.assert_called_with("Failed to infer model signature: Failed")
model_conf = get_model_conf(run.info.artifact_uri)
assert "signature" not in model_conf.to_dict()
def test_autolog_does_not_throw_when_infer_signature_fails():
X, y = get_iris()
with mlflow.start_run() as run, mock.patch(
"mlflow.models.infer_signature", side_effect=Exception("Failed")
), mock.patch("mlflow.sklearn._logger.warning") as mock_warning:
mlflow.sklearn.autolog(log_input_examples=True, log_model_signatures=True)
model = sklearn.linear_model.LinearRegression()
model.fit(X, y)
mock_warning.assert_called_once_with("Failed to infer model signature: Failed")
model_conf = get_model_conf(run.info.artifact_uri)
assert "signature" not in model_conf.to_dict()
@pytest.mark.large
@pytest.mark.parametrize("log_input_examples", [True, False])
@pytest.mark.parametrize("log_model_signatures", [True, False])
def test_autolog_configuration_options(log_input_examples, log_model_signatures):
X, y = get_iris()
with mlflow.start_run() as run:
mlflow.sklearn.autolog(
log_input_examples=log_input_examples, log_model_signatures=log_model_signatures
)
model = sklearn.linear_model.LinearRegression()
model.fit(X, y)
model_conf = get_model_conf(run.info.artifact_uri)
assert ("saved_input_example_info" in model_conf.to_dict()) == log_input_examples
assert ("signature" in model_conf.to_dict()) == log_model_signatures
@pytest.mark.large
@pytest.mark.parametrize("log_models", [True, False])
def test_sklearn_autolog_log_models_configuration(log_models):
X, y = get_iris()
with mlflow.start_run() as run:
mlflow.sklearn.autolog(log_models=log_models)
model = sklearn.linear_model.LinearRegression()
model.fit(X, y)