dataset.h 13.6 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
#ifndef LIGHTGBM_DATA_H_
#define LIGHTGBM_DATA_H_

#include <LightGBM/utils/random.h>
#include <LightGBM/utils/text_reader.h>

#include <LightGBM/meta.h>
Guolin Ke's avatar
Guolin Ke committed
8
#include <LightGBM/config.h>
Guolin Ke's avatar
Guolin Ke committed
9
10
11
12
13

#include <vector>
#include <utility>
#include <functional>
#include <string>
Guolin Ke's avatar
Guolin Ke committed
14
#include <unordered_set>
Guolin Ke's avatar
Guolin Ke committed
15
16
17
18
19
20
21

namespace LightGBM {

/*! \brief forward declaration */
class Feature;

/*!
Hui Xue's avatar
Hui Xue committed
22
* \brief This class is used to store some meta(non-feature) data for training data,
Guolin Ke's avatar
Guolin Ke committed
23
24
*        e.g. labels, weights, initial scores, qurey level informations.
*
Qiwei Ye's avatar
Qiwei Ye committed
25
26
27
28
29
30
31
32
*        Some details:
*        1. Label, used for traning.
*        2. Weights, weighs of records, optional
*        3. Query Boundaries, necessary for lambdarank.
*           The documents of i-th query is in [ query_boundarise[i], query_boundarise[i+1] )
*        4. Query Weights, auto calculate by weights and query_boundarise(if both of them are existed)
*           the weight for i-th query is sum(query_boundarise[i] , .., query_boundarise[i+1]) / (query_boundarise[i + 1] -  query_boundarise[i+1])
*        5. Initial score. optional. if exsitng, the model will boost from this score, otherwise will start from 0.
Guolin Ke's avatar
Guolin Ke committed
33
34
35
36
37
38
39
40
*/
class Metadata {
public:
 /*!
  * \brief Null costructor
  */
  Metadata();
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
41
  * \brief Initialization will load qurey level informations, since it is need for sampling data
Guolin Ke's avatar
Guolin Ke committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  * \param data_filename Filename of data
  * \param init_score_filename Filename of initial score
  * \param is_int_label True if label is int type
  */
  void Init(const char* data_filename, const char* init_score_filename);
  /*!
  * \brief Initialize, only load initial score
  * \param init_score_filename Filename of initial score
  */
  void Init(const char* init_score_filename);
  /*!
  * \brief Initial with binary memory
  * \param memory Pointer to memory
  */
  void LoadFromMemory(const void* memory);
  /*! \brief Destructor */
  ~Metadata();

  /*!
Guolin Ke's avatar
Guolin Ke committed
61
  * \brief Initial work, will allocate space for label, weight(if exists) and query(if exists)
Guolin Ke's avatar
Guolin Ke committed
62
  * \param num_data Number of training data
Guolin Ke's avatar
Guolin Ke committed
63
64
  * \param weight_idx Index of weight column, < 0 means doesn't exists
  * \param query_idx Index of query id column, < 0 means doesn't exists
Guolin Ke's avatar
Guolin Ke committed
65
  */
Guolin Ke's avatar
Guolin Ke committed
66
  void Init(data_size_t num_data, int weight_idx, int query_idx);
Guolin Ke's avatar
Guolin Ke committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

  /*!
  * \brief Partition label by used indices
  * \param used_indices Indice of local used
  */
  void PartitionLabel(const std::vector<data_size_t>& used_indices);

  /*!
  * \brief Partition meta data according to local used indices if need
  * \param num_all_data Number of total training data, including other machines' data on parallel learning
  * \param used_data_indices Indices of local used training data
  */
  void CheckOrPartition(data_size_t num_all_data,
    const std::vector<data_size_t>& used_data_indices);

  /*!
  * \brief Set initial scores
  * \param init_score Initial scores, this class will manage memory for init_score.
  */
Guolin Ke's avatar
Guolin Ke committed
86
  void SetInitScore(const float* init_score, data_size_t len);
Guolin Ke's avatar
Guolin Ke committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110


  /*!
  * \brief Save binary data to file
  * \param file File want to write
  */
  void SaveBinaryToFile(FILE* file) const;

  /*!
  * \brief Get sizes in byte of this object
  */
  size_t SizesInByte() const;

  /*!
  * \brief Get pointer of label
  * \return Pointer of label
  */
  inline const float* label() const { return label_; }

