CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
test_dummy.py716 linesDownload Raw Back to tests
1import warnings
2
3import numpy as np
4import pytest
5import scipy.sparse as sp
6
7from sklearn.base import clone
8from sklearn.dummy import DummyClassifier, DummyRegressor
9from sklearn.exceptions import NotFittedError
10from sklearn.utils._testing import (
11    assert_almost_equal,
12    assert_array_almost_equal,
13    assert_array_equal,
14)
15from sklearn.utils.fixes import CSC_CONTAINERS
16from sklearn.utils.stats import _weighted_percentile
17
18
19def _check_predict_proba(clf, X, y):
20    proba = clf.predict_proba(X)
21
22    # We know that we can have division by zero
23    with warnings.catch_warnings():
24        warnings.filterwarnings("ignore", "divide by zero encountered in log")
25        log_proba = clf.predict_log_proba(X)
26
27    y = np.atleast_1d(y)
28    if y.ndim == 1:
29        y = np.reshape(y, (-1, 1))
30
31    n_outputs = y.shape[1]
32    n_samples = len(X)
33
34    if n_outputs == 1:
35        proba = [proba]
36        log_proba = [log_proba]
37
38    for k in range(n_outputs):
39        assert proba[k].shape[0] == n_samples
40        assert proba[k].shape[1] == len(np.unique(y[:, k]))
41        assert_array_almost_equal(proba[k].sum(axis=1), np.ones(len(X)))
42        # We know that we can have division by zero
43        with warnings.catch_warnings():
44            warnings.filterwarnings("ignore", "divide by zero encountered in log")
45            assert_array_almost_equal(np.log(proba[k]), log_proba[k])
46
47
48def _check_behavior_2d(clf):
49    # 1d case
50    X = np.array([[0], [0], [0], [0]])  # ignored
51    y = np.array([1, 2, 1, 1])
52    est = clone(clf)
53    est.fit(X, y)
54    y_pred = est.predict(X)
55    assert y.shape == y_pred.shape
56
57    # 2d case
58    y = np.array([[1, 0], [2, 0], [1, 0], [1, 3]])
59    est = clone(clf)
60    est.fit(X, y)
61    y_pred = est.predict(X)
62    assert y.shape == y_pred.shape
63
64
65def _check_behavior_2d_for_constant(clf):
66    # 2d case only
67    X = np.array([[0], [0], [0], [0]])  # ignored
68    y = np.array([[1, 0, 5, 4, 3], [2, 0, 1, 2, 5], [1, 0, 4, 5, 2], [1, 3, 3, 2, 0]])
69    est = clone(clf)
70    est.fit(X, y)
71    y_pred = est.predict(X)
72    assert y.shape == y_pred.shape
73
74
75def _check_equality_regressor(statistic, y_learn, y_pred_learn, y_test, y_pred_test):
76    assert_array_almost_equal(np.tile(statistic, (y_learn.shape[0], 1)), y_pred_learn)
77    assert_array_almost_equal(np.tile(statistic, (y_test.shape[0], 1)), y_pred_test)
78
79
80def test_feature_names_in_and_n_features_in_(global_random_seed, n_samples=10):
81    pd = pytest.importorskip("pandas")
82
83    random_state = np.random.RandomState(seed=global_random_seed)
84
85    X = pd.DataFrame([[0]] * n_samples, columns=["feature_1"])
86    y = random_state.rand(n_samples)
87
88    est = DummyRegressor().fit(X, y)
89    assert hasattr(est, "feature_names_in_")
90    assert hasattr(est, "n_features_in_")
91
92    est = DummyClassifier().fit(X, y)
93    assert hasattr(est, "feature_names_in_")
94    assert hasattr(est, "n_features_in_")
95
96
97def test_most_frequent_and_prior_strategy():
98    X = [[0], [0], [0], [0]]  # ignored
99    y = [1, 2, 1, 1]
100
101    for strategy in ("most_frequent", "prior"):
102        clf = DummyClassifier(strategy=strategy, random_state=0)
103        clf.fit(X, y)
104        assert_array_equal(clf.predict(X), np.ones(len(X)))
105        _check_predict_proba(clf, X, y)
106
107        if strategy == "prior":
108            assert_array_almost_equal(
109                clf.predict_proba([X[0]]), clf.class_prior_.reshape((1, -1))
110            )
111        else:
112            assert_array_almost_equal(
113                clf.predict_proba([X[0]]), clf.class_prior_.reshape((1, -1)) > 0.5
114            )
115
116
117def test_most_frequent_and_prior_strategy_with_2d_column_y():
118    # non-regression test added in
119    # https://github.com/scikit-learn/scikit-learn/pull/13545
120    X = [[0], [0], [0], [0]]
121    y_1d = [1, 2, 1, 1]
122    y_2d = [[1], [2], [1], [1]]
123
124    for strategy in ("most_frequent", "prior"):
125        clf_1d = DummyClassifier(strategy=strategy, random_state=0)
126        clf_2d = DummyClassifier(strategy=strategy, random_state=0)
127
128        clf_1d.fit(X, y_1d)
129        clf_2d.fit(X, y_2d)
130        assert_array_equal(clf_1d.predict(X), clf_2d.predict(X))
131
132
133def test_most_frequent_and_prior_strategy_multioutput():
134    X = [[0], [0], [0], [0]]  # ignored
135    y = np.array([[1, 0], [2, 0], [1, 0], [1, 3]])
136
137    n_samples = len(X)
138
139    for strategy in ("prior", "most_frequent"):
140        clf = DummyClassifier(strategy=strategy, random_state=0)
141        clf.fit(X, y)
142        assert_array_equal(
143            clf.predict(X),
144            np.hstack([np.ones((n_samples, 1)), np.zeros((n_samples, 1))]),
145        )
146        _check_predict_proba(clf, X, y)
147        _check_behavior_2d(clf)
148
149
150def test_stratified_strategy(global_random_seed):
151    X = [[0]] * 5  # ignored
152    y = [1, 2, 1, 1, 2]
153    clf = DummyClassifier(strategy="stratified", random_state=global_random_seed)
154    clf.fit(X, y)
155
156    X = [[0]] * 500
157    y_pred = clf.predict(X)
158    p = np.bincount(y_pred) / float(len(X))
159    assert_almost_equal(p[1], 3.0 / 5, decimal=1)
160    assert_almost_equal(p[2], 2.0 / 5, decimal=1)
161    _check_predict_proba(clf, X, y)
162
163
164def test_stratified_strategy_multioutput(global_random_seed):
165    X = [[0]] * 5  # ignored
166    y = np.array([[2, 1], [2, 2], [1, 1], [1, 2], [1, 1]])
167
168    clf = DummyClassifier(strategy="stratified", random_state=global_random_seed)
169    clf.fit(X, y)
170
171    X = [[0]] * 500
172    y_pred = clf.predict(X)
173
174    for k in range(y.shape[1]):
175        p = np.bincount(y_pred[:, k]) / float(len(X))
176        assert_almost_equal(p[1], 3.0 / 5, decimal=1)
177        assert_almost_equal(p[2], 2.0 / 5, decimal=1)
178        _check_predict_proba(clf, X, y)
179
180    _check_behavior_2d(clf)
181
182
183def test_uniform_strategy(global_random_seed):
184    X = [[0]] * 4  # ignored
185    y = [1, 2, 1, 1]
186    clf = DummyClassifier(strategy="uniform", random_state=global_random_seed)
187    clf.fit(X, y)
188
189    X = [[0]] * 500
190    y_pred = clf.predict(X)
191    p = np.bincount(y_pred) / float(len(X))
192    assert_almost_equal(p[1], 0.5, decimal=1)
193    assert_almost_equal(p[2], 0.5, decimal=1)
194    _check_predict_proba(clf, X, y)
195
196
197def test_uniform_strategy_multioutput(global_random_seed):
198    X = [[0]] * 4  # ignored
199    y = np.array([[2, 1], [2, 2], [1, 2], [1, 1]])
200    clf = DummyClassifier(strategy="uniform", random_state=global_random_seed)
201    clf.fit(X, y)
202
203    X = [[0]] * 500
204    y_pred = clf.predict(X)
205
206    for k in range(y.shape[1]):
207        p = np.bincount(y_pred[:, k]) / float(len(X))
208        assert_almost_equal(p[1], 0.5, decimal=1)
209        assert_almost_equal(p[2], 0.5, decimal=1)
210        _check_predict_proba(clf, X, y)
211
212    _check_behavior_2d(clf)
213
214
215def test_string_labels():
216    X = [[0]] * 5
217    y = ["paris", "paris", "tokyo", "amsterdam", "berlin"]
218    clf = DummyClassifier(strategy="most_frequent")
219    clf.fit(X, y)
220    assert_array_equal(clf.predict(X), ["paris"] * 5)
221
222
223@pytest.mark.parametrize(
224    "y,y_test",
225    [
226        ([2, 1, 1, 1], [2, 2, 1, 1]),
227        (
228            np.array([[2, 2], [1, 1], [1, 1], [1, 1]]),
229            np.array([[2, 2], [2, 2], [1, 1], [1, 1]]),
230        ),
231    ],
232)
233def test_classifier_score_with_None(y, y_test):
234    clf = DummyClassifier(strategy="most_frequent")
235    clf.fit(None, y)
236    assert clf.score(None, y_test) == 0.5
237
238
239@pytest.mark.parametrize(
240    "strategy", ["stratified", "most_frequent", "prior", "uniform", "constant"]
241)
242def test_classifier_prediction_independent_of_X(strategy, global_random_seed):
243    y = [0, 2, 1, 1]
244    X1 = [[0]] * 4
245    clf1 = DummyClassifier(
246        strategy=strategy, random_state=global_random_seed, constant=0
247    )
248    clf1.fit(X1, y)
249    predictions1 = clf1.predict(X1)
250
251    X2 = [[1]] * 4
252    clf2 = DummyClassifier(
253        strategy=strategy, random_state=global_random_seed, constant=0
254    )
255    clf2.fit(X2, y)
256    predictions2 = clf2.predict(X2)
257
258    assert_array_equal(predictions1, predictions2)
259
260
261def test_mean_strategy_regressor(global_random_seed):
262    random_state = np.random.RandomState(seed=global_random_seed)
263
264    X = [[0]] * 4  # ignored
265    y = random_state.randn(4)
266
267    reg = DummyRegressor()
268    reg.fit(X, y)
269    assert_array_equal(reg.predict(X), [np.mean(y)] * len(X))
270
271
272def test_mean_strategy_multioutput_regressor(global_random_seed):
273    random_state = np.random.RandomState(seed=global_random_seed)
274
275    X_learn = random_state.randn(10, 10)
276    y_learn = random_state.randn(10, 5)
277
278    mean = np.mean(y_learn, axis=0).reshape((1, -1))
279
280    X_test = random_state.randn(20, 10)
281    y_test = random_state.randn(20, 5)
282
283    # Correctness oracle
284    est = DummyRegressor()
285    est.fit(X_learn, y_learn)
286    y_pred_learn = est.predict(X_learn)
287    y_pred_test = est.predict(X_test)
288
289    _check_equality_regressor(mean, y_learn, y_pred_learn, y_test, y_pred_test)
290    _check_behavior_2d(est)
291
292
293def test_regressor_exceptions():
294    reg = DummyRegressor()
295    with pytest.raises(NotFittedError):
296        reg.predict([])
297
298
299def test_median_strategy_regressor(global_random_seed):
300    random_state = np.random.RandomState(seed=global_random_seed)
301
302    X = [[0]] * 5  # ignored
303    y = random_state.randn(5)
304
305    reg = DummyRegressor(strategy="median")
306    reg.fit(X, y)
307    assert_array_equal(reg.predict(X), [np.median(y)] * len(X))
308
309
310def test_median_strategy_multioutput_regressor(global_random_seed):
311    random_state = np.random.RandomState(seed=global_random_seed)
312
313    X_learn = random_state.randn(10, 10)
314    y_learn = random_state.randn(10, 5)
315
316    median = np.median(y_learn, axis=0).reshape((1, -1))
317
318    X_test = random_state.randn(20, 10)
319    y_test = random_state.randn(20, 5)
320
321    # Correctness oracle
322    est = DummyRegressor(strategy="median")
323    est.fit(X_learn, y_learn)
324    y_pred_learn = est.predict(X_learn)
325    y_pred_test = est.predict(X_test)
326
327    _check_equality_regressor(median, y_learn, y_pred_learn, y_test, y_pred_test)
328    _check_behavior_2d(est)
329
330
331def test_quantile_strategy_regressor(global_random_seed):
332    random_state = np.random.RandomState(seed=global_random_seed)
333
334    X = [[0]] * 5  # ignored
335    y = random_state.randn(5)
336
337    reg = DummyRegressor(strategy="quantile", quantile=0.5)
338    reg.fit(X, y)
339    assert_array_equal(reg.predict(X), [np.median(y)] * len(X))
340
341    reg = DummyRegressor(strategy="quantile", quantile=0)
342    reg.fit(X, y)
343    assert_array_equal(reg.predict(X), [np.min(y)] * len(X))
344
345    reg = DummyRegressor(strategy="quantile", quantile=1)
346    reg.fit(X, y)
347    assert_array_equal(reg.predict(X), [np.max(y)] * len(X))
348
349    reg = DummyRegressor(strategy="quantile", quantile=0.3)
350    reg.fit(X, y)
351    assert_array_equal(reg.predict(X), [np.percentile(y, q=30)] * len(X))
352
353
354def test_quantile_strategy_multioutput_regressor(global_random_seed):
355    random_state = np.random.RandomState(seed=global_random_seed)
356
357    X_learn = random_state.randn(10, 10)
358    y_learn = random_state.randn(10, 5)
359
360    median = np.median(y_learn, axis=0).reshape((1, -1))
361    quantile_values = np.percentile(y_learn, axis=0, q=80).reshape((1, -1))
362
363    X_test = random_state.randn(20, 10)
364    y_test = random_state.randn(20, 5)
365
366    # Correctness oracle
367    est = DummyRegressor(strategy="quantile", quantile=0.5)
368    est.fit(X_learn, y_learn)
369    y_pred_learn = est.predict(X_learn)
370    y_pred_test = est.predict(X_test)
371
372    _check_equality_regressor(median, y_learn, y_pred_learn, y_test, y_pred_test)
373    _check_behavior_2d(est)
374
375    # Correctness oracle
376    est = DummyRegressor(strategy="quantile", quantile=0.8)
377    est.fit(X_learn, y_learn)
378    y_pred_learn = est.predict(X_learn)
379    y_pred_test = est.predict(X_test)
380
381    _check_equality_regressor(
382        quantile_values, y_learn, y_pred_learn, y_test, y_pred_test
383    )
384    _check_behavior_2d(est)
385
386
387def test_quantile_invalid():
388    X = [[0]] * 5  # ignored
389    y = [0] * 5  # ignored
390
391    est = DummyRegressor(strategy="quantile", quantile=None)
392    err_msg = (
393        "When using `strategy='quantile', you have to specify the desired quantile"
394    )
395    with pytest.raises(ValueError, match=err_msg):
396        est.fit(X, y)
397
398
399def test_quantile_strategy_empty_train():
400    est = DummyRegressor(strategy="quantile", quantile=0.4)
401    with pytest.raises(IndexError):
402        est.fit([], [])
403
404
405def test_constant_strategy_regressor(global_random_seed):
406    random_state = np.random.RandomState(seed=global_random_seed)
407
408    X = [[0]] * 5  # ignored
409    y = random_state.randn(5)
410
411    reg = DummyRegressor(strategy="constant", constant=[43])
412    reg.fit(X, y)
413    assert_array_equal(reg.predict(X), [43] * len(X))
414
415    reg = DummyRegressor(strategy="constant", constant=43)
416    reg.fit(X, y)
417    assert_array_equal(reg.predict(X), [43] * len(X))
418
419    # non-regression test for #22478
420    assert not isinstance(reg.constant, np.ndarray)
421
422
423def test_constant_strategy_multioutput_regressor(global_random_seed):
424    random_state = np.random.RandomState(seed=global_random_seed)
425
426    X_learn = random_state.randn(10, 10)
427    y_learn = random_state.randn(10, 5)
428
429    # test with 2d array
430    constants = random_state.randn(5)
431
432    X_test = random_state.randn(20, 10)
433    y_test = random_state.randn(20, 5)
434
435    # Correctness oracle
436    est = DummyRegressor(strategy="constant", constant=constants)
437    est.fit(X_learn, y_learn)
438    y_pred_learn = est.predict(X_learn)
439    y_pred_test = est.predict(X_test)
440
441    _check_equality_regressor(constants, y_learn, y_pred_learn, y_test, y_pred_test)
442    _check_behavior_2d_for_constant(est)
443
444
445def test_y_mean_attribute_regressor():
446    X = [[0]] * 5
447    y = [1, 2, 4, 6, 8]
448    # when strategy = 'mean'
449    est = DummyRegressor(strategy="mean")
450    est.fit(X, y)
451
452    assert est.constant_ == np.mean(y)
453
454
455def test_constants_not_specified_regressor():
456    X = [[0]] * 5
457    y = [1, 2, 4, 6, 8]
458
459    est = DummyRegressor(strategy="constant")
460    err_msg = "Constant target value has to be specified"
461    with pytest.raises(TypeError, match=err_msg):
462        est.fit(X, y)
463
464
465def test_constant_size_multioutput_regressor(global_random_seed):
466    random_state = np.random.RandomState(seed=global_random_seed)
467    X = random_state.randn(10, 10)
468    y = random_state.randn(10, 5)
469
470    est = DummyRegressor(strategy="constant", constant=[1, 2, 3, 4])
471    err_msg = r"Constant target value should have shape \(5, 1\)."
472    with pytest.raises(ValueError, match=err_msg):
473        est.fit(X, y)
474
475
476def test_constant_strategy():
477    X = [[0], [0], [0], [0]]  # ignored
478    y = [2, 1, 2, 2]
479
480    clf = DummyClassifier(strategy="constant", random_state=0, constant=1)
481    clf.fit(X, y)
482    assert_array_equal(clf.predict(X), np.ones(len(X)))
483    _check_predict_proba(clf, X, y)
484
485    X = [[0], [0], [0], [0]]  # ignored
486    y = ["two", "one", "two", "two"]
487    clf = DummyClassifier(strategy="constant", random_state=0, constant="one")
488    clf.fit(X, y)
489    assert_array_equal(clf.predict(X), np.array(["one"] * 4))
490    _check_predict_proba(clf, X, y)
491
492
493def test_constant_strategy_multioutput():
494    X = [[0], [0], [0], [0]]  # ignored
495    y = np.array([[2, 3], [1, 3], [2, 3], [2, 0]])
496
497    n_samples = len(X)
498
499    clf = DummyClassifier(strategy="constant", random_state=0, constant=[1, 0])
500    clf.fit(X, y)
501    assert_array_equal(
502        clf.predict(X), np.hstack([np.ones((n_samples, 1)), np.zeros((n_samples, 1))])
503    )
504    _check_predict_proba(clf, X, y)
505
506
507@pytest.mark.parametrize(
508    "y, params, err_msg",
509    [
510        ([2, 1, 2, 2], {"random_state": 0}, "Constant.*has to be specified"),
511        ([2, 1, 2, 2], {"constant": [2, 0]}, "Constant.*should have shape"),
512        (
513            np.transpose([[2, 1, 2, 2], [2, 1, 2, 2]]),
514            {"constant": 2},
515            "Constant.*should have shape",
516        ),
517        (
518            [2, 1, 2, 2],
519            {"constant": "my-constant"},
520            "constant=my-constant.*Possible values.*\\[1, 2]",
521        ),
522        (
523            np.transpose([[2, 1, 2, 2], [2, 1, 2, 2]]),
524            {"constant": [2, "unknown"]},
525            "constant=\\[2, 'unknown'].*Possible values.*\\[1, 2]",
526        ),
527    ],
528    ids=[
529        "no-constant",
530        "too-many-constant",
531        "not-enough-output",
532        "single-output",
533        "multi-output",
534    ],
535)
536def test_constant_strategy_exceptions(y, params, err_msg):
537    X = [[0], [0], [0], [0]]
538
539    clf = DummyClassifier(strategy="constant", **params)
540    with pytest.raises(ValueError, match=err_msg):
541        clf.fit(X, y)
542
543
544def test_classification_sample_weight():
545    X = [[0], [0], [1]]
546    y = [0, 1, 0]
547    sample_weight = [0.1, 1.0, 0.1]
548
549    clf = DummyClassifier(strategy="stratified").fit(X, y, sample_weight)
550    assert_array_almost_equal(clf.class_prior_, [0.2 / 1.2, 1.0 / 1.2])
551
552
553@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
554def test_constant_strategy_sparse_target(csc_container):
555    X = [[0]] * 5  # ignored
556    y = csc_container(np.array([[0, 1], [4, 0], [1, 1], [1, 4], [1, 1]]))
557
558    n_samples = len(X)
559
560    clf = DummyClassifier(strategy="constant", random_state=0, constant=[1, 0])
561    clf.fit(X, y)
562    y_pred = clf.predict(X)
563    assert sp.issparse(y_pred)
564    assert_array_equal(
565        y_pred.toarray(), np.hstack([np.ones((n_samples, 1)), np.zeros((n_samples, 1))])
566    )
567
568
569@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
570def test_uniform_strategy_sparse_target_warning(global_random_seed, csc_container):
571    X = [[0]] * 5  # ignored
572    y = csc_container(np.array([[2, 1], [2, 2], [1, 4], [4, 2], [1, 1]]))
573
574    clf = DummyClassifier(strategy="uniform", random_state=global_random_seed)
575    with pytest.warns(UserWarning, match="the uniform strategy would not save memory"):
576        clf.fit(X, y)
577
578    X = [[0]] * 500
579    y_pred = clf.predict(X)
580
581    for k in range(y.shape[1]):
582        p = np.bincount(y_pred[:, k]) / float(len(X))
583        assert_almost_equal(p[1], 1 / 3, decimal=1)
584        assert_almost_equal(p[2], 1 / 3, decimal=1)
585        assert_almost_equal(p[4], 1 / 3, decimal=1)
586
587
588@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
589def test_stratified_strategy_sparse_target(global_random_seed, csc_container):
590    X = [[0]] * 5  # ignored
591    y = csc_container(np.array([[4, 1], [0, 0], [1, 1], [1, 4], [1, 1]]))
592
593    clf = DummyClassifier(strategy="stratified", random_state=global_random_seed)
594    clf.fit(X, y)
595
596    X = [[0]] * 500
597    y_pred = clf.predict(X)
598    assert sp.issparse(y_pred)
599    y_pred = y_pred.toarray()
600
601    for k in range(y.shape[1]):
602        p = np.bincount(y_pred[:, k]) / float(len(X))
603        assert_almost_equal(p[1], 3.0 / 5, decimal=1)
604        assert_almost_equal(p[0], 1.0 / 5, decimal=1)
605        assert_almost_equal(p[4], 1.0 / 5, decimal=1)
606
607
608@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
609def test_most_frequent_and_prior_strategy_sparse_target(csc_container):
610    X = [[0]] * 5  # ignored
611    y = csc_container(np.array([[1, 0], [1, 3], [4, 0], [0, 1], [1, 0]]))
612
613    n_samples = len(X)
614    y_expected = np.hstack([np.ones((n_samples, 1)), np.zeros((n_samples, 1))])
615    for strategy in ("most_frequent", "prior"):
616        clf = DummyClassifier(strategy=strategy, random_state=0)
617        clf.fit(X, y)
618
619        y_pred = clf.predict(X)
620        assert sp.issparse(y_pred)
621        assert_array_equal(y_pred.toarray(), y_expected)
622
623
624def test_dummy_regressor_sample_weight(global_random_seed, n_samples=10):
625    random_state = np.random.RandomState(seed=global_random_seed)
626
627    X = [[0]] * n_samples
628    y = random_state.rand(n_samples)
629    sample_weight = random_state.rand(n_samples)
630
631    est = DummyRegressor(strategy="mean").fit(X, y, sample_weight)
632    assert est.constant_ == np.average(y, weights=sample_weight)
633
634    est = DummyRegressor(strategy="median").fit(X, y, sample_weight)
635    assert est.constant_ == _weighted_percentile(y, sample_weight, 50.0)
636
637    est = DummyRegressor(strategy="quantile", quantile=0.95).fit(X, y, sample_weight)
638    assert est.constant_ == _weighted_percentile(y, sample_weight, 95.0)
639
640
641def test_dummy_regressor_on_3D_array():
642    X = np.array([[["foo"]], [["bar"]], [["baz"]]])
643    y = np.array([2, 2, 2])
644    y_expected = np.array([2, 2, 2])
645    cls = DummyRegressor()
646    cls.fit(X, y)
647    y_pred = cls.predict(X)
648    assert_array_equal(y_pred, y_expected)
649
650
651def test_dummy_classifier_on_3D_array():
652    X = np.array([[["foo"]], [["bar"]], [["baz"]]])
653    y = [2, 2, 2]
654    y_expected = [2, 2, 2]
655    y_proba_expected = [[1], [1], [1]]
656    cls = DummyClassifier(strategy="stratified")
657    cls.fit(X, y)
658    y_pred = cls.predict(X)
659    y_pred_proba = cls.predict_proba(X)
660    assert_array_equal(y_pred, y_expected)
661    assert_array_equal(y_pred_proba, y_proba_expected)
662
663
664def test_dummy_regressor_return_std():
665    X = [[0]] * 3  # ignored
666    y = np.array([2, 2, 2])
667    y_std_expected = np.array([0, 0, 0])
668    cls = DummyRegressor()
669    cls.fit(X, y)
670    y_pred_list = cls.predict(X, return_std=True)
671    # there should be two elements when return_std is True
672    assert len(y_pred_list) == 2
673    # the second element should be all zeros
674    assert_array_equal(y_pred_list[1], y_std_expected)
675
676
677@pytest.mark.parametrize(
678    "y,y_test",
679    [
680        ([1, 1, 1, 2], [1.25] * 4),
681        (np.array([[2, 2], [1, 1], [1, 1], [1, 1]]), [[1.25, 1.25]] * 4),
682    ],
683)
684def test_regressor_score_with_None(y, y_test):
685    reg = DummyRegressor()
686    reg.fit(None, y)
687    assert reg.score(None, y_test) == 1.0
688
689
690@pytest.mark.parametrize("strategy", ["mean", "median", "quantile", "constant"])
691def test_regressor_prediction_independent_of_X(strategy):
692    y = [0, 2, 1, 1]
693    X1 = [[0]] * 4
694    reg1 = DummyRegressor(strategy=strategy, constant=0, quantile=0.7)
695    reg1.fit(X1, y)
696    predictions1 = reg1.predict(X1)
697
698    X2 = [[1]] * 4
699    reg2 = DummyRegressor(strategy=strategy, constant=0, quantile=0.7)
700    reg2.fit(X2, y)
701    predictions2 = reg2.predict(X2)
702
703    assert_array_equal(predictions1, predictions2)
704
705
706@pytest.mark.parametrize(
707    "strategy", ["stratified", "most_frequent", "prior", "uniform", "constant"]
708)
709def test_dtype_of_classifier_probas(strategy):
710    y = [0, 2, 1, 1]
711    X = np.zeros(4)
712    model = DummyClassifier(strategy=strategy, random_state=0, constant=0)
713    probas = model.fit(X, y).predict_proba(X)
714
715    assert probas.dtype == np.float64
716 
Aluode/PerceptionLabPortable · CoolFace