config.h 42.4 KB
Newer Older
1
2
3
4
5
6
7
/*!
 * Copyright (c) 2016 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 *
 * \note
 * desc and descl2 fields must be written in reStructuredText format
 */
Guolin Ke's avatar
Guolin Ke committed
8
9
10
#ifndef LIGHTGBM_CONFIG_H_
#define LIGHTGBM_CONFIG_H_

11
12
#include <LightGBM/export.h>
#include <LightGBM/meta.h>
Guolin Ke's avatar
Guolin Ke committed
13
14
15
16
17
#include <LightGBM/utils/common.h>
#include <LightGBM/utils/log.h>

#include <string>
#include <algorithm>
Guolin Ke's avatar
Guolin Ke committed
18
#include <memory>
19
20
21
#include <unordered_map>
#include <unordered_set>
#include <vector>
Guolin Ke's avatar
Guolin Ke committed
22
23
24

namespace LightGBM {

Guolin Ke's avatar
Guolin Ke committed
25
26
27
28
/*! \brief Types of tasks */
enum TaskType {
  kTrain, kPredict, kConvertModel, KRefitTree
};
29
const int kDefaultNumLeaves = 31;
Guolin Ke's avatar
Guolin Ke committed
30

Guolin Ke's avatar
Guolin Ke committed
31
struct Config {
Nikita Titov's avatar
Nikita Titov committed
32
 public:
Guolin Ke's avatar
Guolin Ke committed
33
  std::string ToString() const;
Guolin Ke's avatar
Guolin Ke committed
34
35
36
37
  /*!
  * \brief Get string value by specific name of key
  * \param params Store the key and value for params
  * \param name Name of key
Hui Xue's avatar
Hui Xue committed
38
  * \param out Value will assign to out if key exists
Guolin Ke's avatar
Guolin Ke committed
39
40
  * \return True if key exists
  */
Guolin Ke's avatar
Guolin Ke committed
41
  inline static bool GetString(
Guolin Ke's avatar
Guolin Ke committed
42
43
44
45
46
47
48
    const std::unordered_map<std::string, std::string>& params,
    const std::string& name, std::string* out);

  /*!
  * \brief Get int value by specific name of key
  * \param params Store the key and value for params
  * \param name Name of key
Hui Xue's avatar
Hui Xue committed
49
  * \param out Value will assign to out if key exists
Guolin Ke's avatar
Guolin Ke committed
50
51
  * \return True if key exists
  */
Guolin Ke's avatar
Guolin Ke committed
52
  inline static bool GetInt(
Guolin Ke's avatar
Guolin Ke committed
53
54
55
56
    const std::unordered_map<std::string, std::string>& params,
    const std::string& name, int* out);

  /*!
57
  * \brief Get double value by specific name of key
Guolin Ke's avatar
Guolin Ke committed
58
59
  * \param params Store the key and value for params
  * \param name Name of key
Hui Xue's avatar
Hui Xue committed
60
  * \param out Value will assign to out if key exists
Guolin Ke's avatar
Guolin Ke committed
61
62
  * \return True if key exists
  */
Guolin Ke's avatar
Guolin Ke committed
63
  inline static bool GetDouble(
Guolin Ke's avatar
Guolin Ke committed
64
    const std::unordered_map<std::string, std::string>& params,
65
    const std::string& name, double* out);
Guolin Ke's avatar
Guolin Ke committed
66
67
68
69
70

  /*!
  * \brief Get bool value by specific name of key
  * \param params Store the key and value for params
  * \param name Name of key
Hui Xue's avatar
Hui Xue committed
71
  * \param out Value will assign to out if key exists
Guolin Ke's avatar
Guolin Ke committed
72
73
  * \return True if key exists
  */
Guolin Ke's avatar
Guolin Ke committed
74
  inline static bool GetBool(
Guolin Ke's avatar
Guolin Ke committed
75
76
    const std::unordered_map<std::string, std::string>& params,
    const std::string& name, bool* out);
77

wxchan's avatar
wxchan committed
78
  static void KV2Map(std::unordered_map<std::string, std::string>& params, const char* kv);
79
  static std::unordered_map<std::string, std::string> Str2Map(const char* parameters);
Guolin Ke's avatar
Guolin Ke committed
80

Guolin Ke's avatar
Guolin Ke committed
81
  #pragma region Parameters
82

Guolin Ke's avatar
Guolin Ke committed
83
84
85
  #pragma region Core Parameters

  // [doc-only]
86
87
  // alias = config_file
  // desc = path of config file
88
  // desc = **Note**: can be used only in CLI version
Guolin Ke's avatar
Guolin Ke committed
89
90
91
  std::string config = "";

  // [doc-only]
92
93
94
95
96
97
98
99
  // type = enum
  // default = train
  // options = train, predict, convert_model, refit
  // alias = task_type
  // desc = ``train``, for training, aliases: ``training``
  // desc = ``predict``, for prediction, aliases: ``prediction``, ``test``
  // desc = ``convert_model``, for converting model file into if-else format, see more information in `IO Parameters <#io-parameters>`__
  // desc = ``refit``, for refitting existing models with new data, aliases: ``refit_tree``
Guolin Ke's avatar
Guolin Ke committed
100
  // desc = **Note**: can be used only in CLI version; for language-specific packages you can use the correspondent functions
Guolin Ke's avatar
Guolin Ke committed
101
102
103
  TaskType task = TaskType::kTrain;

