test_dask.py 46 KB
Newer Older
1
# coding: utf-8
2
3
"""Tests for lightgbm.dask module"""

4
5
import inspect
import pickle
6
import random
7
import socket
8
9
from itertools import groupby
from os import getenv
10
from platform import machine
11
from sys import platform
12
13

import pytest
14
15
16

import lightgbm as lgb

17
if not platform.startswith('linux'):
18
    pytest.skip('lightgbm.dask is currently supported in Linux environments', allow_module_level=True)
19
20
if not lgb.compat.DASK_INSTALLED:
    pytest.skip('Dask is not installed', allow_module_level=True)
21

22
import cloudpickle
23
24
import dask.array as da
import dask.dataframe as dd
25
import joblib
26
27
import numpy as np
import pandas as pd
28
import sklearn.utils.estimator_checks as sklearn_checks
29
from dask.array.utils import assert_eq
30
from dask.distributed import Client, LocalCluster, default_client, wait
31
from distributed.utils_test import client, cluster_fixture, gen_cluster, loop
32
from pkg_resources import parse_version
33
from scipy.sparse import csr_matrix
34
from scipy.stats import spearmanr
35
from sklearn import __version__ as sk_version
36
37
from sklearn.datasets import make_blobs, make_regression

38
39
from .utils import make_ranking

40
41
sk_version = parse_version(sk_version)

42
43
# time, in seconds, to wait for the Dask client to close. Used to avoid teardown errors
# see https://distributed.dask.org/en/latest/api.html#distributed.Client.close
44
CLIENT_CLOSE_TIMEOUT = 120
45

46
tasks = ['binary-classification', 'multiclass-classification', 'regression', 'ranking']
47
data_output = ['array', 'scipy_csr_matrix', 'dataframe', 'dataframe-with-categorical']
48
group_sizes = [5, 5, 5, 10, 10, 10, 20, 20, 20, 50, 50]
49
50
51
52
53
54
55
56
57
58
59
60
task_to_dask_factory = {
    'regression': lgb.DaskLGBMRegressor,
    'binary-classification': lgb.DaskLGBMClassifier,
    'multiclass-classification': lgb.DaskLGBMClassifier,
    'ranking': lgb.DaskLGBMRanker
}
task_to_local_factory = {
    'regression': lgb.LGBMRegressor,
    'binary-classification': lgb.LGBMClassifier,
    'multiclass-classification': lgb.LGBMClassifier,
    'ranking': lgb.LGBMRanker
}
61
62

pytestmark = [
63
    pytest.mark.skipif(getenv('TASK', '') == 'mpi', reason='Fails to run with MPI interface'),
64
65
    pytest.mark.skipif(getenv('TASK', '') == 'gpu', reason='Fails to run with GPU interface'),
    pytest.mark.skipif(machine() != 'x86_64', reason='Fails to run with non-x86_64 architecture')
66
67
68
69
70
71
72
73
74
75
76
77
]


@pytest.fixture()
def listen_port():
    listen_port.port += 10
    return listen_port.port


listen_port.port = 13000


78
def _create_ranking_data(n_samples=100, output='array', chunk_size=50, **kwargs):
79
    X, y, g = make_ranking(n_samples=n_samples, random_state=42, **kwargs)
80
81
    rnd = np.random.RandomState(42)
    w = rnd.rand(X.shape[0]) * 0.01
82
    g_rle = np.array([len(list(grp)) for _, grp in groupby(g)])
83

84
    if output.startswith('dataframe'):
85
86
        # add target, weight, and group to DataFrame so that partitions abide by group boundaries.
        X_df = pd.DataFrame(X, columns=[f'feature_{i}' for i in range(X.shape[1])])
87
88
89
90
91
92
93
94
95
        if output == 'dataframe-with-categorical':
            for i in range(5):
                col_name = "cat_col" + str(i)
                cat_values = rnd.choice(['a', 'b'], X.shape[0])
                cat_series = pd.Series(
                    cat_values,
                    dtype='category'
                )
                X_df[col_name] = cat_series
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
        X = X_df.copy()
        X_df = X_df.assign(y=y, g=g, w=w)

        # set_index ensures partitions are based on group id.
        # See https://stackoverflow.com/questions/49532824/dask-dataframe-split-partitions-based-on-a-column-or-function.
        X_df.set_index('g', inplace=True)
        dX = dd.from_pandas(X_df, chunksize=chunk_size)

        # separate target, weight from features.
        dy = dX['y']
        dw = dX['w']
        dX = dX.drop(columns=['y', 'w'])
        dg = dX.index.to_series()

        # encode group identifiers into run-length encoding, the format LightGBMRanker is expecting
        # so that within each partition, sum(g) = n_samples.
        dg = dg.map_partitions(lambda p: p.groupby('g', sort=False).apply(lambda z: z.shape[0]))
    elif output == 'array':
        # ranking arrays: one chunk per group. Each chunk must include all columns.
        p = X.shape[1]
        dX, dy, dw, dg = [], [], [], []
        for g_idx, rhs in enumerate(np.cumsum(g_rle)):
            lhs = rhs - g_rle[g_idx]
            dX.append(da.from_array(X[lhs:rhs, :], chunks=(rhs - lhs, p)))
            dy.append(da.from_array(y[lhs:rhs]))
            dw.append(da.from_array(w[lhs:rhs]))
            dg.append(da.from_array(np.array([g_rle[g_idx]])))

        dX = da.concatenate(dX, axis=0)
        dy = da.concatenate(dy, axis=0)
        dw = da.concatenate(dw, axis=0)
        dg = da.concatenate(dg, axis=0)
    else:
        raise ValueError('Ranking data creation only supported for Dask arrays and dataframes')

    return X, y, w, g_rle, dX, dy, dw, dg


134
def _create_data(objective, n_samples=1_000, output='array', chunk_size=500, **kwargs):
135
136
137
138
139
140
141
    if objective.endswith('classification'):
        if objective == 'binary-classification':
            centers = [[-4, -4], [4, 4]]
        elif objective == 'multiclass-classification':
            centers = [[-4, -4], [4, 4], [-4, 4]]
        else:
            raise ValueError(f"Unknown classification task '{objective}'")
142
143
        X, y = make_blobs(n_samples=n_samples, centers=centers, random_state=42)
    elif objective == 'regression':
144
        X, y = make_regression(n_samples=n_samples, n_features=4, n_informative=2, random_state=42)
