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

#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

namespace LightGBM {

/*! \brief forward declaration */
class Feature;
Guolin Ke's avatar
Guolin Ke committed
20
class BinMapper;
Guolin Ke's avatar
Guolin Ke committed
21
class DatasetLoader;
Guolin Ke's avatar
Guolin Ke committed
22
23

/*!
Hui Xue's avatar
Hui Xue committed
24
* \brief This class is used to store some meta(non-feature) data for training data,
Guolin Ke's avatar
Guolin Ke committed
25
26
*        e.g. labels, weights, initial scores, qurey level informations.
*
Qiwei Ye's avatar
Qiwei Ye committed
27
28
29
30
31
32
33
34
*        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
35
36
37
38
39
40
41
42
*/
class Metadata {
public:
 /*!
  * \brief Null costructor
  */
  Metadata();
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
43
  * \brief Initialization will load qurey level informations, since it is need for sampling data
Guolin Ke's avatar
Guolin Ke committed
44
45
  * \param data_filename Filename of data
  * \param init_score_filename Filename of initial score
46
  * \param num_class Number of classes
Guolin Ke's avatar
Guolin Ke committed
47
  */
Guolin Ke's avatar
Guolin Ke committed
48
  void Init(const char* data_filename, const int num_class);
Guolin Ke's avatar
Guolin Ke committed
49
50
51
52
53
54
55
56
57
  /*!
  * \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
58
  * \brief Initial work, will allocate space for label, weight(if exists) and query(if exists)
Guolin Ke's avatar
Guolin Ke committed
59
  * \param num_data Number of training data
60
  * \param num_class Number of classes
Guolin Ke's avatar
Guolin Ke committed
61
62
  * \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
63
  */
64
  void Init(data_size_t num_data, int num_class, int weight_idx, int query_idx);
Guolin Ke's avatar
Guolin Ke committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

  /*!
  * \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);

Guolin Ke's avatar
Guolin Ke committed
80
81
82
83
84
85
86

  void SetLabel(const float* label, data_size_t len);

  void SetWeights(const float* weights, data_size_t len);

  void SetQueryBoundaries(const data_size_t* QueryBoundaries, data_size_t len);

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


  /*!
  * \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
  */
116
  inline void SetLabelAt(data_size_t idx, float value)
Guolin Ke's avatar
Guolin Ke committed
117
  {
118
    label_[idx] = value;
Guolin Ke's avatar
Guolin Ke committed
119
120
  }

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

  /*!
  * \brief Set Query Id for one record
  * \param idx Index of this record
  * \param value Query Id value of this record
  */
Guolin Ke's avatar
Guolin Ke committed
136
  inline void SetQueryAt(data_size_t idx, data_size_t value)
Guolin Ke's avatar
Guolin Ke committed
137
138
139
140
  {
    queries_[idx] = static_cast<data_size_t>(value);
  }

Guolin Ke's avatar
Guolin Ke committed
141
  /*!
Hui Xue's avatar
Hui Xue committed
142
  * \brief Get weights, if not exists, will return nullptr
Guolin Ke's avatar
Guolin Ke committed
143
144
145
146
147
148
  * \return Pointer of weights
  */
  inline const float* weights()
            const { return weights_; }

  /*!
Hui Xue's avatar
Hui Xue committed
149
  * \brief Get data boundaries on queries, if not exists, will return nullptr
Guolin Ke's avatar
Guolin Ke committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
  *        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
165
  * \brief Get weights for queries, if not exists, will return nullptr
Guolin Ke's avatar
Guolin Ke committed
166
167
168
169
170
  * \return Pointer of weights for queries
  */
  inline const float* query_weights() const { return query_weights_; }