  // [doc-only]
104
105
106
107
108
109
110
111
112
113
114
115
116
  // type = enum
  // options = regression, regression_l1, huber, fair, poisson, quantile, mape, gammma, tweedie, binary, multiclass, multiclassova, xentropy, xentlambda, lambdarank
  // alias = objective_type, app, application
  // desc = regression application
  // descl2 = ``regression_l2``, L2 loss, aliases: ``regression``, ``mean_squared_error``, ``mse``, ``l2_root``, ``root_mean_squared_error``, ``rmse``
  // descl2 = ``regression_l1``, L1 loss, aliases: ``mean_absolute_error``, ``mae``
  // descl2 = ``huber``, `Huber loss <https://en.wikipedia.org/wiki/Huber_loss>`__
  // descl2 = ``fair``, `Fair loss <https://www.kaggle.com/c/allstate-claims-severity/discussion/24520>`__
  // descl2 = ``poisson``, `Poisson regression <https://en.wikipedia.org/wiki/Poisson_regression>`__
  // descl2 = ``quantile``, `Quantile regression <https://en.wikipedia.org/wiki/Quantile_regression>`__
  // descl2 = ``mape``, `MAPE loss <https://en.wikipedia.org/wiki/Mean_absolute_percentage_error>`__, aliases: ``mean_absolute_percentage_error``
  // descl2 = ``gamma``, Gamma regression with log-link. It might be useful, e.g., for modeling insurance claims severity, or for any target that might be `gamma-distributed <https://en.wikipedia.org/wiki/Gamma_distribution#Applications>`__
  // descl2 = ``tweedie``, Tweedie regression with log-link. It might be useful, e.g., for modeling total loss in insurance, or for any target that might be `tweedie-distributed <https://en.wikipedia.org/wiki/Tweedie_distribution#Applications>`__
117
  // desc = ``binary``, binary `log loss <https://en.wikipedia.org/wiki/Cross_entropy>`__ classification (or logistic regression). Requires labels in {0, 1}; see ``cross-entropy`` application for general probability labels in [0, 1]
118
119
120
121
122
123
124
125
126
127
128
129
  // desc = multi-class classification application
  // descl2 = ``multiclass``, `softmax <https://en.wikipedia.org/wiki/Softmax_function>`__ objective function, aliases: ``softmax``
  // descl2 = ``multiclassova``, `One-vs-All <https://en.wikipedia.org/wiki/Multiclass_classification#One-vs.-rest>`__ binary objective function, aliases: ``multiclass_ova``, ``ova``, ``ovr``
  // descl2 = ``num_class`` should be set as well
  // desc = cross-entropy application
  // descl2 = ``xentropy``, objective function for cross-entropy (with optional linear weights), aliases: ``cross_entropy``
  // descl2 = ``xentlambda``, alternative parameterization of cross-entropy, aliases: ``cross_entropy_lambda``
  // descl2 = label is anything in interval [0, 1]
  // desc = ``lambdarank``, `lambdarank <https://papers.nips.cc/paper/2971-learning-to-rank-with-nonsmooth-cost-functions.pdf>`__ application
  // descl2 = label should be ``int`` type in lambdarank tasks, and larger number represents the higher relevance (e.g. 0:bad, 1:fair, 2:good, 3:perfect)
  // descl2 = `label_gain <#objective-parameters>`__ can be used to set the gain (weight) of ``int`` label
  // descl2 = all values in ``label`` must be smaller than number of elements in ``label_gain``
Guolin Ke's avatar
Guolin Ke committed
130
131
132
  std::string objective = "regression";

  // [doc-only]
133
134
  // type = enum
  // alias = boosting_type, boost
135
136
137
  // options = gbdt, gbrt, rf, random_forest, dart, goss
  // desc = ``gbdt``, traditional Gradient Boosting Decision Tree, aliases: ``gbrt``
  // desc = ``rf``, Random Forest, aliases: ``random_forest``
138
139
  // desc = ``dart``, `Dropouts meet Multiple Additive Regression Trees <https://arxiv.org/abs/1505.01866>`__
  // desc = ``goss``, Gradient-based One-Side Sampling
Guolin Ke's avatar
Guolin Ke committed
140
141
  std::string boosting = "gbdt";

142
  // alias = train, train_data, train_data_file, data_filename
143
  // desc = path of training data, LightGBM will train from this data
144
  // desc = **Note**: can be used only in CLI version
Guolin Ke's avatar
Guolin Ke committed
145
146
  std::string data = "";

147
  // alias = test, valid_data, valid_data_file, test_data, test_data_file, valid_filenames
148
  // default = ""
149
  // desc = path(s) of validation/test data, LightGBM will output metrics for these data
150
  // desc = support multiple validation data, separated by ``,``
151
  // desc = **Note**: can be used only in CLI version
Guolin Ke's avatar
Guolin Ke committed
152
153
  std::vector<std::string> valid;

154
  // alias = num_iteration, n_iter, num_tree, num_trees, num_round, num_rounds, num_boost_round, n_estimators
155
156
157
  // check = >=0
  // desc = number of boosting iterations
  // desc = **Note**: internally, LightGBM constructs ``num_class * num_iterations`` trees for multi-class classification problems
Guolin Ke's avatar
Guolin Ke committed
158
  int num_iterations = 100;
Guolin Ke's avatar
Guolin Ke committed
159

160
  // alias = shrinkage_rate, eta
161
  // check = >0.0
162
163
  // desc = shrinkage rate
  // desc = in ``dart``, it also affects on normalization weights of dropped trees
Guolin Ke's avatar
Guolin Ke committed
164
165
  double learning_rate = 0.1;

166
  // default = 31
167
  // alias = num_leaf, max_leaves, max_leaf
168
169
  // check = >1
  // desc = max number of leaves in one tree
Guolin Ke's avatar
Guolin Ke committed
170
171
172
  int num_leaves = kDefaultNumLeaves;

  // [doc-only]
173
174
  // type = enum
  // options = serial, feature, data, voting
175
  // alias = tree, tree_type, tree_learner_type
176
177
178
179
180
  // desc = ``serial``, single machine tree learner
  // desc = ``feature``, feature parallel tree learner, aliases: ``feature_parallel``
  // desc = ``data``, data parallel tree learner, aliases: ``data_parallel``
  // desc = ``voting``, voting parallel tree learner, aliases: ``voting_parallel``
  // desc = refer to `Parallel Learning Guide <./Parallel-Learning-Guide.rst>`__ to get more details
Guolin Ke's avatar
Guolin Ke committed
181
182
  std::string tree_learner = "serial";

183
  // alias = num_thread, nthread, nthreads, n_jobs
Guolin Ke's avatar
Guolin Ke committed
184
  // desc = number of threads for LightGBM
185
186
187
188
189
  // desc = ``0`` means default number of threads in OpenMP
  // desc = for the best speed, set this to the number of **real CPU cores**, not the number of threads (most CPUs use `hyper-threading <https://en.wikipedia.org/wiki/Hyper-threading>`__ to generate 2 threads per CPU core)
  // desc = do not set it too large if your dataset is small (for instance, do not use 64 threads for a dataset with 10,000 rows)
  // desc = be aware a task manager or any similar CPU monitoring tool might report that cores not being fully utilized. **This is normal**
  // desc = for parallel learning, do not use all CPU cores because this will cause poor performance for the network communication
Guolin Ke's avatar
Guolin Ke committed
190
191
192
  int num_threads = 0;

  // [doc-only]
193
194
  // type = enum
  // options = cpu, gpu
195
  // alias = device
196
197
198
199
  // desc = device for the tree learning, you can use GPU to achieve the faster learning
  // desc = **Note**: it is recommended to use the smaller ``max_bin`` (e.g. 63) to get the better speed up
  // desc = **Note**: for the faster speed, GPU uses 32-bit float point to sum up by default, so this may affect the accuracy for some tasks. You can set ``gpu_use_dp=true`` to enable 64-bit float point, but it will slow down the training
  // desc = **Note**: refer to `Installation Guide <./Installation-Guide.rst#build-gpu-version>`__ to build LightGBM with GPU support
Guolin Ke's avatar
Guolin Ke committed
200
201
202
  std::string device_type = "cpu";

  // [doc-only]
203
  // alias = random_seed, random_state
204
205
206
207
  // default = None
  // desc = this seed is used to generate other seeds, e.g. ``data_random_seed``, ``feature_fraction_seed``, etc.
  // desc = by default, this seed is unused in favor of default values of other seeds
  // desc = this seed has lower priority in comparison with other seeds, which means that it will be overridden, if you set other seeds explicitly
Guolin Ke's avatar
Guolin Ke committed
208
209
210
211
212
213
  int seed = 0;

  #pragma endregion