145
146
147
148
149
150
151
    elif objective == 'ranking':
        return _create_ranking_data(
            n_samples=n_samples,
            output=output,
            chunk_size=chunk_size,
            **kwargs
        )
152
    else:
153
        raise ValueError("Unknown objective '%s'" % objective)
154
155
156
157
158
159
160
    rnd = np.random.RandomState(42)
    weights = rnd.random(X.shape[0]) * 0.01

    if output == 'array':
        dX = da.from_array(X, (chunk_size, X.shape[1]))
        dy = da.from_array(y, chunk_size)
        dw = da.from_array(weights, chunk_size)
161
    elif output.startswith('dataframe'):
162
        X_df = pd.DataFrame(X, columns=['feature_%d' % i for i in range(X.shape[1])])
163
        if output == 'dataframe-with-categorical':
164
            num_cat_cols = 2
165
166
167
168
169
170
171
172
173
174
            for i in range(num_cat_cols):
                col_name = "cat_col" + str(i)
                cat_values = rnd.choice(['a', 'b'], X.shape[0])
                cat_series = pd.Series(
                    cat_values,
                    dtype='category'
                )
                X_df[col_name] = cat_series
                X = np.hstack((X, cat_series.cat.codes.values.reshape(-1, 1)))

175
176
            # make one categorical feature relevant to the target
            cat_col_is_a = X_df['cat_col0'] == 'a'
177
            if objective == 'regression':
178
179
180
181
182
183
                y = np.where(cat_col_is_a, y, 2 * y)
            elif objective == 'binary-classification':
                y = np.where(cat_col_is_a, y, 1 - y)
            elif objective == 'multiclass-classification':
                n_classes = 3
                y = np.where(cat_col_is_a, y, (1 + y) % n_classes)
184
185
186
187
188
        y_df = pd.Series(y, name='target')
        dX = dd.from_pandas(X_df, chunksize=chunk_size)
        dy = dd.from_pandas(y_df, chunksize=chunk_size)
        dw = dd.from_array(weights, chunksize=chunk_size)
    elif output == 'scipy_csr_matrix':
189
        dX = da.from_array(X, chunks=(chunk_size, X.shape[1])).map_blocks(csr_matrix)
190
191
192
        dy = da.from_array(y, chunks=chunk_size)
        dw = da.from_array(weights, chunk_size)
    else:
193
        raise ValueError("Unknown output type '%s'" % output)
194

195
    return X, y, weights, None, dX, dy, dw, None
196
197


198
199
200
201
202
203
204
205
206
207
def _r2_score(dy_true, dy_pred):
    numerator = ((dy_true - dy_pred) ** 2).sum(axis=0, dtype=np.float64)
    denominator = ((dy_true - dy_pred.mean(axis=0)) ** 2).sum(axis=0, dtype=np.float64)
    return (1 - numerator / denominator).compute()


def _accuracy_score(dy_true, dy_pred):
    return da.average(dy_true == dy_pred).compute()


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
def _pickle(obj, filepath, serializer):
    if serializer == 'pickle':
        with open(filepath, 'wb') as f:
            pickle.dump(obj, f)
    elif serializer == 'joblib':
        joblib.dump(obj, filepath)
    elif serializer == 'cloudpickle':
        with open(filepath, 'wb') as f:
            cloudpickle.dump(obj, f)
    else:
        raise ValueError(f'Unrecognized serializer type: {serializer}')


def _unpickle(filepath, serializer):
    if serializer == 'pickle':
        with open(filepath, 'rb') as f:
            return pickle.load(f)
    elif serializer == 'joblib':
        return joblib.load(filepath)
    elif serializer == 'cloudpickle':
        with open(filepath, 'rb') as f:
            return cloudpickle.load(f)
    else:
        raise ValueError(f'Unrecognized serializer type: {serializer}')


234
@pytest.mark.parametrize('output', data_output)
235
236
@pytest.mark.parametrize('task', ['binary-classification', 'multiclass-classification'])
def test_classifier(output, task, client):
237
    X, y, w, _, dX, dy, dw, _ = _create_data(
238
239
        objective=task,
        output=output
240
    )
241

242
    params = {
243
244
        "n_estimators": 50,
        "num_leaves": 31
245
    }
246

247
    dask_classifier = lgb.DaskLGBMClassifier(
248
        client=client,
James Lamb's avatar
James Lamb committed
249
        time_out=5,
250
        **params
James Lamb's avatar
James Lamb committed
251
    )
252
    dask_classifier = dask_classifier.fit(dX, dy, sample_weight=dw)
253
    p1 = dask_classifier.predict(dX)
James Lamb's avatar
James Lamb committed
254
    p1_proba = dask_classifier.predict_proba(dX).compute()
255
    p1_pred_leaf = dask_classifier.predict(dX, pred_leaf=True)
256
    p1_local = dask_classifier.to_local().predict(X)
257
    s1 = _accuracy_score(dy, p1)
258
259
    p1 = p1.compute()

260
    local_classifier = lgb.LGBMClassifier(**params)
261
262
    local_classifier.fit(X, y, sample_weight=w)
    p2 = local_classifier.predict(X)
James Lamb's avatar
James Lamb committed
263
    p2_proba = local_classifier.predict_proba(X)
264
265
266
267
268
269
    s2 = local_classifier.score(X, y)

    assert_eq(s1, s2)
    assert_eq(p1, p2)
    assert_eq(y, p1)
    assert_eq(y, p2)
270
    assert_eq(p1_proba, p2_proba, atol=0.01)
271
272
    assert_eq(p1_local, p2)
    assert_eq(y, p1_local)
273

274
275
276
277
278
279
280
281
282
283
284
    # pref_leaf values should have the right shape
    # and values that look like valid tree nodes
    pred_leaf_vals = p1_pred_leaf.compute()
    assert pred_leaf_vals.shape == (
        X.shape[0],
        dask_classifier.booster_.num_trees()
    )
    assert np.max(pred_leaf_vals) <= params['num_leaves']
    assert np.min(pred_leaf_vals) >= 0
    assert len(np.unique(pred_leaf_vals)) <= params['num_leaves']

285
286
287
288
289
290
291
292
293
294
295
296
    # be sure LightGBM actually used at least one categorical column,
    # and that it was correctly treated as a categorical feature
    if output == 'dataframe-with-categorical':
        cat_cols = [
            col for col in dX.columns
            if dX.dtypes[col].name == 'category'
        ]
        tree_df = dask_classifier.booster_.trees_to_dataframe()
        node_uses_cat_col = tree_df['split_feature'].isin(cat_cols)
        assert node_uses_cat_col.sum() > 0
        assert tree_df.loc[node_uses_cat_col, "decision_type"].unique()[0] == '=='