  /*!
Hui Xue's avatar
Hui Xue committed
171
  * \brief Get initial scores, if not exists, will return nullptr
Guolin Ke's avatar
Guolin Ke committed
172
173
  * \return Pointer of initial scores
  */
Guolin Ke's avatar
Guolin Ke committed
174
  inline const float* init_score() const { return init_score_; }
Guolin Ke's avatar
Guolin Ke committed
175
176

private:
Guolin Ke's avatar
Guolin Ke committed
177
178
  /*! \brief Load initial scores from file */
  void LoadInitialScore();
Guolin Ke's avatar
Guolin Ke committed
179
180
181
182
183
184
185
186
187
188
  /*! \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 Number of data */
  data_size_t num_data_;
189
190
  /*! \brief Number of classes */
  int num_class_;
Guolin Ke's avatar
Guolin Ke committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
  /*! \brief Number of weights, used to check correct weight file */
  data_size_t num_weights_;
  /*! \brief Label data */
  float* label_;
  /*! \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
206
  float* init_score_;
Guolin Ke's avatar
Guolin Ke committed
207
208
  /*! \brief Queries data */
  data_size_t* queries_;
Guolin Ke's avatar
Guolin Ke committed
209
210
211
212
213
214
};


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

Guolin Ke's avatar
Guolin Ke committed
216
217
218
219
220
221
  /*! \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
222
223
  * \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
224
225
  */
  virtual void ParseOneLine(const char* str,
226
    std::vector<std::pair<int, double>>* out_features, double* out_label) const = 0;
Guolin Ke's avatar
Guolin Ke committed
227
228
229
230

  /*!
  * \brief Create a object of parser, will auto choose the format depend on file
  * \param filename One Filename of data
231
  * \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
232
  * \param label_idx index of label column
Guolin Ke's avatar
Guolin Ke committed
233
234
  * \return Object of parser
  */
Guolin Ke's avatar
Guolin Ke committed
235
  static Parser* CreateParser(const char* filename, bool has_header, int num_features, int label_idx);
Guolin Ke's avatar
Guolin Ke committed
236
237
238
};

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

/*! \brief The main class of data set,
*          which are used to traning or validation
*/
class Dataset {
public:
Guolin Ke's avatar
Guolin Ke committed
246
  friend DatasetLoader;
Guolin Ke's avatar
Guolin Ke committed
247

Guolin Ke's avatar
Guolin Ke committed
248
  Dataset();
Guolin Ke's avatar
Guolin Ke committed
249

Guolin Ke's avatar
Guolin Ke committed
250
251
252
  /*! \brief Destructor */
  ~Dataset();

Guolin Ke's avatar
Guolin Ke committed
253
254
255

  void SetField(const char* field_name, const void* field_data, data_size_t num_element, int type);

Guolin Ke's avatar
Guolin Ke committed
256
257
258
  /*!
  * \brief Save current dataset into binary file, will save to "filename.bin"
  */
Guolin Ke's avatar
Guolin Ke committed
259
  void SaveBinaryFile(const char* bin_filename);
Guolin Ke's avatar
Guolin Ke committed
260

Guolin Ke's avatar
Guolin Ke committed
261
262
  std::vector<const BinMapper*> GetBinMappers() const;

Guolin Ke's avatar
Guolin Ke committed
263
264
  void CopyFeatureMetadataTo(Dataset *dataset, bool is_enable_sparse) const;

Guolin Ke's avatar
Guolin Ke committed
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
  /*!
  * \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_; }

281
282
283
  /*! \brief Get Number of total features */
  inline int num_total_features() const { return num_total_features_; }

Guolin Ke's avatar
Guolin Ke committed
284
285
286
287
288
289
  /*! \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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
  /*! \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:
  const char* data_filename_;
  /*! \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_;
306
307
  /*! \brief Number of total features*/
  int num_total_features_;
Guolin Ke's avatar
Guolin Ke committed
308
309
  /*! \brief Number of total data*/
  data_size_t num_data_;
310
311
  /*! \brief Number of classes*/
  int num_class_;
Guolin Ke's avatar
Guolin Ke committed
312
313
314
315
  /*! \brief Store some label level data*/
  Metadata metadata_;
  /*! \brief True if dataset is loaded from binary file */
  bool is_loading_from_binfile_;
Guolin Ke's avatar
Guolin Ke committed
316
317
318
319
  /*! \brief index of label column */
  int label_idx_ = 0;
  /*! \brief store feature names */
  std::vector<std::string> feature_names_;
Guolin Ke's avatar
Guolin Ke committed
320
321
322
323
};

}  // namespace LightGBM

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