  #pragma region Learning Control Parameters

214
215
  // desc = limit the max depth for tree model. This is used to deal with over-fitting when ``#data`` is small. Tree still grows leaf-wise
  // desc = ``< 0`` means no limit
Guolin Ke's avatar
Guolin Ke committed
216
217
218
  int max_depth = -1;

  // alias = min_data_per_leaf, min_data, min_child_samples
219
220
  // check = >=0
  // desc = minimal number of data in one leaf. Can be used to deal with over-fitting
Guolin Ke's avatar
Guolin Ke committed
221
222
  int min_data_in_leaf = 20;

223
224
225
  // alias = min_sum_hessian_per_leaf, min_sum_hessian, min_hessian, min_child_weight
  // check = >=0.0
  // desc = minimal sum hessian in one leaf. Like ``min_data_in_leaf``, it can be used to deal with over-fitting
Guolin Ke's avatar
Guolin Ke committed
226
227
  double min_sum_hessian_in_leaf = 1e-3;

228
229
230
231
232
233
234
  // alias = sub_row, subsample, bagging
  // check = >0.0
  // check = <=1.0
  // desc = like ``feature_fraction``, but this will randomly select part of data without resampling
  // desc = can be used to speed up training
  // desc = can be used to deal with over-fitting
  // desc = **Note**: to enable bagging, ``bagging_freq`` should be set to a non zero value as well
Guolin Ke's avatar
Guolin Ke committed
235
236
  double bagging_fraction = 1.0;

237
238
239
240
  // alias = subsample_freq
  // desc = frequency for bagging
  // desc = ``0`` means disable bagging; ``k`` means perform bagging at every ``k`` iteration
  // desc = **Note**: to enable bagging, ``bagging_fraction`` should be set to value smaller than ``1.0`` as well
Guolin Ke's avatar
Guolin Ke committed
241
242
243
244
245
246
247
  int bagging_freq = 0;

  // alias = bagging_fraction_seed
  // desc = random seed for bagging
  int bagging_seed = 3;

  // alias = sub_feature, colsample_bytree
248
249
250
251
252
  // check = >0.0
  // check = <=1.0
  // desc = LightGBM will randomly select part of features on each iteration if ``feature_fraction`` smaller than ``1.0``. For example, if you set it to ``0.8``, LightGBM will select 80% of features before training each tree
  // desc = can be used to speed up training
  // desc = can be used to deal with over-fitting
Guolin Ke's avatar
Guolin Ke committed
253
254
  double feature_fraction = 1.0;

255
  // desc = random seed for ``feature_fraction``
Guolin Ke's avatar
Guolin Ke committed
256
257
  int feature_fraction_seed = 2;

258
259
260
  // alias = early_stopping_rounds, early_stopping
  // desc = will stop training if one metric of one validation data doesn't improve in last ``early_stopping_round`` rounds
  // desc = ``<= 0`` means disable
Guolin Ke's avatar
Guolin Ke committed
261
262
  int early_stopping_round = 0;

263
264
265
266
  // alias = max_tree_output, max_leaf_output
  // desc = used to limit the max output of tree leaves
  // desc = ``<= 0`` means no constraint
  // desc = the final max output of leaves is ``learning_rate * max_delta_step``
Guolin Ke's avatar
Guolin Ke committed
267
268
  double max_delta_step = 0.0;

269
270
271
  // alias = reg_alpha
  // check = >=0.0
  // desc = L1 regularization
Guolin Ke's avatar
Guolin Ke committed
272
273
  double lambda_l1 = 0.0;

274
  // alias = reg_lambda, lambda
275
  // check = >=0.0
Guolin Ke's avatar
Guolin Ke committed
276
277
278
  // desc = L2 regularization
  double lambda_l2 = 0.0;

279
280
281
  // alias = min_split_gain
  // check = >=0.0
  // desc = the minimal gain to perform split
Guolin Ke's avatar
Guolin Ke committed
282
283
  double min_gain_to_split = 0.0;

284
  // alias = rate_drop
285
286
287
  // check = >=0.0
  // check = <=1.0
  // desc = used only in ``dart``
288
  // desc = dropout rate: a fraction of previous trees to drop during the dropout
Guolin Ke's avatar
Guolin Ke committed
289
290
  double drop_rate = 0.1;

291
  // desc = used only in ``dart``
292
  // desc = max number of dropped trees during one boosting iteration
293
  // desc = ``<=0`` means no limit
Guolin Ke's avatar
Guolin Ke committed
294
295
  int max_drop = 50;

296
297
298
  // check = >=0.0
  // check = <=1.0
  // desc = used only in ``dart``
299
  // desc = probability of skipping the dropout procedure during a boosting iteration
Guolin Ke's avatar
Guolin Ke committed
300
301
  double skip_drop = 0.5;

302
303
  // desc = used only in ``dart``
  // desc = set this to ``true``, if you want to use xgboost dart mode
Guolin Ke's avatar
Guolin Ke committed
304
305
  bool xgboost_dart_mode = false;

306
307
  // desc = used only in ``dart``
  // desc = set this to ``true``, if you want to use uniform drop
Guolin Ke's avatar
Guolin Ke committed
308
309
  bool uniform_drop = false;

310
311
  // desc = used only in ``dart``
  // desc = random seed to choose dropping models
Guolin Ke's avatar
Guolin Ke committed
312
313
  int drop_seed = 4;

314
315
316
317
  // check = >=0.0
  // check = <=1.0
  // desc = used only in ``goss``
  // desc = the retain ratio of large gradient data
Guolin Ke's avatar
Guolin Ke committed
318
319
  double top_rate = 0.2;

320
321
322
323
  // check = >=0.0
  // check = <=1.0
  // desc = used only in ``goss``
  // desc = the retain ratio of small gradient data
Guolin Ke's avatar
Guolin Ke committed
324
325
  double other_rate = 0.1;

326
327
  // check = >0
  // desc = minimal number of data per categorical group
Guolin Ke's avatar
Guolin Ke committed
328
329
  int min_data_per_group = 100;

330
331
332
  // check = >0
  // desc = used for the categorical features
  // desc = limit the max threshold points in categorical features
Guolin Ke's avatar
Guolin Ke committed
333
334
  int max_cat_threshold = 32;

335
336
337
338
  // check = >=0.0
  // desc = used for the categorical features
  // desc = L2 regularization in categorcial split
  double cat_l2 = 10.0;
Guolin Ke's avatar
Guolin Ke committed
339

340
341
342
343
  // check = >=0.0
  // desc = used for the categorical features
  // desc = this can reduce the effect of noises in categorical features, especially for categories with few data
  double cat_smooth = 10.0;
344

345
346
  // check = >0
  // desc = when number of categories of one feature smaller than or equal to ``max_cat_to_onehot``, one-vs-other split algorithm will be used
Guolin Ke's avatar
Guolin Ke committed
347
348
349
  int max_cat_to_onehot = 4;

  // alias = topk
350
351
352
  // check = >0
  // desc = used in `Voting parallel <./Parallel-Learning-Guide.rst#choose-appropriate-parallel-algorithm>`__
  // desc = set this to larger value for more accurate result, but it will slow down the training speed
Guolin Ke's avatar
Guolin Ke committed
353
354
355
  int top_k = 20;