297
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)
298

299

300
@pytest.mark.parametrize('output', data_output)
301
302
@pytest.mark.parametrize('task', ['binary-classification', 'multiclass-classification'])
def test_classifier_pred_contrib(output, task, client):
303
    X, y, w, _, dX, dy, dw, _ = _create_data(
304
305
        objective=task,
        output=output
306
    )
307

308
309
310
311
    params = {
        "n_estimators": 10,
        "num_leaves": 10
    }
312

313
    dask_classifier = lgb.DaskLGBMClassifier(
314
        client=client,
315
316
        time_out=5,
        tree_learner='data',
317
        **params
318
    )
319
    dask_classifier = dask_classifier.fit(dX, dy, sample_weight=dw)
320
321
    preds_with_contrib = dask_classifier.predict(dX, pred_contrib=True).compute()

322
    local_classifier = lgb.LGBMClassifier(**params)
323
324
325
326
327
328
    local_classifier.fit(X, y, sample_weight=w)
    local_preds_with_contrib = local_classifier.predict(X, pred_contrib=True)

    if output == 'scipy_csr_matrix':
        preds_with_contrib = np.array(preds_with_contrib.todense())

329
330
331
332
333
334
335
336
337
338
339
340
    # be sure LightGBM actually used at least one categorical column,
    # and that it was correctly treated as a categorical feature
    if output == 'dataframe-with-categorical':
        cat_cols = [
            col for col in dX.columns
            if dX.dtypes[col].name == 'category'
        ]
        tree_df = dask_classifier.booster_.trees_to_dataframe()
        node_uses_cat_col = tree_df['split_feature'].isin(cat_cols)
        assert node_uses_cat_col.sum() > 0
        assert tree_df.loc[node_uses_cat_col, "decision_type"].unique()[0] == '=='

341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
    # shape depends on whether it is binary or multiclass classification
    num_features = dask_classifier.n_features_
    num_classes = dask_classifier.n_classes_
    if num_classes == 2:
        expected_num_cols = num_features + 1
    else:
        expected_num_cols = (num_features + 1) * num_classes

    # * shape depends on whether it is binary or multiclass classification
    # * matrix for binary classification is of the form [feature_contrib, base_value],
    #   for multi-class it's [feat_contrib_class1, base_value_class1, feat_contrib_class2, base_value_class2, etc.]
    # * contrib outputs for distributed training are different than from local training, so we can just test
    #   that the output has the right shape and base values are in the right position
    assert preds_with_contrib.shape[1] == expected_num_cols
    assert preds_with_contrib.shape == local_preds_with_contrib.shape

    if num_classes == 2:
        assert len(np.unique(preds_with_contrib[:, num_features]) == 1)
    else:
        for i in range(num_classes):
            base_value_col = num_features * (i + 1) + i
            assert len(np.unique(preds_with_contrib[:, base_value_col]) == 1)

364
365
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)

366

367
368
369
370
371
372
373
374
375
376
377
378
379
def test_find_random_open_port(client):
    for _ in range(5):
        worker_address_to_port = client.run(lgb.dask._find_random_open_port)
        found_ports = worker_address_to_port.values()
        # check that found ports are different for same address (LocalCluster)
        assert len(set(found_ports)) == len(found_ports)
        # check that the ports are indeed open
        for port in found_ports:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.bind(('', port))
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)


380
def test_training_does_not_fail_on_port_conflicts(client):
381
    _, _, _, _, dX, dy, dw, _ = _create_data('binary-classification', output='array')
382

383
    lightgbm_default_port = 12400
384
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
385
        s.bind(('127.0.0.1', lightgbm_default_port))
386
        dask_classifier = lgb.DaskLGBMClassifier(
387
            client=client,
388
            time_out=5,
James Lamb's avatar
James Lamb committed
389
390
            n_estimators=5,
            num_leaves=5
391
        )
392
        for _ in range(5):
393
394
395
396
397
398
399
            dask_classifier.fit(
                X=dX,
                y=dy,
                sample_weight=dw,
            )
            assert dask_classifier.booster_

400
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)
401

402

403
@pytest.mark.parametrize('output', data_output)
404
def test_regressor(output, client):
405
    X, y, w, _, dX, dy, dw, _ = _create_data(
406
407
408
        objective='regression',
        output=output
    )
409

410
411
    params = {
        "random_state": 42,
412
413
        "num_leaves": 31,
        "n_estimators": 20,
414
    }
415

416
    dask_regressor = lgb.DaskLGBMRegressor(
417
        client=client,
James Lamb's avatar
James Lamb committed
418
        time_out=5,
419
420
        tree='data',
        **params
James Lamb's avatar
James Lamb committed
421
    )
422
    dask_regressor = dask_regressor.fit(dX, dy, sample_weight=dw)
423
    p1 = dask_regressor.predict(dX)
424
425
    p1_pred_leaf = dask_regressor.predict(dX, pred_leaf=True)

426
    s1 = _r2_score(dy, p1)
427
    p1 = p1.compute()
428
429
    p1_local = dask_regressor.to_local().predict(X)
    s1_local = dask_regressor.to_local().score(X, y)
430

431
    local_regressor = lgb.LGBMRegressor(**params)
432
433
434
435
436
    local_regressor.fit(X, y, sample_weight=w)
    s2 = local_regressor.score(X, y)
    p2 = local_regressor.predict(X)

    # Scores should be the same
437
438
    assert_eq(s1, s2, atol=0.01)
    assert_eq(s1, s1_local)
439

440
    # Predictions should be roughly the same.
441
    assert_eq(p1, p1_local)
442

443
444
445
446
447
448
449
450
451
452
453
    # pref_leaf values should have the right shape
    # and values that look like valid tree nodes
    pred_leaf_vals = p1_pred_leaf.compute()
    assert pred_leaf_vals.shape == (
        X.shape[0],
        dask_regressor.booster_.num_trees()
    )
    assert np.max(pred_leaf_vals) <= params['num_leaves']
    assert np.min(pred_leaf_vals) >= 0
    assert len(np.unique(pred_leaf_vals)) <= params['num_leaves']

