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

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
15
from .sklearn import LGBMModel


16
def check_not_tuple_of_2_elements(obj, obj_name='obj'):
wxchan's avatar
wxchan committed
17
    """check object is not tuple or does not have 2 elements"""
18
19
    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
20
21


22
23
24
25
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,
wxchan's avatar
wxchan committed
26
                    ignore_zero=True, figsize=None, grid=True, **kwargs):
27
    """Plot model's feature importances.
28
29
30

    Parameters
    ----------
wxchan's avatar
wxchan committed
31
    booster : Booster or LGBMModel
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
        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)
56
        Max number of top features displayed on plot.
57
58
59
60
61
62
63
64
65
        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.
    grid : bool, optional (default=True)
        Whether to add a grid for axes.
    **kwargs : other parameters
        Other parameters passed to ``ax.barh()``.
66
67
68

    Returns
    -------
69
70
    ax : matplotlib.axes.Axes
        The plot with model's feature importances.
71
72
73
74
    """
    try:
        import matplotlib.pyplot as plt
    except ImportError:
wxchan's avatar
wxchan committed
75
        raise ImportError('You must install matplotlib to plot importance.')
76
77

    if isinstance(booster, LGBMModel):
wxchan's avatar
wxchan committed
78
79
80
81
82
83
        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()
84
85

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

wxchan's avatar
wxchan committed
88
    tuples = sorted(zip(feature_name, importance), key=lambda x: x[1])
89
90
91
92
93
94
95
    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:]
    labels, values = zip(*tuples)

    if ax is None:
96
97
        if figsize is not None:
            check_not_tuple_of_2_elements(figsize, 'figsize')
wxchan's avatar
wxchan committed
98
        _, ax = plt.subplots(1, 1, figsize=figsize)
99
100
101
102
103
104
105
106
107
108
109

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

    for x, y in zip(values, ylocs):
        ax.text(x + 1, y, x, va='center')

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

    if xlim is not None:
110
        check_not_tuple_of_2_elements(xlim, 'xlim')
111
112
113
114
115
    else:
        xlim = (0, max(values) * 1.1)
    ax.set_xlim(xlim)

    if ylim is not None:
116
        check_not_tuple_of_2_elements(ylim, 'ylim')
117
118
119
120
121
122
123
124
125
126
127
128
    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
129
130


131
132
133
134
135
136
137
138
139
140
def plot_metric(booster, metric=None, dataset_names=None,
                ax=None, xlim=None, ylim=None,
                title='Metric during training',
                xlabel='Iterations', ylabel='auto',
                figsize=None, grid=True):
    """Plot one metric during training.

    Parameters
    ----------
    booster : dict or LGBMModel
141
142
        Dictionary returned from ``lightgbm.train()`` or LGBMModel instance.
    metric : string or None, optional (default=None)
143
144
        The metric name to plot.
        Only one metric supported because different metrics have various scales.
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
        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.
    grid : bool, optional (default=True)
        Whether to add a grid for axes.
170
171
172

    Returns
    -------
173
174
    ax : matplotlib.axes.Axes
        The plot with metric's history over the training.
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    """
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        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:
            check_not_tuple_of_2_elements(figsize, 'figsize')
        _, ax = plt.subplots(1, 1, figsize=figsize)

    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
210
211
            msg = """more than one metric available, picking one to plot."""
            warnings.warn(msg, stacklevel=2)
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
        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)
    x_ = range(num_iteration)
    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:
        check_not_tuple_of_2_elements(xlim, 'xlim')
    else:
        xlim = (0, num_iteration)
    ax.set_xlim(xlim)

    if ylim is not None:
        check_not_tuple_of_2_elements(ylim, 'ylim')
    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


255
def _to_graphviz(tree_info, show_info, feature_names, precision=None,
256
257
258
259
260
261
262
263
                 name=None, comment=None, filename=None, directory=None,
                 format=None, engine=None, encoding=None, graph_attr=None,
                 node_attr=None, edge_attr=None, body=None, strict=False):
    """Convert specified tree to graphviz instance.

    See:
      - http://graphviz.readthedocs.io/en/stable/api.html#digraph
    """
264
265
266
267
    try:
        from graphviz import Digraph
    except ImportError:
        raise ImportError('You must install graphviz to plot tree.')