  // type = multi-int
356
357
358
359
360
  // alias = mc, monotone_constraint
  // default = None
  // desc = used for constraints of monotonic features
  // desc = ``1`` means increasing, ``-1`` means decreasing, ``0`` means non-constraint
  // desc = you need to specify all features in order. For example, ``mc=-1,0,1`` means decreasing for 1st feature, non-constraint for 2nd feature and increasing for the 3rd feature
Guolin Ke's avatar
Guolin Ke committed
361
  std::vector<int8_t> monotone_constraints;
Guolin Ke's avatar
Guolin Ke committed
362
363

  // type = multi-double
364
  // alias = feature_contrib, fc, fp, feature_penalty
Guolin Ke's avatar
Guolin Ke committed
365
366
367
368
  // default = None
  // desc = used to control feature's split gain, will use ``gain[i] = max(0, feature_contri[i]) * gain[i]`` to replace the split gain of i-th feature
  // desc = you need to specify all features in order
  std::vector<double> feature_contri;
369

370
371
372
373
  // alias = fs, forced_splits_filename, forced_splits_file, forced_splits
  // desc = path to a ``.json`` file that specifies splits to force at the top of every decision tree before best-first learning commences
  // desc = ``.json`` file can be arbitrarily nested, and each split contains ``feature``, ``threshold`` fields, as well as ``left`` and ``right`` fields representing subsplits
  // desc = categorical splits are forced in a one-hot fashion, with ``left`` representing the split containing the feature value and ``right`` representing other values
374
  // desc = **Note**: the forced split logic will be ignored, if the split makes gain worse
375
  // desc = see `this file <https://github.com/Microsoft/LightGBM/tree/master/examples/binary_classification/forced_splits.json>`__ as an example
Guolin Ke's avatar
Guolin Ke committed
376
377
  std::string forcedsplits_filename = "";

Guolin Ke's avatar
Guolin Ke committed
378
379
380
381
382
383
  // check = >=0.0
  // check = <=1.0
  // desc = decay rate of ``refit`` task, will use ``leaf_output = refit_decay_rate * old_leaf_output + (1.0 - refit_decay_rate) * new_leaf_output`` to refit trees
  // desc = used only in ``refit`` task in CLI version or as argument in ``refit`` function in language-specific package
  double refit_decay_rate = 0.9;

384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
  // check = >=0.0
  // desc = cost-effective gradient boosting multiplier for all penalties
  double cegb_tradeoff = 1.0;

  // check = >=0.0
  // desc = cost-effective gradient-boosting penalty for splitting a node
  double cegb_penalty_split = 0.0;

  // type = multi-double
  // default = 0,0,...,0
  // desc = cost-effective gradient boosting penalty for using a feature
  // desc = applied per data point
  std::vector<double> cegb_penalty_feature_lazy;

  // type = multi-double
  // default = 0,0,...,0
  // desc = cost-effective gradient boosting penalty for using a feature
  // desc = applied once per forest
402
  std::vector<double> cegb_penalty_feature_coupled;
403

Guolin Ke's avatar
Guolin Ke committed
404
405
406
407
  #pragma endregion

  #pragma region IO Parameters

408
409
  // alias = verbose
  // desc = controls the level of LightGBM's verbosity
410
  // desc = ``< 0``: Fatal, ``= 0``: Error (Warning), ``= 1``: Info, ``> 1``: Debug
411
412
413
414
415
416
  int verbosity = 1;

  // check = >1
  // desc = max number of bins that feature values will be bucketed in
  // desc = small number of bins may reduce training accuracy but may increase general power (deal with over-fitting)
  // desc = LightGBM will auto compress memory according to ``max_bin``. For example, LightGBM will use ``uint8_t`` for feature value if ``max_bin=255``
417
  int max_bin = 255;
Guolin Ke's avatar
Guolin Ke committed
418

419
420
421
  // check = >0
  // desc = minimal number of data inside one bin
  // desc = use this to avoid one-data-one-bin (potential over-fitting)
Guolin Ke's avatar
Guolin Ke committed
422
423
  int min_data_in_bin = 3;

424
425
426
427
428
429
430
  // alias = subsample_for_bin
  // check = >0
  // desc = number of data that sampled to construct histogram bins
  // desc = setting this to larger value will give better training result, but will increase data loading time
  // desc = set this to larger value if data is very sparse
  int bin_construct_sample_cnt = 200000;

431
  // alias = hist_pool_size
432
433
434
435
  // desc = max cache size in MB for historical histogram
  // desc = ``< 0`` means no limit
  double histogram_pool_size = -1.0;

436
  // alias = data_seed
437
  // desc = random seed for data partition in parallel learning (excluding the ``feature_parallel`` mode)
Guolin Ke's avatar
Guolin Ke committed
438
  int data_random_seed = 1;
Guolin Ke's avatar
Guolin Ke committed
439

440
441
  // alias = model_output, model_out
  // desc = filename of output model in training
442
  // desc = **Note**: can be used only in CLI version
Guolin Ke's avatar
Guolin Ke committed
443
  std::string output_model = "LightGBM_model.txt";
Guolin Ke's avatar
Guolin Ke committed
444

445
  // alias = save_period
446
447
  // desc = frequency of saving model file snapshot
  // desc = set this to positive value to enable this function. For example, the model file will be snapshotted at each iteration if ``snapshot_freq=1``
448
  // desc = **Note**: can be used only in CLI version
449
450
  int snapshot_freq = -1;

Guolin Ke's avatar
Guolin Ke committed
451
  // alias = model_input, model_in
452
453
454
455
  // desc = filename of input model
  // desc = for ``prediction`` task, this model will be applied to prediction data
  // desc = for ``train`` task, training will be continued from this model
  // desc = **Note**: can be used only in CLI version
Guolin Ke's avatar
Guolin Ke committed
456
  std::string input_model = "";
457

458
  // alias = predict_result, prediction_result, predict_name, prediction_name, pred_name, name_pred
459
  // desc = filename of prediction result in ``prediction`` task
460
  // desc = **Note**: can be used only in CLI version
Guolin Ke's avatar
Guolin Ke committed
461
462
  std::string output_result = "LightGBM_predict_result.txt";

463
  // alias = init_score_filename, init_score_file, init_score, input_init_score
464
  // desc = path of file with training initial scores
465
  // desc = if ``""``, will use ``train_data_file`` + ``.init`` (if exists)
466
  // desc = **Note**: works only in case of loading data directly from file
467
468
469
470
  std::string initscore_filename = "";