454
455
    assert_eq(p1, y, rtol=0.5, atol=50.)
    assert_eq(p2, y, rtol=0.5, atol=50.)
456
457
458
459
460
461
462
463
464
465
466
467
468

    # be sure LightGBM actually used at least one categorical column,
    # and that it was correctly treated as a categorical feature
    if output == 'dataframe-with-categorical':
        cat_cols = [
            col for col in dX.columns
            if dX.dtypes[col].name == 'category'
        ]
        tree_df = dask_regressor.booster_.trees_to_dataframe()
        node_uses_cat_col = tree_df['split_feature'].isin(cat_cols)
        assert node_uses_cat_col.sum() > 0
        assert tree_df.loc[node_uses_cat_col, "decision_type"].unique()[0] == '=='

469
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)
470

471

472
@pytest.mark.parametrize('output', data_output)
473
def test_regressor_pred_contrib(output, client):
474
    X, y, w, _, dX, dy, dw, _ = _create_data(
475
476
477
        objective='regression',
        output=output
    )
478

479
480
481
482
    params = {
        "n_estimators": 10,
        "num_leaves": 10
    }
483

484
    dask_regressor = lgb.DaskLGBMRegressor(
485
        client=client,
486
487
        time_out=5,
        tree_learner='data',
488
        **params
489
    )
490
    dask_regressor = dask_regressor.fit(dX, dy, sample_weight=dw)
491
492
    preds_with_contrib = dask_regressor.predict(dX, pred_contrib=True).compute()

493
    local_regressor = lgb.LGBMRegressor(**params)
494
495
496
497
498
499
500
501
502
503
504
505
    local_regressor.fit(X, y, sample_weight=w)
    local_preds_with_contrib = local_regressor.predict(X, pred_contrib=True)

    if output == "scipy_csr_matrix":
        preds_with_contrib = np.array(preds_with_contrib.todense())

    # contrib outputs for distributed training are different than from local training, so we can just test
    # that the output has the right shape and base values are in the right position
    num_features = dX.shape[1]
    assert preds_with_contrib.shape[1] == num_features + 1
    assert preds_with_contrib.shape == local_preds_with_contrib.shape

506
507
508
509
510
511
512
513
514
515
516
517
    # be sure LightGBM actually used at least one categorical column,
    # and that it was correctly treated as a categorical feature
    if output == 'dataframe-with-categorical':
        cat_cols = [
            col for col in dX.columns
            if dX.dtypes[col].name == 'category'
        ]
        tree_df = dask_regressor.booster_.trees_to_dataframe()
        node_uses_cat_col = tree_df['split_feature'].isin(cat_cols)
        assert node_uses_cat_col.sum() > 0
        assert tree_df.loc[node_uses_cat_col, "decision_type"].unique()[0] == '=='

518
519
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)

520

521
522
@pytest.mark.parametrize('output', data_output)
@pytest.mark.parametrize('alpha', [.1, .5, .9])
523
def test_regressor_quantile(output, client, alpha):
524
    X, y, w, _, dX, dy, dw, _ = _create_data(
525
526
527
        objective='regression',
        output=output
    )
528

529
530
531
532
533
534
535
    params = {
        "objective": "quantile",
        "alpha": alpha,
        "random_state": 42,
        "n_estimators": 10,
        "num_leaves": 10
    }
536

537
    dask_regressor = lgb.DaskLGBMRegressor(
538
        client=client,
539
540
        tree_learner_type='data_parallel',
        **params
James Lamb's avatar
James Lamb committed
541
    )
542
    dask_regressor = dask_regressor.fit(dX, dy, sample_weight=dw)
543
544
545
    p1 = dask_regressor.predict(dX).compute()
    q1 = np.count_nonzero(y < p1) / y.shape[0]

546
    local_regressor = lgb.LGBMRegressor(**params)
547
548
549
550
551
552
553
554
    local_regressor.fit(X, y, sample_weight=w)
    p2 = local_regressor.predict(X)
    q2 = np.count_nonzero(y < p2) / y.shape[0]

    # Quantiles should be right
    np.testing.assert_allclose(q1, alpha, atol=0.2)
    np.testing.assert_allclose(q2, alpha, atol=0.2)

555
556
557
558
559
560
561
562
563
564
565
566
    # be sure LightGBM actually used at least one categorical column,
    # and that it was correctly treated as a categorical feature
    if output == 'dataframe-with-categorical':
        cat_cols = [
            col for col in dX.columns
            if dX.dtypes[col].name == 'category'
        ]
        tree_df = dask_regressor.booster_.trees_to_dataframe()
        node_uses_cat_col = tree_df['split_feature'].isin(cat_cols)
        assert node_uses_cat_col.sum() > 0
        assert tree_df.loc[node_uses_cat_col, "decision_type"].unique()[0] == '=='

567
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)
568

569

570
@pytest.mark.parametrize('output', ['array', 'dataframe', 'dataframe-with-categorical'])
571
@pytest.mark.parametrize('group', [None, group_sizes])
572
def test_ranker(output, client, group):
573
    if output == 'dataframe-with-categorical':
574
575
        X, y, w, g, dX, dy, dw, dg = _create_data(
            objective='ranking',
576
577
578
579
580
581
            output=output,
            group=group,
            n_features=1,
            n_informative=1
        )
    else:
582
583
        X, y, w, g, dX, dy, dw, dg = _create_data(
            objective='ranking',
584
            output=output,
585
            group=group
586
        )
587

588
    # rebalance small dask.Array dataset for better performance.
589
590
591
592
593
594
595
596
    if output == 'array':
        dX = dX.persist()
        dy = dy.persist()
        dw = dw.persist()
        dg = dg.persist()
        _ = wait([dX, dy, dw, dg])
        client.rebalance()

597
    # use many trees + leaves to overfit, help ensure that Dask data-parallel strategy matches that of
598
    # serial learner. See https://github.com/microsoft/LightGBM/issues/3292#issuecomment-671288210.
599
600
601
602
603
604
    params = {
        "random_state": 42,
        "n_estimators": 50,
        "num_leaves": 20,
        "min_child_samples": 1
    }
605

606
    dask_ranker = lgb.DaskLGBMRanker(
607
        client=client,
608
609
        time_out=5,
        tree_learner_type='data_parallel',
610
        **params
611
    )
612
    dask_ranker = dask_ranker.fit(dX, dy, sample_weight=dw, group=dg)
613
614
    rnkvec_dask = dask_ranker.predict(dX)
    rnkvec_dask = rnkvec_dask.compute()