  /*!
  * \brief Set label for one record
  * \param idx Index of this record
  * \param value Label value of this record
  */
111
  inline void SetLabelAt(data_size_t idx, float value)
Guolin Ke's avatar
Guolin Ke committed
112
  {
113
    label_[idx] = value;
Guolin Ke's avatar
Guolin Ke committed
114
115
  }

Guolin Ke's avatar
Guolin Ke committed
116
117
118
119
120
  /*!
  * \brief Set Weight for one record
  * \param idx Index of this record
  * \param value Weight value of this record
  */
121
  inline void SetWeightAt(data_size_t idx, float value)
Guolin Ke's avatar
Guolin Ke committed
122
  {
123
    weights_[idx] = value;
Guolin Ke's avatar
Guolin Ke committed
124
125
126
127
128
129
130
  }

  /*!
  * \brief Set Query Id for one record
  * \param idx Index of this record
  * \param value Query Id value of this record
  */
131
  inline void SetQueryAt(data_size_t idx, float value)
Guolin Ke's avatar
Guolin Ke committed
132
133
134
135
  {
    queries_[idx] = static_cast<data_size_t>(value);
  }

Guolin Ke's avatar
Guolin Ke committed
136
  /*!
Hui Xue's avatar
Hui Xue committed
137
  * \brief Get weights, if not exists, will return nullptr
Guolin Ke's avatar
Guolin Ke committed
138
139
140
141
142
143
  * \return Pointer of weights
  */
  inline const float* weights()
            const { return weights_; }

  /*!
Hui Xue's avatar
Hui Xue committed
144
  * \brief Get data boundaries on queries, if not exists, will return nullptr
Guolin Ke's avatar
Guolin Ke committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
  *        we assume data will order by query, 
  *        the interval of [query_boundaris[i], query_boundaris[i+1])
  *        is the data indices for query i.
  * \return Pointer of data boundaries on queries
  */
  inline const data_size_t* query_boundaries()
           const { return query_boundaries_; }

  /*!
  * \brief Get Number of queries
  * \return Number of queries
  */
  inline const data_size_t num_queries() const { return num_queries_; }

  /*!
Hui Xue's avatar
Hui Xue committed
160
  * \brief Get weights for queries, if not exists, will return nullptr
Guolin Ke's avatar
Guolin Ke committed
161
162
163
164
165
  * \return Pointer of weights for queries
  */
  inline const float* query_weights() const { return query_weights_; }

  /*!
Hui Xue's avatar
Hui Xue committed
166
  * \brief Get initial scores, if not exists, will return nullptr
Guolin Ke's avatar
Guolin Ke committed
167
168
  * \return Pointer of initial scores
  */
Guolin Ke's avatar
Guolin Ke committed
169
  inline const float* init_score() const { return init_score_; }
Guolin Ke's avatar
Guolin Ke committed
170
171
172
173
174
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

  /*! \brief Load initial scores from file */
  void LoadInitialScore();

private:
  /*! \brief Load wights from file */
  void LoadWeights();
  /*! \brief Load query boundaries from file */
  void LoadQueryBoundaries();
  /*! \brief Load query wights */
  void LoadQueryWeights();
  /*! \brief Filename of current data */
  const char* data_filename_;
  /*! \brief Filename of initial scores */
  const char* init_score_filename_;
  /*! \brief Number of data */
  data_size_t num_data_;
  /*! \brief Number of weights, used to check correct weight file */
  data_size_t num_weights_;
  /*! \brief Label data */
  float* label_;
  /*! \brief Label data, int type */
  int16_t* label_int_;
  /*! \brief Weights data */
  float* weights_;
  /*! \brief Query boundaries */
  data_size_t* query_boundaries_;
  /*! \brief Query weights */
  float* query_weights_;
  /*! \brief Number of querys */
  data_size_t num_queries_;
  /*! \brief Number of Initial score, used to check correct weight file */
  data_size_t num_init_score_;
  /*! \brief Initial score */
Guolin Ke's avatar
Guolin Ke committed
204
  float* init_score_;
Guolin Ke's avatar
Guolin Ke committed
205
206
  /*! \brief Queries data */
  data_size_t* queries_;
Guolin Ke's avatar
Guolin Ke committed
207
208
209
210
211
212
};


/*! \brief Interface for Parser */
class Parser {
public:
Guolin Ke's avatar
Guolin Ke committed
213

Guolin Ke's avatar
Guolin Ke committed
214
215
216
217
218
219
  /*! \brief virtual destructor */
  virtual ~Parser() {}