  // alias = valid_data_init_scores, valid_init_score_file, valid_init_score
  // default = ""
471
  // desc = path(s) of file(s) with validation initial scores
472
473
  // desc = if ``""``, will use ``valid_data_file`` + ``.init`` (if exists)
  // desc = separate by ``,`` for multi-validation data
474
  // desc = **Note**: works only in case of loading data directly from file
475
476
  std::vector<std::string> valid_data_initscores;

Guolin Ke's avatar
Guolin Ke committed
477
  // alias = is_pre_partition
478
479
  // desc = used for parallel learning (excluding the ``feature_parallel`` mode)
  // desc = ``true`` if training data are pre-partitioned, and different machines use different partitions
Guolin Ke's avatar
Guolin Ke committed
480
481
  bool pre_partition = false;

482
483
484
485
486
487
488
489
490
491
492
493
494
495
  // alias = is_enable_bundle, bundle
  // desc = set this to ``false`` to disable Exclusive Feature Bundling (EFB), which is described in `LightGBM: A Highly Efficient Gradient Boosting Decision Tree <https://papers.nips.cc/paper/6907-lightgbm-a-highly-efficient-gradient-boosting-decision-tree>`__
  // desc = **Note**: disabling this may cause the slow training speed for sparse datasets
  bool enable_bundle = true;

  // check = >=0.0
  // check = <1.0
  // desc = max conflict rate for bundles in EFB
  // desc = set this to ``0.0`` to disallow the conflict and provide more accurate results
  // desc = set this to a larger value to achieve faster speed
  double max_conflict_rate = 0.0;

  // alias = is_sparse, enable_sparse, sparse
  // desc = used to enable/disable sparse optimization
Guolin Ke's avatar
Guolin Ke committed
496
  bool is_enable_sparse = true;
Guolin Ke's avatar
Guolin Ke committed
497

498
499
  // check = >0.0
  // check = <=1.0
500
  // desc = the threshold of zero elements percentage for treating a feature as a sparse one
501
  double sparse_threshold = 0.8;
Guolin Ke's avatar
Guolin Ke committed
502

503
504
505
  // desc = set this to ``false`` to disable the special handle of missing value
  bool use_missing = true;

506
  // desc = set this to ``true`` to treat all zero as missing values (including the unshown values in libsvm/sparse matrices)
507
508
509
510
511
512
  // desc = set this to ``false`` to use ``na`` for representing missing values
  bool zero_as_missing = false;

  // alias = two_round_loading, use_two_round_loading
  // desc = set this to ``true`` if data file is too big to fit in memory
  // desc = by default, LightGBM will map data file to memory and load features from memory. This will provide faster data loading speed, but may cause run out of memory error when the data file is very big
513
  // desc = **Note**: works only in case of loading data directly from file
Guolin Ke's avatar
Guolin Ke committed
514
515
516
  bool two_round = false;

  // alias = is_save_binary, is_save_binary_file
517
  // desc = if ``true``, LightGBM will save the dataset (including validation data) to a binary file. This speed ups the data loading for the next time
518
  // desc = **Note**: can be used only in CLI version; for language-specific packages you can use the correspondent function
Guolin Ke's avatar
Guolin Ke committed
519
520
521
  bool save_binary = false;

  // alias = has_header
522
  // desc = set this to ``true`` if input data has header
523
  // desc = **Note**: works only in case of loading data directly from file
Guolin Ke's avatar
Guolin Ke committed
524
525
  bool header = false;

526
527
528
529
530
  // type = int or string
  // alias = label
  // desc = used to specify the label column
  // desc = use number for index, e.g. ``label=0`` means column\_0 is the label
  // desc = add a prefix ``name:`` for column name, e.g. ``label=name:is_click``
531
  // desc = **Note**: works only in case of loading data directly from file
Guolin Ke's avatar
Guolin Ke committed
532
  std::string label_column = "";
Guolin Ke's avatar
Guolin Ke committed
533

534
535
536
537
538
  // type = int or string
  // alias = weight
  // desc = used to specify the weight column
  // desc = use number for index, e.g. ``weight=0`` means column\_0 is the weight
  // desc = add a prefix ``name:`` for column name, e.g. ``weight=name:weight``
539
  // desc = **Note**: works only in case of loading data directly from file
540
  // desc = **Note**: index starts from ``0`` and it doesn't count the label column when passing type is ``int``, e.g. when label is column\_0, and weight is column\_1, the correct parameter is ``weight=0``
Guolin Ke's avatar
Guolin Ke committed
541
  std::string weight_column = "";
Guolin Ke's avatar
Guolin Ke committed
542

543
544
545
546
547
  // type = int or string
  // alias = group, group_id, query_column, query, query_id
  // desc = used to specify the query/group id column
  // desc = use number for index, e.g. ``query=0`` means column\_0 is the query id
  // desc = add a prefix ``name:`` for column name, e.g. ``query=name:query_id``
548
  // desc = **Note**: works only in case of loading data directly from file
549
550
  // desc = **Note**: data should be grouped by query\_id
  // desc = **Note**: index starts from ``0`` and it doesn't count the label column when passing type is ``int``, e.g. when label is column\_0 and query\_id is column\_1, the correct parameter is ``query=0``
Guolin Ke's avatar
Guolin Ke committed
551
  std::string group_column = "";
Guolin Ke's avatar
Guolin Ke committed
552

553
  // type = multi-int or string
Guolin Ke's avatar
Guolin Ke committed
554
  // alias = ignore_feature, blacklist
555
556
557
558
559
  // desc = used to specify some ignoring columns in training
  // desc = use number for index, e.g. ``ignore_column=0,1,2`` means column\_0, column\_1 and column\_2 will be ignored
  // desc = add a prefix ``name:`` for column name, e.g. ``ignore_column=name:c1,c2,c3`` means c1, c2 and c3 will be ignored
  // desc = **Note**: works only in case of loading data directly from file
  // desc = **Note**: index starts from ``0`` and it doesn't count the label column when passing type is ``int``
560
  // desc = **Note**: despite the fact that specified columns will be completely ignored during the training, they still should have a valid format allowing LightGBM to load file successfully
Guolin Ke's avatar
Guolin Ke committed
561
  std::string ignore_column = "";
562

563
564
565
566
567
568
569
570
  // type = multi-int or string
  // alias = cat_feature, categorical_column, cat_column
  // desc = used to specify categorical features
  // desc = use number for index, e.g. ``categorical_feature=0,1,2`` means column\_0, column\_1 and column\_2 are categorical features
  // desc = add a prefix ``name:`` for column name, e.g. ``categorical_feature=name:c1,c2,c3`` means c1, c2 and c3 are categorical features
  // desc = **Note**: only supports categorical with ``int`` type
  // desc = **Note**: index starts from ``0`` and it doesn't count the label column when passing type is ``int``
  // desc = **Note**: all values should be less than ``Int32.MaxValue`` (2147483647)
571
  // desc = **Note**: using large values could be memory consuming. Tree decision rule works best when categorical features are presented by consecutive integers starting from zero
572
  // desc = **Note**: all negative values will be treated as **missing values**
Guolin Ke's avatar
Guolin Ke committed
573
574
  std::string categorical_feature = "";

575
576
577
578
  // alias = is_predict_raw_score, predict_rawscore, raw_score
  // desc = used only in ``prediction`` task
  // desc = set this to ``true`` to predict only the raw scores
  // desc = set this to ``false`` to predict transformed scores
Guolin Ke's avatar
Guolin Ke committed
579
580
  bool predict_raw_score = false;

581
582
583
  // alias = is_predict_leaf_index, leaf_index
  // desc = used only in ``prediction`` task
  // desc = set this to ``true`` to predict with leaf index of all trees
Guolin Ke's avatar
Guolin Ke committed
584
585
  bool predict_leaf_index = false;

586
587
  // alias = is_predict_contrib, contrib
  // desc = used only in ``prediction`` task
588
  // desc = set this to ``true`` to estimate `SHAP values <https://arxiv.org/abs/1706.06060>`__, which represent how each feature contributes to each prediction
589
  // desc = produces ``#features + 1`` values where the last value is the expected value of the model output over the training data
590
  // desc = **Note**: if you want to get more explanation for your model's predictions using SHAP values like SHAP interaction values, you can install `shap package <https://github.com/slundberg/shap>`__
Guolin Ke's avatar
Guolin Ke committed
591
592
  bool predict_contrib = false;

593
594
595
  // desc = used only in ``prediction`` task
  // desc = used to specify how many trained iterations will be used in prediction
  // desc = ``<= 0`` means no limit
Guolin Ke's avatar
Guolin Ke committed
596
597
  int num_iteration_predict = -1;

598
599
  // desc = used only in ``prediction`` task
  // desc = if ``true``, will use early-stopping to speed up the prediction. May affect the accuracy
600
  bool pred_early_stop = false;
601
602
603

