plotting.py 24 KB
Newer Older
1
2
# coding: utf-8
# pylint: disable = C0103
3
"""Plotting library."""
4
from __future__ import absolute_import, division
5

wxchan's avatar
wxchan committed
6
import warnings
7
from copy import deepcopy
wxchan's avatar
wxchan committed
8
9
from io import BytesIO

10
11
import numpy as np

wxchan's avatar
wxchan committed
12
from .basic import Booster
13
14
from .compat import (MATPLOTLIB_INSTALLED, GRAPHVIZ_INSTALLED, LGBMDeprecationWarning,
                     range_, zip_, string_type)
15
16
17
from .sklearn import LGBMModel


18
19
def _check_not_tuple_of_2_elements(obj, obj_name='obj'):
    """Check object is not tuple or does not have 2 elements."""
20
21
    if not isinstance(obj, tuple) or len(obj) != 2:
        raise TypeError('%s must be a tuple of 2 elements.' % obj_name)
wxchan's avatar
wxchan committed
22
23


24
25
26
27
28
29
def _float2str(value, precision=None):
    return ("{0:.{1}f}".format(value, precision)
            if precision is not None and not isinstance(value, string_type)
            else str(value))


30
31
32
33
def plot_importance(booster, ax=None, height=0.2,
                    xlim=None, ylim=None, title='Feature importance',
                    xlabel='Feature importance', ylabel='Features',
                    importance_type='split', max_num_features=None,
34
                    ignore_zero=True, figsize=None, dpi=None, grid=True,
35
                    precision=3, **kwargs):
36
    """Plot model's feature importances.
37
38
39

    Parameters
    ----------
wxchan's avatar
wxchan committed
40
    booster : Booster or LGBMModel
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
        Booster or LGBMModel instance which feature importance should be plotted.
    ax : matplotlib.axes.Axes or None, optional (default=None)
        Target axes instance.
        If None, new figure and axes will be created.
    height : float, optional (default=0.2)
        Bar height, passed to ``ax.barh()``.
    xlim : tuple of 2 elements or None, optional (default=None)
        Tuple passed to ``ax.xlim()``.
    ylim : tuple of 2 elements or None, optional (default=None)
        Tuple passed to ``ax.ylim()``.
    title : string or None, optional (default="Feature importance")
        Axes title.
        If None, title is disabled.
    xlabel : string or None, optional (default="Feature importance")
        X-axis title label.
        If None, title is disabled.
    ylabel : string or None, optional (default="Features")
        Y-axis title label.
        If None, title is disabled.
    importance_type : string, optional (default="split")
        How the importance is calculated.
        If "split", result contains numbers of times the feature is used in a model.
        If "gain", result contains total gains of splits which use the feature.
    max_num_features : int or None, optional (default=None)
65
        Max number of top features displayed on plot.
66
67
68
69
70
        If None or <1, all features will be displayed.
    ignore_zero : bool, optional (default=True)
        Whether to ignore features with zero importance.
    figsize : tuple of 2 elements or None, optional (default=None)
        Figure size.
71
72
    dpi : int or None, optional (default=None)
        Resolution of the figure.
73
74
    grid : bool, optional (default=True)
        Whether to add a grid for axes.
75
    precision : int or None, optional (default=3)
76
        Used to restrict the display of floating point values to a certain precision.
77
    **kwargs
78
        Other parameters passed to ``ax.barh()``.
79
80
81

    Returns
    -------
82
83
    ax : matplotlib.axes.Axes
        The plot with model's feature importances.
84
    """
85
    if MATPLOTLIB_INSTALLED:
86
        import matplotlib.pyplot as plt
87
    else:
wxchan's avatar
wxchan committed
88
        raise ImportError('You must install matplotlib to plot importance.')
89
90

    if isinstance(booster, LGBMModel):
wxchan's avatar
wxchan committed
91
92
93
94
95
96
        booster = booster.booster_
    elif not isinstance(booster, Booster):
        raise TypeError('booster must be Booster or LGBMModel.')

    importance = booster.feature_importance(importance_type=importance_type)
    feature_name = booster.feature_name()
97
98

    if not len(importance):
99
        raise ValueError("Booster's feature_importance is empty.")
100

101
    tuples = sorted(zip_(feature_name, importance), key=lambda x: x[1])