  /*!
  * \brief Parse one line with label
  * \param str One line record, string format, should end with '\0'
Guolin Ke's avatar
Guolin Ke committed
220
221
  * \param out_features Output columns, store in (column_idx, values)
  * \param out_label Label will store to this if exists
Guolin Ke's avatar
Guolin Ke committed
222
223
  */
  virtual void ParseOneLine(const char* str,
224
    std::vector<std::pair<int, float>>* out_features, float* out_label) const = 0;
Guolin Ke's avatar
Guolin Ke committed
225
226
227
228

  /*!
  * \brief Create a object of parser, will auto choose the format depend on file
  * \param filename One Filename of data
229
  * \param num_features Pass num_features of this data file if you know, <=0 means don't know
Guolin Ke's avatar
Guolin Ke committed
230
  * \param label_idx index of label column
Guolin Ke's avatar
Guolin Ke committed
231
232
  * \return Object of parser
  */
Guolin Ke's avatar
Guolin Ke committed
233
  static Parser* CreateParser(const char* filename, bool has_header, int num_features, int label_idx);
Guolin Ke's avatar
Guolin Ke committed
234
235
236
};

using PredictFunction =
237
  std::function<float(const std::vector<std::pair<int, float>>&)>;
Guolin Ke's avatar
Guolin Ke committed
238
239
240
241
242
243
244
245
246
247

/*! \brief The main class of data set,
*          which are used to traning or validation
*/
class Dataset {
public:
  /*!
  * \brief Constructor
  * \param data_filename Filename of dataset
  * \param init_score_filename Filename of initial score
Guolin Ke's avatar
Guolin Ke committed
248
  * \param io_config configs for IO
Hui Xue's avatar
Hui Xue committed
249
  * \param predict_fun Used for initial model, will give a prediction score based on this function, then set as initial score
Guolin Ke's avatar
Guolin Ke committed
250
251
  */
  Dataset(const char* data_filename, const char* init_score_filename,
Guolin Ke's avatar
Guolin Ke committed
252
    const IOConfig& io_config, const PredictFunction& predict_fun);
Guolin Ke's avatar
Guolin Ke committed
253
254
255
256

  /*!
  * \brief Constructor
  * \param data_filename Filename of dataset
Guolin Ke's avatar
Guolin Ke committed
257
  * \param io_config configs for IO
Hui Xue's avatar
Hui Xue committed
258
  * \param predict_fun Used for initial model, will give a prediction score based on this function, then set as initial score
Guolin Ke's avatar
Guolin Ke committed
259
260
  */
  Dataset(const char* data_filename,
Guolin Ke's avatar
Guolin Ke committed
261
262
    const IOConfig& io_config, const PredictFunction& predict_fun)
    : Dataset(data_filename, "", io_config, predict_fun) {
Guolin Ke's avatar
Guolin Ke committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
  }

  /*! \brief Destructor */
  ~Dataset();

  /*!
  * \brief Load training data on parallel training
  * \param rank Rank of local machine
  * \param num_machines Total number of all machines
  * \param is_pre_partition True if data file is pre-partitioned
  * \param use_two_round_loading True if need to use two round loading
  */
  void LoadTrainData(int rank, int num_machines, bool is_pre_partition,
                                           bool use_two_round_loading);

  /*!
  * \brief Load training data on single machine training
  * \param use_two_round_loading True if need to use two round loading
  */
  inline void LoadTrainData(bool use_two_round_loading) {
    LoadTrainData(0, 1, false, use_two_round_loading);
  }

  /*!
  * \brief Load data and use bin mapper from other data set, general this function is used to extract feature for validation data
  * \param train_set Other loaded data set
  * \param use_two_round_loading True if need to use two round loading
  */
  void LoadValidationData(const Dataset* train_set, bool use_two_round_loading);

  /*!
  * \brief Save current dataset into binary file, will save to "filename.bin"
  */
  void SaveBinaryFile();

  /*!
  * \brief Get a feature pointer for specific index
  * \param i Index for feature
  * \return Pointer of feature
  */
  inline const Feature* FeatureAt(int i) const { return features_[i]; }

  /*!
  * \brief Get meta data pointer
  * \return Pointer of meta data
  */
  inline const Metadata& metadata() const { return metadata_; }

  /*! \brief Get Number of used features */
  inline int num_features() const { return num_features_; }

314
315
316
  /*! \brief Get Number of total features */
  inline int num_total_features() const { return num_total_features_; }

Guolin Ke's avatar
Guolin Ke committed
317
318
319
320
321
322
  /*! \brief Get the index of label column */
  inline int label_idx() const { return label_idx_; }