  // desc = used only in ``prediction`` task
  // desc = the frequency of checking early-stopping prediction
604
  int pred_early_stop_freq = 10;
Guolin Ke's avatar
Guolin Ke committed
605

606
607
  // desc = used only in ``prediction`` task
  // desc = the threshold of margin in early-stopping prediction
Guolin Ke's avatar
Guolin Ke committed
608
  double pred_early_stop_margin = 10.0;
Guolin Ke's avatar
Guolin Ke committed
609

610
611
612
  // desc = used only in ``convert_model`` task
  // desc = only ``cpp`` is supported yet
  // desc = if ``convert_model_language`` is set and ``task=train``, the model will be also converted
613
  // desc = **Note**: can be used only in CLI version
Guolin Ke's avatar
Guolin Ke committed
614
615
  std::string convert_model_language = "";

616
617
618
  // alias = convert_model_file
  // desc = used only in ``convert_model`` task
  // desc = output filename of converted model
619
  // desc = **Note**: can be used only in CLI version
Guolin Ke's avatar
Guolin Ke committed
620
621
  std::string convert_model = "gbdt_prediction.cpp";

622
  #pragma endregion
Guolin Ke's avatar
Guolin Ke committed
623
624
625

  #pragma region Objective Parameters

626
627
628
629
  // check = >0
  // alias = num_classes
  // desc = used only in ``multi-class`` classification application
  int num_class = 1;
Guolin Ke's avatar
Guolin Ke committed
630

631
  // alias = unbalance, unbalanced_sets
632
  // desc = used only in ``binary`` application
633
  // desc = set this to ``true`` if training data are unbalanced
634
  // desc = **Note**: while enabling this should increase the overall performance metric of your model, it will also result in poor estimates of the individual class probabilities
635
636
  // desc = **Note**: this parameter cannot be used at the same time with ``scale_pos_weight``, choose only **one** of them
  bool is_unbalance = false;
Guolin Ke's avatar
Guolin Ke committed
637

638
639
640
  // check = >0.0
  // desc = used only in ``binary`` application
  // desc = weight of labels with positive class
641
  // desc = **Note**: while enabling this should increase the overall performance metric of your model, it will also result in poor estimates of the individual class probabilities
642
643
  // desc = **Note**: this parameter cannot be used at the same time with ``is_unbalance``, choose only **one** of them
  double scale_pos_weight = 1.0;
Guolin Ke's avatar
Guolin Ke committed
644

645
646
647
648
  // check = >0.0
  // desc = used only in ``binary`` and ``multiclassova`` classification and in ``lambdarank`` applications
  // desc = parameter for the sigmoid function
  double sigmoid = 1.0;
Guolin Ke's avatar
Guolin Ke committed
649

650
651
  // desc = used only in ``regression``, ``binary`` and ``cross-entropy`` applications
  // desc = adjusts initial score to the mean of labels for faster convergence
Guolin Ke's avatar
Guolin Ke committed
652
653
  bool boost_from_average = true;

654
655
656
657
  // desc = used only in ``regression`` application
  // desc = used to fit ``sqrt(label)`` instead of original values and prediction result will be also automatically converted to ``prediction^2``
  // desc = might be useful in case of large-range labels
  bool reg_sqrt = false;
Guolin Ke's avatar
Guolin Ke committed
658

659
660
661
662
  // check = >0.0
  // desc = used only in ``huber`` and ``quantile`` ``regression`` applications
  // desc = parameter for `Huber loss <https://en.wikipedia.org/wiki/Huber_loss>`__ and `Quantile regression <https://en.wikipedia.org/wiki/Quantile_regression>`__
  double alpha = 0.9;
Guolin Ke's avatar
Guolin Ke committed
663

664
665
666
667
  // check = >0.0
  // desc = used only in ``fair`` ``regression`` application
  // desc = parameter for `Fair loss <https://www.kaggle.com/c/allstate-claims-severity/discussion/24520>`__
  double fair_c = 1.0;
Guolin Ke's avatar
Guolin Ke committed
668

669
670
671
672
  // check = >0.0
  // desc = used only in ``poisson`` ``regression`` application
  // desc = parameter for `Poisson regression <https://en.wikipedia.org/wiki/Poisson_regression>`__ to safeguard optimization
  double poisson_max_delta_step = 0.7;
Guolin Ke's avatar
Guolin Ke committed
673

674
675
676
677
678
679
680
  // check = >=1.0
  // check = <2.0
  // desc = used only in ``tweedie`` ``regression`` application
  // desc = used to control the variance of the tweedie distribution
  // desc = set this closer to ``2`` to shift towards a **Gamma** distribution
  // desc = set this closer to ``1`` to shift towards a **Poisson** distribution
  double tweedie_variance_power = 1.5;
Guolin Ke's avatar
Guolin Ke committed
681

682
683
684
  // check = >0
  // desc = used only in ``lambdarank`` application
  // desc = optimizes `NDCG <https://en.wikipedia.org/wiki/Discounted_cumulative_gain#Normalized_DCG>`__ at this position
Guolin Ke's avatar
Guolin Ke committed
685
  int max_position = 20;
Guolin Ke's avatar
Guolin Ke committed
686

687
688
689
690
691
692
693
  // type = multi-double
  // default = 0,1,3,7,15,31,63,...,2^30-1
  // desc = used only in ``lambdarank`` application
  // desc = relevant gain for labels. For example, the gain of label ``2`` is ``3`` in case of default label gains
  // desc = separate by ``,``
  std::vector<double> label_gain;

Guolin Ke's avatar
Guolin Ke committed
694
695
696
  #pragma endregion