615
    p1_pred_leaf = dask_ranker.predict(dX, pred_leaf=True)
616
    rnkvec_dask_local = dask_ranker.to_local().predict(X)
617

618
    local_ranker = lgb.LGBMRanker(**params)
619
620
621
622
623
624
625
    local_ranker.fit(X, y, sample_weight=w, group=g)
    rnkvec_local = local_ranker.predict(X)

    # distributed ranker should be able to rank decently well and should
    # have high rank correlation with scores from serial ranker.
    dcor = spearmanr(rnkvec_dask, y).correlation
    assert dcor > 0.6
626
    assert spearmanr(rnkvec_dask, rnkvec_local).correlation > 0.8
627
    assert_eq(rnkvec_dask, rnkvec_dask_local)
628

629
630
631
632
633
634
635
636
637
638
639
    # pref_leaf values should have the right shape
    # and values that look like valid tree nodes
    pred_leaf_vals = p1_pred_leaf.compute()
    assert pred_leaf_vals.shape == (
        X.shape[0],
        dask_ranker.booster_.num_trees()
    )
    assert np.max(pred_leaf_vals) <= params['num_leaves']
    assert np.min(pred_leaf_vals) >= 0
    assert len(np.unique(pred_leaf_vals)) <= params['num_leaves']

640
641
642
643
644
645
646
647
648
649
650
651
    # be sure LightGBM actually used at least one categorical column,
    # and that it was correctly treated as a categorical feature
    if output == 'dataframe-with-categorical':
        cat_cols = [
            col for col in dX.columns
            if dX.dtypes[col].name == 'category'
        ]
        tree_df = dask_ranker.booster_.trees_to_dataframe()
        node_uses_cat_col = tree_df['split_feature'].isin(cat_cols)
        assert node_uses_cat_col.sum() > 0
        assert tree_df.loc[node_uses_cat_col, "decision_type"].unique()[0] == '=='

652
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)
653

654

655
@pytest.mark.parametrize('task', tasks)
656
def test_training_works_if_client_not_provided_or_set_after_construction(task, client):
657
658
659
660
661
    _, _, _, _, dX, dy, _, dg = _create_data(
        objective=task,
        output='array',
        group=None
    )
662
    model_factory = task_to_dask_factory[task]
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

    params = {
        "time_out": 5,
        "n_estimators": 1,
        "num_leaves": 2
    }

    # should be able to use the class without specifying a client
    dask_model = model_factory(**params)
    assert dask_model.client is None
    with pytest.raises(lgb.compat.LGBMNotFittedError, match='Cannot access property client_ before calling fit'):
        dask_model.client_

    dask_model.fit(dX, dy, group=dg)
    assert dask_model.fitted_
    assert dask_model.client is None
    assert dask_model.client_ == client

    preds = dask_model.predict(dX)
    assert isinstance(preds, da.Array)
    assert dask_model.fitted_
    assert dask_model.client is None
    assert dask_model.client_ == client

    local_model = dask_model.to_local()
    with pytest.raises(AttributeError):
        local_model.client
        local_model.client_

    # should be able to set client after construction
    dask_model = model_factory(**params)
    dask_model.set_params(client=client)
    assert dask_model.client == client

    with pytest.raises(lgb.compat.LGBMNotFittedError, match='Cannot access property client_ before calling fit'):
        dask_model.client_

    dask_model.fit(dX, dy, group=dg)
    assert dask_model.fitted_
    assert dask_model.client == client
    assert dask_model.client_ == client

    preds = dask_model.predict(dX)
    assert isinstance(preds, da.Array)
    assert dask_model.fitted_
    assert dask_model.client == client
    assert dask_model.client_ == client

    local_model = dask_model.to_local()
    with pytest.raises(AttributeError):
        local_model.client
        local_model.client_

    client.close(timeout=CLIENT_CLOSE_TIMEOUT)


@pytest.mark.parametrize('serializer', ['pickle', 'joblib', 'cloudpickle'])
720
@pytest.mark.parametrize('task', tasks)
721
@pytest.mark.parametrize('set_client', [True, False])
722
def test_model_and_local_version_are_picklable_whether_or_not_client_set_explicitly(serializer, task, set_client, tmp_path):
723

724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
    with LocalCluster(n_workers=2, threads_per_worker=1) as cluster1, Client(cluster1) as client1:
        # data on cluster1
        X_1, _, _, _, dX_1, dy_1, _, dg_1 = _create_data(
            objective=task,
            output='array',
            group=None
        )

        with LocalCluster(n_workers=2, threads_per_worker=1) as cluster2, Client(cluster2) as client2:
            # create identical data on cluster2
            X_2, _, _, _, dX_2, dy_2, _, dg_2 = _create_data(
                objective=task,
                output='array',
                group=None
            )
739

740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
            model_factory = task_to_dask_factory[task]

            params = {
                "time_out": 5,
                "n_estimators": 1,
                "num_leaves": 2
            }

            # at this point, the result of default_client() is client2 since it was the most recently
            # created. So setting client to client1 here to test that you can select a non-default client
            assert default_client() == client2
            if set_client:
                params.update({"client": client1})

            # unfitted model should survive pickling round trip, and pickling
            # shouldn't have side effects on the model object
            dask_model = model_factory(**params)
            local_model = dask_model.to_local()
            if set_client:
                assert dask_model.client == client1