  /*! \brief Get names of current data set */
  inline std::vector<std::string> feature_names() const { return feature_names_; }

Guolin Ke's avatar
Guolin Ke committed
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
  /*! \brief Get Number of data */
  inline data_size_t num_data() const { return num_data_; }

  /*! \brief Disable copy */
  Dataset& operator=(const Dataset&) = delete;
  /*! \brief Disable copy */
  Dataset(const Dataset&) = delete;

private:
  /*!
  * \brief Load data content on memory. if num_machines > 1 and !is_pre_partition, will partition data
  * \param rank Rank of local machine
  * \param num_machines Total number of all machines
  * \param is_pre_partition True if data file is pre-partitioned
  */
  void LoadDataToMemory(int rank, int num_machines, bool is_pre_partition);

  /*!
  * \brief Sample data from memory, need load data to memory first
  * \param out_data Store the sampled data
  */
  void SampleDataFromMemory(std::vector<std::string>* out_data);

  /*!
  * \brief Sample data from file
  * \param rank Rank of local machine
  * \param num_machines Total number of all machines
  * \param is_pre_partition True if data file is pre-partitioned
  * \param out_data Store the sampled data
  */
  void SampleDataFromFile(int rank, int num_machines,
    bool is_pre_partition, std::vector<std::string>* out_data);

  /*!
  * \brief Get feature bin mapper from sampled data.
  * if num_machines > 1, differnt machines will construct bin mapper for different features, then have a global sync up
  * \param rank Rank of local machine
  * \param num_machines Total number of all machines
  */
  void ConstructBinMappers(int rank, int num_machines,
         const std::vector<std::string>& sample_data);

  /*! \brief Extract local features from memory */
  void ExtractFeaturesFromMemory();

  /*! \brief Extract local features from file */
  void ExtractFeaturesFromFile();

  /*! \brief Check can load from binary file */
  void CheckCanLoadFromBin();

  /*!
  * \brief Load data set from binary file
  * \param rank Rank of local machine
  * \param num_machines Total number of all machines
  * \param is_pre_partition True if data file is pre-partitioned
  */
  void LoadDataFromBinFile(int rank, int num_machines, bool is_pre_partition);

  /*! \brief Check this data set is null or not */
  void CheckDataset();

  /*! \brief Filename of data */
  const char* data_filename_;
  /*! \brief A reader class that can read text data */
  TextReader<data_size_t>* text_reader_;
  /*! \brief A parser class that can parse data */
  Parser* parser_;
  /*! \brief Store used features */
  std::vector<Feature*> features_;
  /*! \brief Mapper from real feature index to used index*/
  std::vector<int> used_feature_map_;
  /*! \brief Number of used features*/
  int num_features_;
397
398
  /*! \brief Number of total features*/
  int num_total_features_;
Guolin Ke's avatar
Guolin Ke committed
399
400
401
402
403
404
405
406
407
408
409
410
411
412
  /*! \brief Number of total data*/
  data_size_t num_data_;
  /*! \brief Store some label level data*/
  Metadata metadata_;
  /*! \brief Random generator*/
  Random random_;
  /*! \brief The maximal number of bin that feature values will bucket in */
  int max_bin_;
  /*! \brief True if enable sparse */
  bool is_enable_sparse_;
  /*! \brief True if dataset is loaded from binary file */
  bool is_loading_from_binfile_;
  /*! \brief Number of global data, used for distributed learning */
  size_t global_num_data_ = 0;
Guolin Ke's avatar
Guolin Ke committed
413
  /*! \brief used to local used data indices */
Guolin Ke's avatar
Guolin Ke committed
414
  std::vector<data_size_t> used_data_indices_;
Guolin Ke's avatar
Guolin Ke committed
415
  /*! \brief prediction function for initial model */
Guolin Ke's avatar
Guolin Ke committed
416
  const PredictFunction& predict_fun_;
Guolin Ke's avatar
Guolin Ke committed
417
418
419
420
421
422
423
424
425
426
  /*! \brief index of label column */
  int label_idx_ = 0;
  /*! \brief index of weight column */
  int weight_idx_ = -1;
  /*! \brief index of group column */
  int group_idx_ = -1;
  /*! \brief Mapper from real feature index to used index*/
  std::unordered_set<int> ignore_features_;
  /*! \brief store feature names */
  std::vector<std::string> feature_names_;
Guolin Ke's avatar
Guolin Ke committed
427
428
429
430
};

}  // namespace LightGBM

Guolin Ke's avatar
Guolin Ke committed
431
#endif   // LightGBM_DATA_H_