random.h 1.72 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef LIGHTGBM_UTILS_RANDOM_H_
#define LIGHTGBM_UTILS_RANDOM_H_

#include <cstdint>

#include <random>
#include <vector>

namespace LightGBM {

/*!
* \brief A wrapper for random generator
*/
class Random {
public:
  /*!
  * \brief Constructor, with random seed
  */
Guolin Ke's avatar
Guolin Ke committed
19
  Random() {
Guolin Ke's avatar
Guolin Ke committed
20
    std::random_device rd;
Guolin Ke's avatar
Guolin Ke committed
21
22
23
    auto genrator = std::mt19937(rd());
    std::uniform_int_distribution<int> distribution(0, x);
    x = static_cast<unsigned int>(distribution(genrator));
Guolin Ke's avatar
Guolin Ke committed
24
25
26
27
  }
  /*!
  * \brief Constructor, with specific seed
  */
Guolin Ke's avatar
Guolin Ke committed
28
29
  Random(int seed) {
    x = static_cast<unsigned int>(seed);
Guolin Ke's avatar
Guolin Ke committed
30
31
32
33
34
35
36
  }
  /*!
  * \brief Generate random integer
  * \param lower_bound lower bound
  * \param upper_bound upper bound
  * \return The random integer between [lower_bound, upper_bound)
  */
Guolin Ke's avatar
Guolin Ke committed
37
  inline int NextInt(int lower_bound, int upper_bound) {
Guolin Ke's avatar
Guolin Ke committed
38
    return (fastrand()) % (upper_bound - lower_bound) + lower_bound;
Guolin Ke's avatar
Guolin Ke committed
39
40
41
42
43
  }
  /*!
  * \brief Generate random float data
  * \return The random float between [0.0, 1.0)
  */
Guolin Ke's avatar
Guolin Ke committed
44
  inline float NextFloat() {
Guolin Ke's avatar
Guolin Ke committed
45
    // get random float in [0,1)
Guolin Ke's avatar
Guolin Ke committed
46
    return static_cast<float>(fastrand()) / (32768.0f);
Guolin Ke's avatar
Guolin Ke committed
47
48
49
50
51
52
53
  }
  /*!
  * \brief Sample K data from {0,1,...,N-1}
  * \param N
  * \param K
  * \return K Ordered sampled data from {0,1,...,N-1}
  */
54
55
  inline std::vector<int> Sample(int N, int K) {
    std::vector<int> ret;
Guolin Ke's avatar
Guolin Ke committed
56
57
58
    if (K > N || K < 0) {
      return ret;
    }
59
    for (int i = 0; i < N; ++i) {
Guolin Ke's avatar
Guolin Ke committed
60
      double prob = (K - ret.size()) / static_cast<double>(N - i);
Guolin Ke's avatar
Guolin Ke committed
61
      if (NextFloat() < prob) {
Guolin Ke's avatar
Guolin Ke committed
62
63
64
65
66
67
        ret.push_back(i);
      }
    }
    return ret;
  }
private:
Guolin Ke's avatar
Guolin Ke committed
68
69
70
  inline int fastrand() {
    x = (214013 * x + 2531011);
    return (x >> 16) & 0x7FFF;
Guolin Ke's avatar
Guolin Ke committed
71
  }
Guolin Ke's avatar
Guolin Ke committed
72
  int x = 123456789;
Guolin Ke's avatar
Guolin Ke committed
73
74
};

Guolin Ke's avatar
Guolin Ke committed
75

Guolin Ke's avatar
Guolin Ke committed
76
77
}  // namespace LightGBM

Guolin Ke's avatar
Guolin Ke committed
78
#endif   // LightGBM_UTILS_RANDOM_H_