760
            else:
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
                assert dask_model.client is None

            with pytest.raises(lgb.compat.LGBMNotFittedError, match='Cannot access property client_ before calling fit'):
                dask_model.client_

            assert "client" not in local_model.get_params()
            assert getattr(local_model, "client", None) is None

            tmp_file = str(tmp_path / "model-1.pkl")
            _pickle(
                obj=dask_model,
                filepath=tmp_file,
                serializer=serializer
            )
            model_from_disk = _unpickle(
                filepath=tmp_file,
                serializer=serializer
            )

            local_tmp_file = str(tmp_path / "local-model-1.pkl")
            _pickle(
                obj=local_model,
                filepath=local_tmp_file,
                serializer=serializer
            )
            local_model_from_disk = _unpickle(
                filepath=local_tmp_file,
                serializer=serializer
            )

            assert model_from_disk.client is None

            if set_client:
                assert dask_model.client == client1
            else:
                assert dask_model.client is None

            with pytest.raises(lgb.compat.LGBMNotFittedError, match='Cannot access property client_ before calling fit'):
                dask_model.client_

            # client will always be None after unpickling
            if set_client:
                from_disk_params = model_from_disk.get_params()
                from_disk_params.pop("client", None)
                dask_params = dask_model.get_params()
                dask_params.pop("client", None)
                assert from_disk_params == dask_params
            else:
                assert model_from_disk.get_params() == dask_model.get_params()
            assert local_model_from_disk.get_params() == local_model.get_params()

            # fitted model should survive pickling round trip, and pickling
            # shouldn't have side effects on the model object
            if set_client:
                dask_model.fit(dX_1, dy_1, group=dg_1)
            else:
                dask_model.fit(dX_2, dy_2, group=dg_2)
            local_model = dask_model.to_local()

            assert "client" not in local_model.get_params()
            with pytest.raises(AttributeError):
                local_model.client
                local_model.client_

            tmp_file2 = str(tmp_path / "model-2.pkl")
            _pickle(
                obj=dask_model,
                filepath=tmp_file2,
                serializer=serializer
            )
            fitted_model_from_disk = _unpickle(
                filepath=tmp_file2,
                serializer=serializer
            )

            local_tmp_file2 = str(tmp_path / "local-model-2.pkl")
            _pickle(
                obj=local_model,
                filepath=local_tmp_file2,
                serializer=serializer
            )
            local_fitted_model_from_disk = _unpickle(
                filepath=local_tmp_file2,
                serializer=serializer
            )

            if set_client:
                assert dask_model.client == client1
                assert dask_model.client_ == client1
            else:
                assert dask_model.client is None
                assert dask_model.client_ == default_client()
                assert dask_model.client_ == client2

            assert isinstance(fitted_model_from_disk, model_factory)
            assert fitted_model_from_disk.client is None
            assert fitted_model_from_disk.client_ == default_client()
            assert fitted_model_from_disk.client_ == client2

            # client will always be None after unpickling
            if set_client:
                from_disk_params = fitted_model_from_disk.get_params()
                from_disk_params.pop("client", None)
                dask_params = dask_model.get_params()
                dask_params.pop("client", None)
                assert from_disk_params == dask_params
            else:
                assert fitted_model_from_disk.get_params() == dask_model.get_params()
            assert local_fitted_model_from_disk.get_params() == local_model.get_params()

            if set_client:
                preds_orig = dask_model.predict(dX_1).compute()
                preds_loaded_model = fitted_model_from_disk.predict(dX_1).compute()
                preds_orig_local = local_model.predict(X_1)
                preds_loaded_model_local = local_fitted_model_from_disk.predict(X_1)
            else:
                preds_orig = dask_model.predict(dX_2).compute()
                preds_loaded_model = fitted_model_from_disk.predict(dX_2).compute()
                preds_orig_local = local_model.predict(X_2)
                preds_loaded_model_local = local_fitted_model_from_disk.predict(X_2)

            assert_eq(preds_orig, preds_loaded_model)
            assert_eq(preds_orig_local, preds_loaded_model_local)
884
885


886
887
888
889
def test_warns_and_continues_on_unrecognized_tree_learner(client):
    X = da.random.random((1e3, 10))
    y = da.random.random((1e3, 1))
    dask_regressor = lgb.DaskLGBMRegressor(
890
        client=client,
891
892
893
894
895
896
        time_out=5,
        tree_learner='some-nonsense-value',
        n_estimators=1,
        num_leaves=2
    )
    with pytest.warns(UserWarning, match='Parameter tree_learner set to some-nonsense-value'):
897
        dask_regressor = dask_regressor.fit(X, y)
898
899
900

    assert dask_regressor.fitted_

901
902
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)

903
904
905
906
907
908

def test_warns_but_makes_no_changes_for_feature_or_voting_tree_learner(client):
    X = da.random.random((1e3, 10))
    y = da.random.random((1e3, 1))
    for tree_learner in ['feature_parallel', 'voting']:
        dask_regressor = lgb.DaskLGBMRegressor(
909
            client=client,
910
911
912
913
914
915
            time_out=5,
            tree_learner=tree_learner,
            n_estimators=1,
            num_leaves=2
        )
        with pytest.warns(UserWarning, match='Support for tree_learner %s in lightgbm' % tree_learner):
916
            dask_regressor = dask_regressor.fit(X, y)
917
918
919
920

        assert dask_regressor.fitted_
        assert dask_regressor.get_params()['tree_learner'] == tree_learner

921
922
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)

923

924
925
926
927
928
929
930
931
@gen_cluster(client=True, timeout=None)
def test_errors(c, s, a, b):
    def f(part):
        raise Exception('foo')

    df = dd.demo.make_timeseries()
    df = df.map_partitions(f, meta=df._meta)
    with pytest.raises(Exception) as info:
932
        yield lgb.dask._train(
933
934
935
936
            client=c,
            data=df,
            label=df.x,
            params={},
937
            model_factory=lgb.LGBMClassifier
938
        )
939
        assert 'foo' in str(info.value)
940
941


942
943
944
945
946
947
948
949
950
951
952
953
954
955
@pytest.mark.parametrize('task', tasks)
@pytest.mark.parametrize('output', data_output)
def test_training_succeeds_even_if_some_workers_do_not_have_any_data(client, task, output):
    if task == 'ranking' and output == 'scipy_csr_matrix':
        pytest.skip('LGBMRanker is not currently tested on sparse matrices')

    def collection_to_single_partition(collection):
        """Merge the parts of a Dask collection into a single partition."""
        if collection is None:
            return
        if isinstance(collection, da.Array):
            return collection.rechunk(*collection.shape)
        return collection.repartition(npartitions=1)

956
957
958
959
960
    X, y, w, g, dX, dy, dw, dg = _create_data(
        objective=task,
        output=output,
        group=None
    )
961
962
963

    dask_model_factory = task_to_dask_factory[task]
    local_model_factory = task_to_local_factory[task]
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

    dX = collection_to_single_partition(dX)
    dy = collection_to_single_partition(dy)
    dw = collection_to_single_partition(dw)
    dg = collection_to_single_partition(dg)

    n_workers = len(client.scheduler_info()['workers'])
    assert n_workers > 1
    assert dX.npartitions == 1

    params = {
        'time_out': 5,
        'random_state': 42,
        'num_leaves': 10
    }

    dask_model = dask_model_factory(tree='data', client=client, **params)
    dask_model.fit(dX, dy, group=dg, sample_weight=dw)
    dask_preds = dask_model.predict(dX).compute()

    local_model = local_model_factory(**params)
    if task == 'ranking':
        local_model.fit(X, y, group=g, sample_weight=w)
    else:
        local_model.fit(X, y, sample_weight=w)
    local_preds = local_model.predict(X)

    assert assert_eq(dask_preds, local_preds)

    client.close(timeout=CLIENT_CLOSE_TIMEOUT)