wxchan's avatar
wxchan committed
268

269
270
271
    def float2str(value, precision=None):
        return "{0:.{1}f}".format(value, precision) if precision is not None else str(value)

wxchan's avatar
wxchan committed
272
273
274
    def add(root, parent=None, decision=None):
        """recursively add node or edge"""
        if 'split_index' in root:  # non-leaf
275
            name = 'split{0}'.format(root['split_index'])
wxchan's avatar
wxchan committed
276
            if feature_names is not None:
277
                label = 'split_feature_name: {0}'.format(feature_names[root['split_feature']])
wxchan's avatar
wxchan committed
278
            else:
279
280
                label = 'split_feature_index: {0}'.format(root['split_feature'])
            label += r'\nthreshold: {0}'.format(float2str(root['threshold'], precision))
wxchan's avatar
wxchan committed
281
            for info in show_info:
282
283
284
285
                if info in {'split_gain', 'internal_value'}:
                    label += r'\n{0}: {1}'.format(info, float2str(root[info], precision))
                elif info == 'internal_count':
                    label += r'\n{0}: {1}'.format(info, root[info])
wxchan's avatar
wxchan committed
286
            graph.node(name, label=label)
287
            if root['decision_type'] == '<=':
288
                l_dec, r_dec = '<=', '>'
289
            elif root['decision_type'] == '==':
290
291
292
                l_dec, r_dec = 'is', "isn't"
            else:
                raise ValueError('Invalid decision type in tree model.')
wxchan's avatar
wxchan committed
293
294
295
            add(root['left_child'], name, l_dec)
            add(root['right_child'], name, r_dec)
        else:  # leaf
296
297
298
            name = 'leaf{0}'.format(root['leaf_index'])
            label = 'leaf_index: {0}'.format(root['leaf_index'])
            label += r'\nleaf_value: {0}'.format(float2str(root['leaf_value'], precision))
wxchan's avatar
wxchan committed
299
            if 'leaf_count' in show_info:
300
                label += r'\nleaf_count: {0}'.format(root['leaf_count'])
wxchan's avatar
wxchan committed
301
302
303
304
            graph.node(name, label=label)
        if parent is not None:
            graph.edge(parent, name, decision)

305
306
307
    graph = Digraph(name=name, comment=comment, filename=filename, directory=directory,
                    format=format, engine=engine, encoding=encoding, graph_attr=graph_attr,
                    node_attr=node_attr, edge_attr=edge_attr, body=body, strict=strict)
wxchan's avatar
wxchan committed
308
    add(tree_info['tree_structure'])
309
310
311
312

    return graph


313
def create_tree_digraph(booster, tree_index=0, show_info=None, precision=None,
314
315
316
                        name=None, comment=None, filename=None, directory=None,
                        format=None, engine=None, encoding=None, graph_attr=None,
                        node_attr=None, edge_attr=None, body=None, strict=False):