102
103
104
105
    if ignore_zero:
        tuples = [x for x in tuples if x[1] > 0]
    if max_num_features is not None and max_num_features > 0:
        tuples = tuples[-max_num_features:]
106
    labels, values = zip_(*tuples)
107
108

    if ax is None:
109
        if figsize is not None:
110
            _check_not_tuple_of_2_elements(figsize, 'figsize')
111
        _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)
112
113
114
115

    ylocs = np.arange(len(values))
    ax.barh(ylocs, values, align='center', height=height, **kwargs)

116
    for x, y in zip_(values, ylocs):
117
118
119
        ax.text(x + 1, y,
                _float2str(x, precision) if importance_type == 'gain' else x,
                va='center')
120
121
122
123
124

    ax.set_yticks(ylocs)
    ax.set_yticklabels(labels)

    if xlim is not None:
125
        _check_not_tuple_of_2_elements(xlim, 'xlim')
126
127
128
129
130
    else:
        xlim = (0, max(values) * 1.1)
    ax.set_xlim(xlim)

    if ylim is not None:
131
        _check_not_tuple_of_2_elements(ylim, 'ylim')
132
133
134
135
136
137
138
139
140
141
142
143
    else:
        ylim = (-1, len(values))
    ax.set_ylim(ylim)

    if title is not None:
        ax.set_title(title)
    if xlabel is not None:
        ax.set_xlabel(xlabel)
    if ylabel is not None:
        ax.set_ylabel(ylabel)
    ax.grid(grid)
    return ax
wxchan's avatar
wxchan committed
144
145


146
147
148
149
def plot_split_value_histogram(booster, feature, bins=None, ax=None, width_coef=0.8,
                               xlim=None, ylim=None,
                               title='Split value histogram for feature with @index/name@ @feature@',
                               xlabel='Feature split value', ylabel='Count',
150
                               figsize=None, dpi=None, grid=True, **kwargs):
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
    """Plot split value histogram for the specified feature of the model.

    Parameters
    ----------
    booster : Booster or LGBMModel
        Booster or LGBMModel instance of which feature split value histogram should be plotted.
    feature : int or string
        The feature name or index the histogram is plotted for.
        If int, interpreted as index.
        If string, interpreted as name.
    bins : int, string or None, optional (default=None)
        The maximum number of bins.
        If None, the number of bins equals number of unique split values.
        If string, it should be one from the list of the supported values by ``numpy.histogram()`` function.
    ax : matplotlib.axes.Axes or None, optional (default=None)
        Target axes instance.
        If None, new figure and axes will be created.
    width_coef : float, optional (default=0.8)
        Coefficient for histogram bar width.
    xlim : tuple of 2 elements or None, optional (default=None)
        Tuple passed to ``ax.xlim()``.
    ylim : tuple of 2 elements or None, optional (default=None)
        Tuple passed to ``ax.ylim()``.
    title : string or None, optional (default="Split value histogram for feature with @index/name@ @feature@")
        Axes title.
        If None, title is disabled.
        @feature@ placeholder can be used, and it will be replaced with the value of ``feature`` parameter.
        @index/name@ placeholder can be used,
        and it will be replaced with ``index`` word in case of ``int`` type ``feature`` parameter
        or ``name`` word in case of ``string`` type ``feature`` parameter.
    xlabel : string or None, optional (default="Feature split value")
        X-axis title label.
        If None, title is disabled.
    ylabel : string or None, optional (default="Count")
        Y-axis title label.
        If None, title is disabled.
    figsize : tuple of 2 elements or None, optional (default=None)
        Figure size.
189
190
    dpi : int or None, optional (default=None)
        Resolution of the figure.
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
    grid : bool, optional (default=True)
        Whether to add a grid for axes.
    **kwargs
        Other parameters passed to ``ax.bar()``.

    Returns
    -------
    ax : matplotlib.axes.Axes
        The plot with specified model's feature split value histogram.
    """
    if MATPLOTLIB_INSTALLED:
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
    else:
        raise ImportError('You must install matplotlib to plot split value histogram.')

    if isinstance(booster, LGBMModel):
        booster = booster.booster_
    elif not isinstance(booster, Booster):
        raise TypeError('booster must be Booster or LGBMModel.')

    hist, bins = booster.get_split_value_histogram(feature=feature, bins=bins, xgboost_style=False)
    if np.count_nonzero(hist) == 0:
        raise ValueError('Cannot plot split value histogram, '
                         'because feature {} was not used in splitting'.format(feature))
    width = width_coef * (bins[1] - bins[0])
    centred = (bins[:-1] + bins[1:]) / 2

    if ax is None:
        if figsize is not None:
            _check_not_tuple_of_2_elements(figsize, 'figsize')