996
997
998
999
1000
1001
@pytest.mark.parametrize('task', tasks)
@pytest.mark.parametrize('output', data_output)
def test_network_params_not_required_but_respected_if_given(client, task, output, listen_port):
    if task == 'ranking' and output == 'scipy_csr_matrix':
        pytest.skip('LGBMRanker is not currently tested on sparse matrices')

1002
1003
    client.wait_for_workers(2)

1004
1005
1006
1007
1008
1009
    _, _, _, _, dX, dy, _, dg = _create_data(
        objective=task,
        output=output,
        chunk_size=10,
        group=None
    )
1010
1011

    dask_model_factory = task_to_dask_factory[task]
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021

    # rebalance data to be sure that each worker has a piece of the data
    if output == 'array':
        client.rebalance()

    # model 1 - no network parameters given
    dask_model1 = dask_model_factory(
        n_estimators=5,
        num_leaves=5,
    )
1022
    dask_model1.fit(dX, dy, group=dg)
1023
1024
1025
1026
1027
1028
1029
    assert dask_model1.fitted_
    params = dask_model1.get_params()
    assert 'local_listen_port' not in params
    assert 'machines' not in params

    # model 2 - machines given
    n_workers = len(client.scheduler_info()['workers'])
1030
    open_ports = [lgb.dask._find_random_open_port() for _ in range(n_workers)]
1031
1032
1033
1034
1035
1036
1037
1038
1039
    dask_model2 = dask_model_factory(
        n_estimators=5,
        num_leaves=5,
        machines=",".join([
            "127.0.0.1:" + str(port)
            for port in open_ports
        ]),
    )

1040
    dask_model2.fit(dX, dy, group=dg)
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
    assert dask_model2.fitted_
    params = dask_model2.get_params()
    assert 'local_listen_port' not in params
    assert 'machines' in params

    # model 3 - local_listen_port given
    # training should fail because LightGBM will try to use the same
    # port for multiple worker processes on the same machine
    dask_model3 = dask_model_factory(
        n_estimators=5,
        num_leaves=5,
        local_listen_port=listen_port
    )
    error_msg = "has multiple Dask worker processes running on it"
    with pytest.raises(lgb.basic.LightGBMError, match=error_msg):
1056
        dask_model3.fit(dX, dy, group=dg)
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067

    client.close(timeout=CLIENT_CLOSE_TIMEOUT)


@pytest.mark.parametrize('task', tasks)
@pytest.mark.parametrize('output', data_output)
def test_machines_should_be_used_if_provided(task, output):
    if task == 'ranking' and output == 'scipy_csr_matrix':
        pytest.skip('LGBMRanker is not currently tested on sparse matrices')

    with LocalCluster(n_workers=2) as cluster, Client(cluster) as client:
1068
1069
1070
1071
1072
1073
        _, _, _, _, dX, dy, _, dg = _create_data(
            objective=task,
            output=output,
            chunk_size=10,
            group=None
        )
1074
1075

        dask_model_factory = task_to_dask_factory[task]
1076
1077
1078
1079
1080
1081

        # rebalance data to be sure that each worker has a piece of the data
        if output == 'array':
            client.rebalance()

        n_workers = len(client.scheduler_info()['workers'])
1082
        assert n_workers > 1
1083
        open_ports = [lgb.dask._find_random_open_port() for _ in range(n_workers)]
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
        dask_model = dask_model_factory(
            n_estimators=5,
            num_leaves=5,
            machines=",".join([
                "127.0.0.1:" + str(port)
                for port in open_ports
            ]),
        )

        # test that "machines" is actually respected by creating a socket that uses
        # one of the ports mentioned in "machines"
        error_msg = "Binding port %s failed" % open_ports[0]
        with pytest.raises(lgb.basic.LightGBMError, match=error_msg):
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.bind(('127.0.0.1', open_ports[0]))
1099
                dask_model.fit(dX, dy, group=dg)
1100

1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
        # an informative error should be raised if "machines" has duplicates
        one_open_port = lgb.dask._find_random_open_port()
        dask_model.set_params(
            machines=",".join([
                "127.0.0.1:" + str(one_open_port)
                for _ in range(n_workers)
            ])
        )
        with pytest.raises(ValueError, match="Found duplicates in 'machines'"):
            dask_model.fit(dX, dy, group=dg)

1112

1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
@pytest.mark.parametrize(
    "classes",
    [
        (lgb.DaskLGBMClassifier, lgb.LGBMClassifier),
        (lgb.DaskLGBMRegressor, lgb.LGBMRegressor),
        (lgb.DaskLGBMRanker, lgb.LGBMRanker)
    ]
)
def test_dask_classes_and_sklearn_equivalents_have_identical_constructors_except_client_arg(classes):
    dask_spec = inspect.getfullargspec(classes[0])
    sklearn_spec = inspect.getfullargspec(classes[1])
    assert dask_spec.varargs == sklearn_spec.varargs
    assert dask_spec.varkw == sklearn_spec.varkw
    assert dask_spec.kwonlyargs == sklearn_spec.kwonlyargs
    assert dask_spec.kwonlydefaults == sklearn_spec.kwonlydefaults

    # "client" should be the only different, and the final argument
    assert dask_spec.args[:-1] == sklearn_spec.args
    assert dask_spec.defaults[:-1] == sklearn_spec.defaults
    assert dask_spec.args[-1] == 'client'
    assert dask_spec.defaults[-1] is None
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161