  #pragma region Metric Parameters
697

Guolin Ke's avatar
Guolin Ke committed
698
  // [doc-only]
699
700
701
  // alias = metrics, metric_types
  // default = ""
  // type = multi-enum
702
  // desc = metric(s) to be evaluated on the evaluation set(s)
703
  // descl2 = ``""`` (empty string or not specified) means that metric corresponding to specified ``objective`` will be used (this is possible only for pre-defined objective functions, otherwise no evaluation metric will be added)
704
  // descl2 = ``"None"`` (string, **not** a ``None`` value) means that no metric will be registered, aliases: ``na``, ``null``, ``custom``
705
706
707
708
709
710
711
712
713
714
715
  // descl2 = ``l1``, absolute loss, aliases: ``mean_absolute_error``, ``mae``, ``regression_l1``
  // descl2 = ``l2``, square loss, aliases: ``mean_squared_error``, ``mse``, ``regression_l2``, ``regression``
  // descl2 = ``l2_root``, root square loss, aliases: ``root_mean_squared_error``, ``rmse``
  // descl2 = ``quantile``, `Quantile regression <https://en.wikipedia.org/wiki/Quantile_regression>`__
  // descl2 = ``mape``, `MAPE loss <https://en.wikipedia.org/wiki/Mean_absolute_percentage_error>`__, aliases: ``mean_absolute_percentage_error``
  // descl2 = ``huber``, `Huber loss <https://en.wikipedia.org/wiki/Huber_loss>`__
  // descl2 = ``fair``, `Fair loss <https://www.kaggle.com/c/allstate-claims-severity/discussion/24520>`__
  // descl2 = ``poisson``, negative log-likelihood for `Poisson regression <https://en.wikipedia.org/wiki/Poisson_regression>`__
  // descl2 = ``gamma``, negative log-likelihood for **Gamma** regression
  // descl2 = ``gamma_deviance``, residual deviance for **Gamma** regression
  // descl2 = ``tweedie``, negative log-likelihood for **Tweedie** regression
716
  // descl2 = ``ndcg``, `NDCG <https://en.wikipedia.org/wiki/Discounted_cumulative_gain#Normalized_DCG>`__, aliases: ``lambdarank``
717
718
719
720
721
722
723
724
725
726
  // descl2 = ``map``, `MAP <https://makarandtapaswi.wordpress.com/2012/07/02/intuition-behind-average-precision-and-map/>`__, aliases: ``mean_average_precision``
  // descl2 = ``auc``, `AUC <https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve>`__
  // descl2 = ``binary_logloss``, `log loss <https://en.wikipedia.org/wiki/Cross_entropy>`__, aliases: ``binary``
  // descl2 = ``binary_error``, for one sample: ``0`` for correct classification, ``1`` for error classification
  // descl2 = ``multi_logloss``, log loss for multi-class classification, aliases: ``multiclass``, ``softmax``, ``multiclassova``, ``multiclass_ova``, ``ova``, ``ovr``
  // descl2 = ``multi_error``, error rate for multi-class classification
  // descl2 = ``xentropy``, cross-entropy (with optional linear weights), aliases: ``cross_entropy``
  // descl2 = ``xentlambda``, "intensity-weighted" cross-entropy, aliases: ``cross_entropy_lambda``
  // descl2 = ``kldiv``, `Kullback-Leibler divergence <https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence>`__, aliases: ``kullback_leibler``
  // desc = support multiple metrics, separated by ``,``
Guolin Ke's avatar
Guolin Ke committed
727
728
  std::vector<std::string> metric;

729
  // check = >0
Guolin Ke's avatar
Guolin Ke committed
730
731
732
733
  // alias = output_freq
  // desc = frequency for metric output
  int metric_freq = 1;

734
735
  // alias = training_metric, is_training_metric, train_metric
  // desc = set this to ``true`` to output metric result over training dataset
736
  // desc = **Note**: can be used only in CLI version
737
  bool is_provide_training_metric = false;
738

739
740
  // type = multi-int
  // default = 1,2,3,4,5
741
  // alias = ndcg_eval_at, ndcg_at, map_eval_at, map_at
742
  // desc = used only with ``ndcg`` and ``map`` metrics
743
  // desc = `NDCG <https://en.wikipedia.org/wiki/Discounted_cumulative_gain#Normalized_DCG>`__ and `MAP <https://makarandtapaswi.wordpress.com/2012/07/02/intuition-behind-average-precision-and-map/>`__ evaluation positions, separated by ``,``
Guolin Ke's avatar
Guolin Ke committed
744
  std::vector<int> eval_at;
Guolin Ke's avatar
Guolin Ke committed
745

Guolin Ke's avatar
Guolin Ke committed
746
747
748
749
  #pragma endregion

  #pragma region Network Parameters

750
751
752
753
  // check = >0
  // alias = num_machine
  // desc = the number of machines for parallel learning application
  // desc = this parameter is needed to be set in both **socket** and **mpi** versions
Guolin Ke's avatar
Guolin Ke committed
754
  int num_machines = 1;
Guolin Ke's avatar
Guolin Ke committed
755

756
757
758
759
  // check = >0
  // alias = local_port, port
  // desc = TCP listen port for local machines
  // desc = **Note**: don't forget to allow this port in firewall settings before training
Guolin Ke's avatar
Guolin Ke committed
760
  int local_listen_port = 12400;
Guolin Ke's avatar
Guolin Ke committed
761

762
763
764
  // check = >0
  // desc = socket time-out in minutes
  int time_out = 120;
Guolin Ke's avatar
Guolin Ke committed
765

766
767
768
  // alias = machine_list_file, machine_list, mlist
  // desc = path of file that lists machines for this parallel learning application
  // desc = each line contains one IP and one port for one machine. The format is ``ip port`` (space as a separator)
Guolin Ke's avatar
Guolin Ke committed
769
  std::string machine_list_filename = "";
Guolin Ke's avatar
Guolin Ke committed
770

771
772
  // alias = workers, nodes
  // desc = list of machines in the following format: ``ip1:port1,ip2:port2``
773
  std::string machines = "";
Guolin Ke's avatar
Guolin Ke committed
774

Guolin Ke's avatar
Guolin Ke committed
775
776
777
778
  #pragma endregion

  #pragma region GPU Parameters

779
780
  // desc = OpenCL platform ID. Usually each GPU vendor exposes one OpenCL platform
  // desc = ``-1`` means the system-wide default platform
781
  // desc = **Note**: refer to `GPU Targets <./GPU-Targets.rst#query-opencl-devices-in-your-system>`__ for more details
Guolin Ke's avatar
Guolin Ke committed
782
783
  int gpu_platform_id = -1;

784
785
  // desc = OpenCL device ID in the specified platform. Each GPU in the selected platform has a unique device ID
  // desc = ``-1`` means the default device in the selected platform
786
  // desc = **Note**: refer to `GPU Targets <./GPU-Targets.rst#query-opencl-devices-in-your-system>`__ for more details
Guolin Ke's avatar
Guolin Ke committed
787
788
  int gpu_device_id = -1;

789
  // desc = set this to ``true`` to use double precision math on GPU (by default single precision is used)
Guolin Ke's avatar
Guolin Ke committed
790
791
792
793
794
  bool gpu_use_dp = false;