222
        _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)
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

    ax.bar(centred, hist, align='center', width=width, **kwargs)

    if xlim is not None:
        _check_not_tuple_of_2_elements(xlim, 'xlim')
    else:
        range_result = bins[-1] - bins[0]
        xlim = (bins[0] - range_result * 0.2, bins[-1] + range_result * 0.2)
    ax.set_xlim(xlim)

    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    if ylim is not None:
        _check_not_tuple_of_2_elements(ylim, 'ylim')
    else:
        ylim = (0, max(hist) * 1.1)
    ax.set_ylim(ylim)

    if title is not None:
        title = title.replace('@feature@', str(feature))
        title = title.replace('@index/name@', ('name' if isinstance(feature, string_type) else 'index'))
        ax.set_title(title)
    if xlabel is not None:
        ax.set_xlabel(xlabel)
    if ylabel is not None:
        ax.set_ylabel(ylabel)
    ax.grid(grid)
    return ax


252
253
254
255
def plot_metric(booster, metric=None, dataset_names=None,
                ax=None, xlim=None, ylim=None,
                title='Metric during training',
                xlabel='Iterations', ylabel='auto',
256
                figsize=None, dpi=None, grid=True):
257
258
259
260
261
    """Plot one metric during training.

    Parameters
    ----------
    booster : dict or LGBMModel
262
263
        Dictionary returned from ``lightgbm.train()`` or LGBMModel instance.
    metric : string or None, optional (default=None)
264
265
        The metric name to plot.
        Only one metric supported because different metrics have various scales.
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
        If None, first metric picked from dictionary (according to hashcode).
    dataset_names : list of strings or None, optional (default=None)
        List of the dataset names which are used to calculate metric to plot.
        If None, all datasets are used.
    ax : matplotlib.axes.Axes or None, optional (default=None)
        Target axes instance.
        If None, new figure and axes will be created.
    xlim : tuple of 2 elements or None, optional (default=None)
        Tuple passed to ``ax.xlim()``.
    ylim : tuple of 2 elements or None, optional (default=None)
        Tuple passed to ``ax.ylim()``.
    title : string or None, optional (default="Metric during training")
        Axes title.
        If None, title is disabled.
    xlabel : string or None, optional (default="Iterations")
        X-axis title label.
        If None, title is disabled.
    ylabel : string or None, optional (default="auto")
        Y-axis title label.
        If 'auto', metric name is used.
        If None, title is disabled.
    figsize : tuple of 2 elements or None, optional (default=None)
        Figure size.
289
290
    dpi : int or None, optional (default=None)
        Resolution of the figure.
291
292
    grid : bool, optional (default=True)
        Whether to add a grid for axes.
293
294
295

    Returns
    -------
296
297
    ax : matplotlib.axes.Axes
        The plot with metric's history over the training.
298
    """
299
    if MATPLOTLIB_INSTALLED:
300
        import matplotlib.pyplot as plt
301
    else:
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
        raise ImportError('You must install matplotlib to plot metric.')

    if isinstance(booster, LGBMModel):
        eval_results = deepcopy(booster.evals_result_)
    elif isinstance(booster, dict):
        eval_results = deepcopy(booster)
    else:
        raise TypeError('booster must be dict or LGBMModel.')

    num_data = len(eval_results)

    if not num_data:
        raise ValueError('eval results cannot be empty.')

    if ax is None:
        if figsize is not None:
318
            _check_not_tuple_of_2_elements(figsize, 'figsize')
319
        _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)
320
321
322
323
324
325
326
327
328
329
330
331
332

    if dataset_names is None:
        dataset_names = iter(eval_results.keys())
    elif not isinstance(dataset_names, (list, tuple, set)) or not dataset_names:
        raise ValueError('dataset_names should be iterable and cannot be empty')
    else:
        dataset_names = iter(dataset_names)

    name = next(dataset_names)  # take one as sample
    metrics_for_one = eval_results[name]
    num_metric = len(metrics_for_one)
    if metric is None:
        if num_metric > 1:
wxchan's avatar
wxchan committed
333
334
            msg = """more than one metric available, picking one to plot."""
            warnings.warn(msg, stacklevel=2)
335
336
337
338
339
340
        metric, results = metrics_for_one.popitem()
    else:
        if metric not in metrics_for_one:
            raise KeyError('No given metric in eval results.')
        results = metrics_for_one[metric]
    num_iteration, max_result, min_result = len(results), max(results), min(results)
341
    x_ = range_(num_iteration)
342
343
344
345
346
347
348
349
350
351
352
    ax.plot(x_, results, label=name)

    for name in dataset_names:
        metrics_for_one = eval_results[name]
        results = metrics_for_one[metric]
        max_result, min_result = max(max(results), max_result), min(min(results), min_result)
        ax.plot(x_, results, label=name)

    ax.legend(loc='best')

    if xlim is not None:
353
        _check_not_tuple_of_2_elements(xlim, 'xlim')
354
355
356
357
358
    else:
        xlim = (0, num_iteration)
    ax.set_xlim(xlim)

    if ylim is not None:
359
        _check_not_tuple_of_2_elements(ylim, 'ylim')
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
    else:
        range_result = max_result - min_result
        ylim = (min_result - range_result * 0.2, max_result + range_result * 0.2)
    ax.set_ylim(ylim)

    if ylabel == 'auto':
        ylabel = metric

    if title is not None:
        ax.set_title(title)
    if xlabel is not None:
        ax.set_xlabel(xlabel)
    if ylabel is not None:
        ax.set_ylabel(ylabel)
    ax.grid(grid)
    return ax


378
def _to_graphviz(tree_info, show_info, feature_names, precision=3, constraints=None, **kwargs):
379
380
381
    """Convert specified tree to graphviz instance.

    See:
382
      - https://graphviz.readthedocs.io/en/stable/api.html#digraph
383
    """
384
    if GRAPHVIZ_INSTALLED:
385
        from graphviz import Digraph
386
    else:
387
        raise ImportError('You must install graphviz to plot tree.')
wxchan's avatar
wxchan committed
388

389
    def add(root, total_count, parent=None, decision=None):
390
        """Recursively add node or edge."""
wxchan's avatar
wxchan committed
391
        if 'split_index' in root:  # non-leaf
392
393
            l_dec = 'yes'
            r_dec = 'no'
394
            if root['decision_type'] == '<=':
395
396
                lte_symbol = "&#8804;"
                operator = lte_symbol
397
            elif root['decision_type'] == '==':
398
                operator = "="
399
400
            else:
                raise ValueError('Invalid decision type in tree model.')
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
            name = 'split{0}'.format(root['split_index'])
            if feature_names is not None:
                label = '<B>{0}</B> {1} '.format(feature_names[root['split_feature']], operator)
            else:
                label = 'feature <B>{0}</B> {1} '.format(root['split_feature'], operator)
            label += '<B>{0}</B>'.format(_float2str(root['threshold'], precision))
            for info in ['split_gain', 'internal_value', 'internal_weight', "internal_count", "data_percentage"]:
                if info in show_info:
                    output = info.split('_')[-1]
                    if info in {'split_gain', 'internal_value', 'internal_weight'}:
                        label += '<br/>{0} {1}'.format(_float2str(root[info], precision), output)
                    elif info == 'internal_count':
                        label += '<br/>{0}: {1}'.format(output, root[info])
                    elif info == "data_percentage":
                        label += '<br/>{0}% of data'.format(_float2str(root['internal_count'] / total_count * 100, 2))

            fillcolor = "white"
            style = ""
            if constraints:
                if constraints[root['split_feature']] == 1:
                    fillcolor = "#ddffdd"  # light green
                if constraints[root['split_feature']] == -1:
                    fillcolor = "#ffdddd"  # light red
                style = "filled"
            label = "<" + label + ">"
            graph.node(name, label=label, shape="rectangle", style=style, fillcolor=fillcolor)
            add(root['left_child'], total_count, name, l_dec)
            add(root['right_child'], total_count, name, r_dec)
wxchan's avatar
wxchan committed
429
        else:  # leaf
430
            name = 'leaf{0}'.format(root['leaf_index'])
