Random Numbers¶
Global random number generator¶
The Shark machine learning library provides many functions for drawing random numbers.
We start with the following header files:
#include <shark/Core/Random.h>
#include <shark/Statistics/Distributions/MultiVariateNormalDistribution.h>
using namespace shark;
using namespace std;
It provides access to a global random number generator and convenience functions to draw from the following distributions:
- Bernoulli with name
coinToss
- DiscreteUniform with name discrete`
- Uniform with name
uni
- Normal with name
gauss
- Cauchy with name
cauchy
- Geometric with name
geom
- DiffGeometric with name
diffGeom
- Poisson with name
poisson
- Gamma with name
gam`
- Dirichlet with name
dir
Examples:
bool rn1 = random::coinToss( );
long rn2 = random::discrete( );
double rn3 = random::uni( );
double rn4 = random::gauss( );
double rn5 = random::cauchy( );
long rn6 = random::geom( );
long rn7 = random::diffGeom( );
You can set the seed of the global random number generator by:
random::seed( 1234 );
Examples of distributions¶
Some examples of distributions:
Weibull<> dist1( shark::random::globalrandom );
Bernoulli<> dist2( shark::random::globalrandom );
Binomial<> dist3( shark::random::globalrandom );
Cauchy<> dist4( shark::random::globalrandom );
DiffGeometric<> dist5( shark::random::globalrandom );
Dirichlet<> dist6( shark::random::globalrandom );
DiscreteUniform<> dist7( shark::random::globalrandom );
Erlang<> dist8( shark::random::globalrandom );
Gamma<> dist9( shark::random::globalrandom );
Geometric<> dist10( shark::random::globalrandom );
HyperGeometric<> dist12( shark::random::globalrandom );
LogNormal<> dist13( shark::random::globalrandom );
NegExponential<> dist14( shark::random::globalrandom );
Normal<> dist15( shark::random::globalrandom );
Poisson<> dist16( shark::random::globalrandom );
Uniform<> dist17( shark::random::globalrandom );
This example shows how to access the mean and variance of a normal distribution with mean one and unit variance:
Normal< random::rng_type > normal( random::globalrandom, 1., 1. );
double mean = normal.mean();
double variance = normal.variance();
cout << mean << " (" << variance << ")" << endl;
Here’s an example of a uniform distribution over the real numbers from 1 to 5:
Uniform< shark::random::rng_type > uniform( shark::random::globalrandom, 1, 5 );
Multivariate normal distribution¶
The following code shows how to sample from a mean-free multivariate Gaussian distribution:
RealMatrix Sigma(2,2);
Sigma(0,0) = 1;
Sigma(0,1) = 2;
Sigma(1,0) = .5;
Sigma(1,1) = 1;
MultiVariateNormalDistribution M(Sigma);
for(unsigned i=0; i<100; i++) {
cout << M().first(0) << " " << M().first(1) << endl;
}
Here the sampling is special, because not only the realization of the
random vector is returned, but also the realization of the standard
normally distributed random vector from which it was
generated. Therefore, the realization has to be accessed using
first
.