  #pragma endregion

  #pragma endregion
Guolin Ke's avatar
Guolin Ke committed
795
796
797

  bool is_parallel = false;
  bool is_parallel_find_bin = false;
Guolin Ke's avatar
Guolin Ke committed
798
799
800
  LIGHTGBM_EXPORT void Set(const std::unordered_map<std::string, std::string>& params);
  static std::unordered_map<std::string, std::string> alias_table;
  static std::unordered_set<std::string> parameter_set;
801

Nikita Titov's avatar
Nikita Titov committed
802
 private:
Guolin Ke's avatar
Guolin Ke committed
803
  void CheckParamConflict();
Guolin Ke's avatar
Guolin Ke committed
804
805
  void GetMembersFromString(const std::unordered_map<std::string, std::string>& params);
  std::string SaveMembersToString() const;
Guolin Ke's avatar
Guolin Ke committed
806
807
};

Guolin Ke's avatar
Guolin Ke committed
808
inline bool Config::GetString(
Guolin Ke's avatar
Guolin Ke committed
809
810
811
812
813
814
815
816
817
  const std::unordered_map<std::string, std::string>& params,
  const std::string& name, std::string* out) {
  if (params.count(name) > 0) {
    *out = params.at(name);
    return true;
  }
  return false;
}

Guolin Ke's avatar
Guolin Ke committed
818
inline bool Config::GetInt(
Guolin Ke's avatar
Guolin Ke committed
819
820
821
  const std::unordered_map<std::string, std::string>& params,
  const std::string& name, int* out) {
  if (params.count(name) > 0) {
822
    if (!Common::AtoiAndCheck(params.at(name).c_str(), out)) {
823
      Log::Fatal("Parameter %s should be of type int, got \"%s\"",
Guolin Ke's avatar
Guolin Ke committed
824
                 name.c_str(), params.at(name).c_str());
825
    }
Guolin Ke's avatar
Guolin Ke committed
826
827
828
829
830
    return true;
  }
  return false;
}

Guolin Ke's avatar
Guolin Ke committed
831
inline bool Config::GetDouble(
Guolin Ke's avatar
Guolin Ke committed
832
  const std::unordered_map<std::string, std::string>& params,
833
  const std::string& name, double* out) {
Guolin Ke's avatar
Guolin Ke committed
834
  if (params.count(name) > 0) {
835
    if (!Common::AtofAndCheck(params.at(name).c_str(), out)) {
836
      Log::Fatal("Parameter %s should be of type double, got \"%s\"",
Guolin Ke's avatar
Guolin Ke committed
837
                 name.c_str(), params.at(name).c_str());
838
    }
Guolin Ke's avatar
Guolin Ke committed
839
840
841
842
843
    return true;
  }
  return false;
}

Guolin Ke's avatar
Guolin Ke committed
844
inline bool Config::GetBool(
Guolin Ke's avatar
Guolin Ke committed
845
846
847
848
  const std::unordered_map<std::string, std::string>& params,
  const std::string& name, bool* out) {
  if (params.count(name) > 0) {
    std::string value = params.at(name);
Guolin Ke's avatar
Guolin Ke committed
849
    std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
850
    if (value == std::string("false") || value == std::string("-")) {
Guolin Ke's avatar
Guolin Ke committed
851
      *out = false;
852
    } else if (value == std::string("true") || value == std::string("+")) {
Guolin Ke's avatar
Guolin Ke committed
853
      *out = true;
854
    } else {
855
      Log::Fatal("Parameter %s should be \"true\"/\"+\" or \"false\"/\"-\", got \"%s\"",
Guolin Ke's avatar
Guolin Ke committed
856
                 name.c_str(), params.at(name).c_str());
Guolin Ke's avatar
Guolin Ke committed
857
858
859
860
861
862
863
864
865
866
    }
    return true;
  }
  return false;
}

struct ParameterAlias {
  static void KeyAliasTransform(std::unordered_map<std::string, std::string>* params) {
    std::unordered_map<std::string, std::string> tmp_map;
    for (const auto& pair : *params) {
Guolin Ke's avatar
Guolin Ke committed
867
      auto alias = Config::alias_table.find(pair.first);
868
      if (alias != Config::alias_table.end()) {  // found alias
Guolin Ke's avatar
Guolin Ke committed
869
        auto alias_set = tmp_map.find(alias->second);
870
871
        if (alias_set != tmp_map.end()) {  // alias already set
                                           // set priority by length & alphabetically to ensure reproducible behavior
wxchan's avatar
wxchan committed
872
873
          if (alias_set->second.size() < pair.first.size() ||
            (alias_set->second.size() == pair.first.size() && alias_set->second < pair.first)) {
874
            Log::Warning("%s is set with %s=%s, %s=%s will be ignored. Current value: %s=%s",
Guolin Ke's avatar
Guolin Ke committed
875
876
                         alias->second.c_str(), alias_set->second.c_str(), params->at(alias_set->second).c_str(),
                         pair.first.c_str(), pair.second.c_str(), alias->second.c_str(), params->at(alias_set->second).c_str());
wxchan's avatar
wxchan committed
877
          } else {
878
            Log::Warning("%s is set with %s=%s, will be overridden by %s=%s. Current value: %s=%s",
Guolin Ke's avatar
Guolin Ke committed
879
880
                         alias->second.c_str(), alias_set->second.c_str(), params->at(alias_set->second).c_str(),
                         pair.first.c_str(), pair.second.c_str(), alias->second.c_str(), pair.second.c_str());
wxchan's avatar
wxchan committed
881
882
            tmp_map[alias->second] = pair.first;
          }
883
        } else {  // alias not set
wxchan's avatar
wxchan committed
884
885
          tmp_map.emplace(alias->second, pair.first);
        }
Guolin Ke's avatar
Guolin Ke committed
886
      } else if (Config::parameter_set.find(pair.first) == Config::parameter_set.end()) {
wxchan's avatar
wxchan committed
887
        Log::Warning("Unknown parameter: %s", pair.first.c_str());
Guolin Ke's avatar
Guolin Ke committed
888
889
890
      }
    }
    for (const auto& pair : tmp_map) {
wxchan's avatar
wxchan committed
891
      auto alias = params->find(pair.first);
892
      if (alias == params->end()) {  // not find
wxchan's avatar
wxchan committed
893
894
895
        params->emplace(pair.first, params->at(pair.second));
        params->erase(pair.second);
      } else {
Guolin Ke's avatar
Guolin Ke committed
896
897
898
        Log::Warning("%s is set=%s, %s=%s will be ignored. Current value: %s=%s",
                     pair.first.c_str(), alias->second.c_str(), pair.second.c_str(), params->at(pair.second).c_str(),
                     pair.first.c_str(), alias->second.c_str());
Guolin Ke's avatar
Guolin Ke committed
899
900
901
902
903
904
905
      }
    }
  }
};

}   // namespace LightGBM

Guolin Ke's avatar
Guolin Ke committed
906
#endif   // LightGBM_CONFIG_H_