431
432
            label = 'leaf {0}: '.format(root['leaf_index'])
            label += '<B>{0}</B>'.format(_float2str(root['leaf_value'], precision))
433
            if 'leaf_weight' in show_info:
434
435
436
437
438
439
                label += '<br/>{0} weight'.format(_float2str(root['leaf_weight'], precision))
            if 'leaf_count' in show_info:
                label += '<br/>count: {0}'.format(root['leaf_count'])
            if "data_percentage" in show_info:
                label += '<br/>{0}% of data'.format(_float2str(root['leaf_count'] / total_count * 100, 2))
            label = "<" + label + ">"
wxchan's avatar
wxchan committed
440
441
442
443
            graph.node(name, label=label)
        if parent is not None:
            graph.edge(parent, name, decision)

444
    graph = Digraph(**kwargs)
445
446
447
448
    graph.attr("graph", nodesep="0.05", ranksep="0.3", rankdir="LR")
    if "internal_count" in tree_info['tree_structure']:
        add(tree_info['tree_structure'], tree_info['tree_structure']["internal_count"])
    else:
449
        raise Exception("Cannot plot trees with no split")
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468

    if constraints:
        # "#ddffdd" is light green, "#ffdddd" is light red
        legend = """<
            <TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4">
             <TR>
              <TD COLSPAN="2"><B>Monotone constraints</B></TD>
             </TR>
             <TR>
              <TD>Increasing</TD>
              <TD BGCOLOR="#ddffdd"></TD>
             </TR>
             <TR>
              <TD>Decreasing</TD>
              <TD BGCOLOR="#ffdddd"></TD>
             </TR>
            </TABLE>
           >"""
        graph.node("legend", label=legend, shape="rectangle", color="white")
469
470
471
    return graph


472
def create_tree_digraph(booster, tree_index=0, show_info=None, precision=3,
473
474
475
                        old_name=None, old_comment=None, old_filename=None, old_directory=None,
                        old_format=None, old_engine=None, old_encoding=None, old_graph_attr=None,
                        old_node_attr=None, old_edge_attr=None, old_body=None, old_strict=False, **kwargs):
476
    """Create a digraph representation of specified tree.
477

Nikita Titov's avatar
Nikita Titov committed
478
479
480
481
    .. note::

        For more information please visit
        https://graphviz.readthedocs.io/en/stable/api.html#digraph.
482

483
484
    Parameters
    ----------
485
    booster : Booster or LGBMModel
486
        Booster or LGBMModel instance to be converted.
487
488
    tree_index : int, optional (default=0)
        The index of a target tree to convert.
489
490
    show_info : list of strings or None, optional (default=None)
        What information should be shown in nodes.
491
        Possible values of list items:
492
493
494
        'split_gain', 'internal_value', 'internal_count', 'internal_weight',
        'leaf_count', 'leaf_weight', 'data_percentage'.
    precision : int or None, optional (default=3)
495
        Used to restrict the display of floating point values to a certain precision.
496
    **kwargs
497
498
        Other parameters passed to ``Digraph`` constructor.
        Check https://graphviz.readthedocs.io/en/stable/api.html#digraph for the full list of supported parameters.
499
500
501

    Returns
    -------
502
503
    graph : graphviz.Digraph
        The digraph representation of specified tree.
504
505
506
507
508
509
    """
    if isinstance(booster, LGBMModel):
        booster = booster.booster_
    elif not isinstance(booster, Booster):
        raise TypeError('booster must be Booster or LGBMModel.')

510
511
512
513
514
    for param_name in ['old_name', 'old_comment', 'old_filename', 'old_directory',
                       'old_format', 'old_engine', 'old_encoding', 'old_graph_attr',
                       'old_node_attr', 'old_edge_attr', 'old_body']:
        param = locals().get(param_name)
        if param is not None:
515
            warnings.warn('{0} parameter is deprecated and will be removed in 2.4 version.\n'
516
517
518
519
520
                          'Please use **kwargs to pass {1} parameter.'.format(param_name, param_name[4:]),
                          LGBMDeprecationWarning)
            if param_name[4:] not in kwargs:
                kwargs[param_name[4:]] = param
    if locals().get('strict'):
521
        warnings.warn('old_strict parameter is deprecated and will be removed in 2.4 version.\n'
522
523
524
525
526
                      'Please use **kwargs to pass strict parameter.',
                      LGBMDeprecationWarning)
        if 'strict' not in kwargs:
            kwargs['strict'] = True