@pytest.mark.parametrize(
    "methods",
    [
        (lgb.DaskLGBMClassifier.fit, lgb.LGBMClassifier.fit),
        (lgb.DaskLGBMClassifier.predict, lgb.LGBMClassifier.predict),
        (lgb.DaskLGBMClassifier.predict_proba, lgb.LGBMClassifier.predict_proba),
        (lgb.DaskLGBMRegressor.fit, lgb.LGBMRegressor.fit),
        (lgb.DaskLGBMRegressor.predict, lgb.LGBMRegressor.predict),
        (lgb.DaskLGBMRanker.fit, lgb.LGBMRanker.fit),
        (lgb.DaskLGBMRanker.predict, lgb.LGBMRanker.predict)
    ]
)
def test_dask_methods_and_sklearn_equivalents_have_similar_signatures(methods):
    dask_spec = inspect.getfullargspec(methods[0])
    sklearn_spec = inspect.getfullargspec(methods[1])
    dask_params = inspect.signature(methods[0]).parameters
    sklearn_params = inspect.signature(methods[1]).parameters
    assert dask_spec.args == sklearn_spec.args[:len(dask_spec.args)]
    assert dask_spec.varargs == sklearn_spec.varargs
    if sklearn_spec.varkw:
        assert dask_spec.varkw == sklearn_spec.varkw[:len(dask_spec.varkw)]
    assert dask_spec.kwonlyargs == sklearn_spec.kwonlyargs
    assert dask_spec.kwonlydefaults == sklearn_spec.kwonlydefaults
    for param in dask_spec.args:
        error_msg = f"param '{param}' has different default values in the methods"
        assert dask_params[param].default == sklearn_params[param].default, error_msg
1162
1163


1164
1165
1166
1167
1168
@pytest.mark.parametrize('task', tasks)
def test_training_succeeds_when_data_is_dataframe_and_label_is_column_array(
    task,
    client,
):
1169
1170
1171
1172
1173
    _, _, _, _, dX, dy, dw, dg = _create_data(
        objective=task,
        output='dataframe',
        group=None
    )
1174
1175
1176

    model_factory = task_to_dask_factory[task]

1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
    dy = dy.to_dask_array(lengths=True)
    dy_col_array = dy.reshape(-1, 1)
    assert len(dy_col_array.shape) == 2 and dy_col_array.shape[1] == 1

    params = {
        'n_estimators': 1,
        'num_leaves': 3,
        'random_state': 0,
        'time_out': 5
    }
    model = model_factory(**params)
    model.fit(dX, dy_col_array, sample_weight=dw, group=dg)
    assert model.fitted_
1190

1191
1192
1193
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)


1194
1195
@pytest.mark.parametrize('task', tasks)
@pytest.mark.parametrize('output', data_output)
1196
def test_init_score(task, output, client):
1197
1198
1199
    if task == 'ranking' and output == 'scipy_csr_matrix':
        pytest.skip('LGBMRanker is not currently tested on sparse matrices')

1200
1201
1202
1203
1204
    _, _, _, _, dX, dy, dw, dg = _create_data(
        objective=task,
        output=output,
        group=None
    )
1205
1206

    model_factory = task_to_dask_factory[task]
1207
1208
1209
1210
1211
1212
1213

    params = {
        'n_estimators': 1,
        'num_leaves': 2,
        'time_out': 5
    }
    init_score = random.random()
1214
1215
1216
1217
1218
1219
1220
    # init_scores must be a 1D array, even for multiclass classification
    # where you need to provide 1 score per class for each row in X
    # https://github.com/microsoft/LightGBM/issues/4046
    size_factor = 1
    if task == 'multiclass-classification':
        size_factor = 3  # number of classes

1221
    if output.startswith('dataframe'):
1222
        init_scores = dy.map_partitions(lambda x: pd.Series([init_score] * x.size * size_factor))
1223
    else:
1224
        init_scores = dy.map_blocks(lambda x: np.repeat(init_score, x.size * size_factor))
1225
1226
1227
1228
1229
1230
1231
1232
    model = model_factory(client=client, **params)
    model.fit(dX, dy, sample_weight=dw, init_score=init_scores, group=dg)
    # value of the root node is 0 when init_score is set
    assert model.booster_.trees_to_dataframe()['value'][0] == 0

    client.close(timeout=CLIENT_CLOSE_TIMEOUT)


1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
def sklearn_checks_to_run():
    check_names = [
        "check_estimator_get_tags_default_keys",
        "check_get_params_invariance",
        "check_set_params"
    ]
    for check_name in check_names:
        check_func = getattr(sklearn_checks, check_name, None)
        if check_func:
            yield check_func


def _tested_estimators():
    for Estimator in [lgb.DaskLGBMClassifier, lgb.DaskLGBMRegressor]:
        yield Estimator()


@pytest.mark.parametrize("estimator", _tested_estimators())
@pytest.mark.parametrize("check", sklearn_checks_to_run())
def test_sklearn_integration(estimator, check, client):
    estimator.set_params(local_listen_port=18000, time_out=5)
    name = type(estimator).__name__
    check(name, estimator)
    client.close(timeout=CLIENT_CLOSE_TIMEOUT)


# this test is separate because it takes a not-yet-constructed estimator
@pytest.mark.parametrize("estimator", list(_tested_estimators()))
def test_parameters_default_constructible(estimator):
1262
1263
1264
1265
1266
    name = estimator.__class__.__name__
    if sk_version >= parse_version("0.24"):
        Estimator = estimator
    else:
        Estimator = estimator.__class__
1267
    sklearn_checks.check_parameters_default_constructible(name, Estimator)
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307


@pytest.mark.parametrize('task', tasks)
@pytest.mark.parametrize('output', data_output)
def test_predict_with_raw_score(task, output, client):
    if task == 'ranking' and output == 'scipy_csr_matrix':
        pytest.skip('LGBMRanker is not currently tested on sparse matrices')

    _, _, _, _, dX, dy, _, dg = _create_data(
        objective=task,
        output=output,
        group=None
    )

    model_factory = task_to_dask_factory[task]
    params = {
        'client': client,
        'n_estimators': 1,
        'num_leaves': 2,
        'time_out': 5,
        'min_sum_hessian': 0
    }
    model = model_factory(**params)
    model.fit(dX, dy, group=dg)
    raw_predictions = model.predict(dX, raw_score=True).compute()

    trees_df = model.booster_.trees_to_dataframe()
    leaves_df = trees_df[trees_df.node_depth == 2]
    if task == 'multiclass-classification':
        for i in range(model.n_classes_):
            class_df = leaves_df[leaves_df.tree_index == i]
            assert set(raw_predictions[:, i]) == set(class_df['value'])
    else:
        assert set(raw_predictions) == set(leaves_df['value'])

    if task.endswith('classification'):
        pred_proba_raw = model.predict_proba(dX, raw_score=True).compute()
        assert_eq(raw_predictions, pred_proba_raw)

    client.close(timeout=CLIENT_CLOSE_TIMEOUT)