Python-Intro.rst 6.17 KB
Newer Older
1
Python-package Introduction
2
3
4
5
6
7
===========================

This document gives a basic walkthrough of LightGBM Python-package.

**List of other helpful links**

8
-  `Python Examples <https://github.com/microsoft/LightGBM/tree/master/examples/python-guide>`__
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

-  `Python API <./Python-API.rst>`__

-  `Parameters Tuning <./Parameters-Tuning.rst>`__

Install
-------

Install Python-package dependencies,
``setuptools``, ``wheel``, ``numpy`` and ``scipy`` are required, ``scikit-learn`` is required for sklearn interface and recommended:

::

    pip install setuptools wheel numpy scipy scikit-learn -U

Refer to `Python-package`_ folder for the installation guide.

To verify your installation, try to ``import lightgbm`` in Python:

::

    import lightgbm as lgb

Data Interface
--------------

35
The LightGBM Python module can load data from:
36

Darío Hereñú's avatar
Darío Hereñú committed
37
-  libsvm/tsv/csv/txt format file
38

39
-  NumPy 2D array(s), pandas DataFrame, H2O DataTable's Frame, SciPy sparse matrix
40
41
42
43
44

-  LightGBM binary file

The data is stored in a ``Dataset`` object.

45
46
47
48
49
50
Many of the examples in this page use functionality from ``numpy``. To run the examples, be sure to import ``numpy`` in your session.

.. code:: python

    import numpy as np

51
52
53
54
55
56
57
58
59
60
61
62
63
64
**To load a libsvm text file or a LightGBM binary file into Dataset:**

.. code:: python

    train_data = lgb.Dataset('train.svm.bin')

**To load a numpy array into Dataset:**

.. code:: python

    data = np.random.rand(500, 10)  # 500 entities, each contains 10 features
    label = np.random.randint(2, size=500)  # binary target
    train_data = lgb.Dataset(data, label=label)

65
**To load a scipy.sparse.csr\_matrix array into Dataset:**
66
67
68

.. code:: python

69
    import scipy
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    csr = scipy.sparse.csr_matrix((dat, (row, col)))
    train_data = lgb.Dataset(csr)

**Saving Dataset into a LightGBM binary file will make loading faster:**

.. code:: python

    train_data = lgb.Dataset('train.svm.txt')
    train_data.save_binary('train.bin')

**Create validation data:**

.. code:: python

84
    validation_data = train_data.create_valid('validation.svm')
85
86
87
88
89

or

.. code:: python

90
    validation_data = lgb.Dataset('validation.svm', reference=train_data)
91
92
93
94
95
96
97
98
99
100

In LightGBM, the validation data should be aligned with training data.

**Specific feature names and categorical features:**

.. code:: python

    train_data = lgb.Dataset(data, label=label, feature_name=['c1', 'c2', 'c3'], categorical_feature=['c3'])

LightGBM can use categorical features as input directly.
Darío Hereñú's avatar
Darío Hereñú committed
101
It doesn't need to convert to one-hot coding, and is much faster than one-hot coding (about 8x speed-up).
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

**Note**: You should convert your categorical features to ``int`` type before you construct ``Dataset``.

**Weights can be set when needed:**

.. code:: python

    w = np.random.rand(500, )
    train_data = lgb.Dataset(data, label=label, weight=w)

or

.. code:: python

    train_data = lgb.Dataset(data, label=label)
    w = np.random.rand(500, )
    train_data.set_weight(w)

And you can use ``Dataset.set_init_score()`` to set initial score, and ``Dataset.set_group()`` to set group/query data for ranking tasks.

122
**Memory efficient usage:**
123

Harry Moreno's avatar
Harry Moreno committed
124
125
126
The ``Dataset`` object in LightGBM is very memory-efficient, it only needs to save discrete bins.
However, Numpy/Array/Pandas object is memory expensive.
If you are concerned about your memory consumption, you can save memory by:
127

Harry Moreno's avatar
Harry Moreno committed
128
1. Set ``free_raw_data=True`` (default is ``True``) when constructing the ``Dataset``
129

Harry Moreno's avatar
Harry Moreno committed
130
2. Explicitly set ``raw_data=None`` after the ``Dataset`` has been constructed
131
132
133
134
135
136

3. Call ``gc``

Setting Parameters
------------------

137
LightGBM can use a dictionary to set `Parameters <./Parameters.rst>`__.
138
139
140
141
142
143
For instance:

-  Booster parameters:

   .. code:: python

144
       param = {'num_leaves': 31, 'num_trees': 100, 'objective': 'binary'}
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
       param['metric'] = 'auc'

-  You can also specify multiple eval metrics:

   .. code:: python

       param['metric'] = ['auc', 'binary_logloss']

Training
--------

Training a model requires a parameter list and data set:

.. code:: python

    num_round = 10
161
    bst = lgb.train(param, train_data, num_round, valid_sets=[validation_data])
162
163
164
165
166
167
168
169
170
171
172
173
174

After training, the model can be saved:

.. code:: python

    bst.save_model('model.txt')

The trained model can also be dumped to JSON format:

.. code:: python

    json_model = bst.dump_model()

Nikita Titov's avatar
Nikita Titov committed
175
A saved model can be loaded:
176
177
178

.. code:: python

179
    bst = lgb.Booster(model_file='model.txt')  # init model
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194

CV
--

Training with 5-fold CV:

.. code:: python

    num_round = 10
    lgb.cv(param, train_data, num_round, nfold=5)

Early Stopping
--------------

If you have a validation set, you can use early stopping to find the optimal number of boosting rounds.
195
Early stopping requires at least one set in ``valid_sets``. If there is more than one, it will use all of them except the training data:
196
197
198
199
200
201
202

.. code:: python

    bst = lgb.train(param, train_data, num_round, valid_sets=valid_sets, early_stopping_rounds=10)
    bst.save_model('model.txt', num_iteration=bst.best_iteration)

The model will train until the validation score stops improving.
203
Validation score needs to improve at least every ``early_stopping_rounds`` to continue training.
204

205
The index of iteration that has the best performance will be saved in the ``best_iteration`` field if early stopping logic is enabled by setting ``early_stopping_rounds``.
206
Note that ``train()`` will return a model from the best iteration.
207

208
209
This works with both metrics to minimize (L2, log loss, etc.) and to maximize (NDCG, AUC, etc.).
Note that if you specify more than one evaluation metric, all of them will be used for early stopping.
210
However, you can change this behavior and make LightGBM check only the first metric for early stopping by creating ``early_stopping`` callback with ``first_metric_only=True``.
211
212
213
214

Prediction
----------

215
A model that has been trained or loaded can perform predictions on datasets:
216
217
218
219
220
221
222
223
224
225
226
227
228

.. code:: python

    # 7 entities, each contains 10 features
    data = np.random.rand(7, 10)
    ypred = bst.predict(data)

If early stopping is enabled during training, you can get predictions from the best iteration with ``bst.best_iteration``:

.. code:: python

    ypred = bst.predict(data, num_iteration=bst.best_iteration)

229
.. _Python-package: https://github.com/microsoft/LightGBM/tree/master/python-package