527
528
529
530
531
532
533
    model = booster.dump_model()
    tree_infos = model['tree_info']
    if 'feature_names' in model:
        feature_names = model['feature_names']
    else:
        feature_names = None

534
535
    monotone_constraints = model.get('monotone_constraints', None)

536
537
538
539
540
541
542
543
    if tree_index < len(tree_infos):
        tree_info = tree_infos[tree_index]
    else:
        raise IndexError('tree_index is out of range.')

    if show_info is None:
        show_info = []

544
    graph = _to_graphviz(tree_info, show_info, feature_names, precision, monotone_constraints, **kwargs)
545

wxchan's avatar
wxchan committed
546
547
548
    return graph


549
def plot_tree(booster, ax=None, tree_index=0, figsize=None, dpi=None,
550
              old_graph_attr=None, old_node_attr=None, old_edge_attr=None,
551
              show_info=None, precision=3, **kwargs):
wxchan's avatar
wxchan committed
552
553
    """Plot specified tree.

Nikita Titov's avatar
Nikita Titov committed
554
555
556
557
    .. note::

        It is preferable to use ``create_tree_digraph()`` because of its lossless quality
        and returned objects can be also rendered and displayed directly inside a Jupyter notebook.
558

wxchan's avatar
wxchan committed
559
560
    Parameters
    ----------
561
562
563
564
565
566
567
568
    booster : Booster or LGBMModel
        Booster or LGBMModel instance to be plotted.
    ax : matplotlib.axes.Axes or None, optional (default=None)
        Target axes instance.
        If None, new figure and axes will be created.
    tree_index : int, optional (default=0)
        The index of a target tree to plot.
    figsize : tuple of 2 elements or None, optional (default=None)
wxchan's avatar
wxchan committed
569
        Figure size.
570
571
    dpi : int or None, optional (default=None)
        Resolution of the figure.
572
573
    show_info : list of strings or None, optional (default=None)
        What information should be shown in nodes.
574
        Possible values of list items:
575
576
577
        'split_gain', 'internal_value', 'internal_count', 'internal_weight',
        'leaf_count', 'leaf_weight', 'data_percentage'.
    precision : int or None, optional (default=3)
578
        Used to restrict the display of floating point values to a certain precision.
579
    **kwargs
580
581
        Other parameters passed to ``Digraph`` constructor.
        Check https://graphviz.readthedocs.io/en/stable/api.html#digraph for the full list of supported parameters.
wxchan's avatar
wxchan committed
582
583
584

    Returns
    -------
585
586
    ax : matplotlib.axes.Axes
        The plot with single tree.
wxchan's avatar
wxchan committed
587
    """
588
    if MATPLOTLIB_INSTALLED:
wxchan's avatar
wxchan committed
589
590
        import matplotlib.pyplot as plt
        import matplotlib.image as image
591
    else:
wxchan's avatar
wxchan committed
592
593
        raise ImportError('You must install matplotlib to plot tree.')

594
595
596
    for param_name in ['old_graph_attr', 'old_node_attr', 'old_edge_attr']:
        param = locals().get(param_name)
        if param is not None:
597
            warnings.warn('{0} parameter is deprecated and will be removed in 2.4 version.\n'
598
599
600
601
602
                          'Please use **kwargs to pass {1} parameter.'.format(param_name, param_name[4:]),
                          LGBMDeprecationWarning)
            if param_name[4:] not in kwargs:
                kwargs[param_name[4:]] = param

wxchan's avatar
wxchan committed
603
    if ax is None:
604
        if figsize is not None:
605
            _check_not_tuple_of_2_elements(figsize, 'figsize')
606
        _, ax = plt.subplots(1, 1, figsize=figsize, dpi=dpi)
wxchan's avatar
wxchan committed
607

608
609
    graph = create_tree_digraph(booster=booster, tree_index=tree_index,
                                show_info=show_info, precision=precision, **kwargs)
wxchan's avatar
wxchan committed
610
611

    s = BytesIO()
612
    s.write(graph.pipe(format='png'))
wxchan's avatar
wxchan committed
613
614
615
616
617
618
    s.seek(0)
    img = image.imread(s)

    ax.imshow(img)
    ax.axis('off')
    return ax