317
    """Create a digraph representation of specified tree.
318

319
320
321
322
    Note
    ----
    For more information please visit
    http://graphviz.readthedocs.io/en/stable/api.html#digraph.
323

324
325
    Parameters
    ----------
326
    booster : Booster or LGBMModel
327
        Booster or LGBMModel instance.
328
329
    tree_index : int, optional (default=0)
        The index of a target tree to convert.
330
331
    show_info : list of strings or None, optional (default=None)
        What information should be shown in nodes.
332
        Possible values of list items: 'split_gain', 'internal_value', 'internal_count', 'leaf_count'.
333
334
    precision : int or None, optional (default=None)
        Used to restrict the display of floating point values to a certain precision.
335
    name : string or None, optional (default=None)
336
        Graph name used in the source code.
337
    comment : string or None, optional (default=None)
338
        Comment added to the first line of the source.
339
340
341
342
    filename : string or None, optional (default=None)
        Filename for saving the source.
        If None, ``name`` + '.gv' is used.
    directory : string or None, optional (default=None)
343
        (Sub)directory for source saving and rendering.
344
    format : string or None, optional (default=None)
345
        Rendering output format ('pdf', 'png', ...).
346
    engine : string or None, optional (default=None)
347
        Layout command used ('dot', 'neato', ...).
348
    encoding : string or None, optional (default=None)
349
        Encoding for saving the source.
350
    graph_attr : dict, list of tuples or None, optional (default=None)
351
        Mapping of (attribute, value) pairs set for the graph.
352
353
        All attributes and values must be strings or bytes-like objects.
    node_attr : dict, list of tuples or None, optional (default=None)
354
        Mapping of (attribute, value) pairs set for all nodes.
355
356
        All attributes and values must be strings or bytes-like objects.
    edge_attr : dict, list of tuples or None, optional (default=None)
357
        Mapping of (attribute, value) pairs set for all edges.
358
        All attributes and values must be strings or bytes-like objects.
359
360
361
362
    body : list of strings or None, optional (default=None)
        Lines to add to the graph body.
    strict : bool, optional (default=False)
        Whether rendering should merge multi-edges.
363
364
365

    Returns
    -------
366
367
    graph : graphviz.Digraph
        The digraph representation of specified tree.
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
    """
    if isinstance(booster, LGBMModel):
        booster = booster.booster_
    elif not isinstance(booster, Booster):
        raise TypeError('booster must be Booster or LGBMModel.')

    model = booster.dump_model()
    tree_infos = model['tree_info']
    if 'feature_names' in model:
        feature_names = model['feature_names']
    else:
        feature_names = None

    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 = []

389
    graph = _to_graphviz(tree_info, show_info, feature_names, precision,
390
391
392
                         name=name, comment=comment, filename=filename, directory=directory,
                         format=format, engine=engine, encoding=encoding, graph_attr=graph_attr,
                         node_attr=node_attr, edge_attr=edge_attr, body=body, strict=strict)
393

wxchan's avatar
wxchan committed
394
395
396
397
398
    return graph


def plot_tree(booster, ax=None, tree_index=0, figsize=None,
              graph_attr=None, node_attr=None, edge_attr=None,
399
              show_info=None, precision=None):
wxchan's avatar
wxchan committed
400
401
402
403
    """Plot specified tree.

    Parameters
    ----------
404
405
406
407
408
409
410
411
    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
412
        Figure size.
413
    graph_attr : dict, list of tuples or None, optional (default=None)
414
        Mapping of (attribute, value) pairs set for the graph.
415
416
        All attributes and values must be strings or bytes-like objects.
    node_attr : dict, list of tuples or None, optional (default=None)
wxchan's avatar
wxchan committed
417
        Mapping of (attribute, value) pairs set for all nodes.
418
419
        All attributes and values must be strings or bytes-like objects.
    edge_attr : dict, list of tuples or None, optional (default=None)
wxchan's avatar
wxchan committed
420
        Mapping of (attribute, value) pairs set for all edges.
421
422
423
        All attributes and values must be strings or bytes-like objects.
    show_info : list of strings or None, optional (default=None)
        What information should be shown in nodes.
424
        Possible values of list items: 'split_gain', 'internal_value', 'internal_count', 'leaf_count'.
425
426
    precision : int or None, optional (default=None)
        Used to restrict the display of floating point values to a certain precision.
wxchan's avatar
wxchan committed
427
428
429

    Returns
    -------
430
431
    ax : matplotlib.axes.Axes
        The plot with single tree.
wxchan's avatar
wxchan committed
432
433
434
435
436
437
438
439
    """
    try:
        import matplotlib.pyplot as plt
        import matplotlib.image as image
    except ImportError:
        raise ImportError('You must install matplotlib to plot tree.')

    if ax is None:
440
441
        if figsize is not None:
            check_not_tuple_of_2_elements(figsize, 'figsize')
wxchan's avatar
wxchan committed
442
443
        _, ax = plt.subplots(1, 1, figsize=figsize)

444
445
446
    graph = create_tree_digraph(
        booster=booster,
        tree_index=tree_index,
447
448
        show_info=show_info,
        precision=precision,
449
450
        graph_attr=graph_attr,
        node_attr=node_attr,
451
        edge_attr=edge_attr
452
    )
wxchan's avatar
wxchan committed
453
454

    s = BytesIO()
455
    s.write(graph.pipe(format='png'))
wxchan's avatar
wxchan committed
456
457
458
459
460
461
    s.seek(0)
    img = image.imread(s)

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