Medial Code Documentation
Loading...
Searching...
No Matches
random.h
1#ifndef LIGHTGBM_UTILS_RANDOM_H_
2#define LIGHTGBM_UTILS_RANDOM_H_
3
4#include <cstdint>
5
6#include <random>
7#include <vector>
8#include <set>
9
10namespace LightGBM {
11
15class Random {
16public:
21 std::random_device rd;
22 auto genrator = std::mt19937(rd());
23 std::uniform_int_distribution<int> distribution(0, x);
24 x = distribution(genrator);
25 }
29 Random(int seed) {
30 x = seed;
31 }
38 inline int NextShort(int lower_bound, int upper_bound) {
39 return (RandInt16()) % (upper_bound - lower_bound) + lower_bound;
40 }
41
48 inline int NextInt(int lower_bound, int upper_bound) {
49 return (RandInt32()) % (upper_bound - lower_bound) + lower_bound;
50 }
51
56 inline float NextFloat() {
57 // get random float in [0,1)
58 return static_cast<float>(RandInt16()) / (32768.0f);
59 }
66 inline std::vector<int> Sample(int N, int K) {
67 std::vector<int> ret;
68 ret.reserve(K);
69 if (K > N || K <= 0) {
70 return ret;
71 } else if (K == N) {
72 for (int i = 0; i < N; ++i) {
73 ret.push_back(i);
74 }
75 } else if (K > 1 && K > (N / std::log2(K))) {
76 for (int i = 0; i < N; ++i) {
77 double prob = (K - ret.size()) / static_cast<double>(N - i);
78 if (NextFloat() < prob) {
79 ret.push_back(i);
80 }
81 }
82 } else {
83 std::set<int> sample_set;
84 while (static_cast<int>(sample_set.size()) < K) {
85 int next = RandInt32() % N;
86 if (sample_set.count(next) == 0) {
87 sample_set.insert(next);
88 }
89 }
90 for (auto iter = sample_set.begin(); iter != sample_set.end(); ++iter) {
91 ret.push_back(*iter);
92 }
93 }
94 return ret;
95 }
96
97private:
98 inline int RandInt16() {
99 x = (214013 * x + 2531011);
100 return static_cast<int>((x >> 16) & 0x7FFF);
101 }
102
103 inline int RandInt32() {
104 x = (214013 * x + 2531011);
105 return static_cast<int>(x & 0x7FFFFFFF);
106 }
107
108 unsigned int x = 123456789;
109};
110
111
112} // namespace LightGBM
113
114#endif // LightGBM_UTILS_RANDOM_H_
A wrapper for random generator.
Definition random.h:15
Random(int seed)
Constructor, with specific seed.
Definition random.h:29
int NextShort(int lower_bound, int upper_bound)
Generate random integer, int16 range. [0, 65536].
Definition random.h:38
std::vector< int > Sample(int N, int K)
Sample K data from {0,1,...,N-1}.
Definition random.h:66
int NextInt(int lower_bound, int upper_bound)
Generate random integer, int32 range.
Definition random.h:48
float NextFloat()
Generate random float data.
Definition random.h:56
Random()
Constructor, with random seed.
Definition random.h:20
desc and descl2 fields must be written in reStructuredText format
Definition application.h:10