diff --git a/examples/undocumented/libshogun/classifier_latent_svm.cpp b/examples/undocumented/libshogun/classifier_latent_svm.cpp index 18471b8d506..c39b1faadc4 100644 --- a/examples/undocumented/libshogun/classifier_latent_svm.cpp +++ b/examples/undocumented/libshogun/classifier_latent_svm.cpp @@ -115,7 +115,6 @@ static void read_dataset(char* fname, CLatentFeatures*& feats, CLatentLabels*& l SG_REF(feats); auto pb = progress(range(num_examples)); - CMath::init_random(); for (int i = 0; (!feof(fd)) && (i < num_examples); ++i) { fgets(line, MAX_LINE_LENGTH, fd); diff --git a/examples/undocumented/libshogun/evaluation_cross_validation_multiclass_mkl.cpp b/examples/undocumented/libshogun/evaluation_cross_validation_multiclass_mkl.cpp index eb83866eaf0..5d151d27aa1 100644 --- a/examples/undocumented/libshogun/evaluation_cross_validation_multiclass_mkl.cpp +++ b/examples/undocumented/libshogun/evaluation_cross_validation_multiclass_mkl.cpp @@ -33,9 +33,7 @@ const char fname_labels[]="../data/label_train_multiclass.dat"; void test_multiclass_mkl_cv() { - /* init random number generator for reproducible results of cross-validation in the light of ASSERT(result->mean>0.81); some lines down below */ - sg_rand->set_seed(12); - + CMath::init_random(12); /* dense features from matrix */ CCSVFile* feature_file = new CCSVFile(fname_feats); SGMatrix mat=SGMatrix(); @@ -89,6 +87,7 @@ void test_multiclass_mkl_cv() CMulticlassAccuracy* eval_crit=new CMulticlassAccuracy(); CStratifiedCrossValidationSplitting* splitting= new CStratifiedCrossValidationSplitting(labels, n_folds); + splitting->set_seed(12); CCrossValidation *cross=new CCrossValidation(mkl, cfeats, labels, splitting, eval_crit); cross->set_autolock(false); diff --git a/src/shogun/base/SGObject.cpp b/src/shogun/base/SGObject.cpp index cbf3b607ff8..02e42eb2be4 100644 --- a/src/shogun/base/SGObject.cpp +++ b/src/shogun/base/SGObject.cpp @@ -494,6 +494,7 @@ void CSGObject::init() m_parameters = new Parameter(); m_model_selection_parameters = new Parameter(); m_gradient_parameters=new Parameter(); + m_rng = std::unique_ptr(new CRandom()); m_generic = PT_NOT_GENERIC; m_load_pre_called = false; m_load_post_called = false; @@ -800,3 +801,8 @@ bool CSGObject::type_erased_has(const BaseTag& _tag) const { return self->has(_tag); } + +void CSGObject::set_seed(int32_t seed) +{ + m_rng->set_seed(seed); +} diff --git a/src/shogun/base/SGObject.h b/src/shogun/base/SGObject.h index 6a95453b524..ebd013a2b60 100644 --- a/src/shogun/base/SGObject.h +++ b/src/shogun/base/SGObject.h @@ -23,6 +23,8 @@ #include #include +#include + /** \namespace shogun * @brief all of classes and functions are contained in the shogun namespace */ @@ -33,6 +35,7 @@ class SGIO; class Parallel; class Parameter; class CSerializableFile; +class CRandom; template class CMap; @@ -491,6 +494,11 @@ class CSGObject */ virtual CSGObject* clone(); + /** Set random seed + * @param seed seed for random generator + */ + void set_seed(int32_t seed); + protected: /* Iteratively clones all parameters of the provided instance into this instance. * This will fail if the objects have different sets of registered parameters, @@ -567,6 +575,10 @@ class CSGObject /** Hash of parameter values*/ uint32_t m_hash; +protected: + /** random generator */ + std::unique_ptr m_rng; + private: EPrimitiveType m_generic; diff --git a/src/shogun/base/init.cpp b/src/shogun/base/init.cpp index 104636e925d..bccbcbb2332 100644 --- a/src/shogun/base/init.cpp +++ b/src/shogun/base/init.cpp @@ -38,7 +38,7 @@ namespace shogun SGIO* sg_io=NULL; Version* sg_version=NULL; CMath* sg_math=NULL; - CRandom* sg_rand=NULL; + std::unique_ptr sg_linalg(nullptr); /// function called to print normal messages @@ -67,8 +67,6 @@ namespace shogun sg_version = new shogun::Version(); if (!sg_math) sg_math = new shogun::CMath(); - if (!sg_rand) - sg_rand = new shogun::CRandom(); if (!sg_linalg) sg_linalg = std::unique_ptr(new shogun::SGLinalg()); @@ -82,7 +80,6 @@ namespace shogun SG_REF(sg_parallel); SG_REF(sg_version); SG_REF(sg_math); - SG_REF(sg_rand); sg_print_message=print_message; sg_print_warning=print_warning; @@ -116,7 +113,6 @@ namespace shogun sg_print_error=NULL; sg_cancel_computations=NULL; - SG_UNREF(sg_rand); SG_UNREF(sg_math); SG_UNREF(sg_version); SG_UNREF(sg_parallel); @@ -179,18 +175,6 @@ namespace shogun return sg_math; } - void set_global_rand(CRandom* rand) - { - SG_REF(rand); - SG_UNREF(sg_rand); - sg_rand=rand; - } - - CRandom* get_global_rand() - { - SG_REF(sg_rand); - return sg_rand; - } #ifndef SWIG // SWIG should skip this part SGLinalg* get_global_linalg() { diff --git a/src/shogun/base/init.h b/src/shogun/base/init.h index 7f60097496a..8856ae6cad8 100644 --- a/src/shogun/base/init.h +++ b/src/shogun/base/init.h @@ -97,18 +97,6 @@ void set_global_math(CMath* math); */ CMath* get_global_math(); -/** set the global random object - * - * @param rand random object to use - */ -void set_global_rand(CRandom* rand); - -/** get the global random object - * - * @return random object - */ -CRandom* get_global_rand(); - #ifndef SWIG // SWIG should skip this part /** get the global linalg library object * diff --git a/src/shogun/clustering/KMeansMiniBatch.cpp b/src/shogun/clustering/KMeansMiniBatch.cpp index cb871935dbf..bf51be3e68b 100644 --- a/src/shogun/clustering/KMeansMiniBatch.cpp +++ b/src/shogun/clustering/KMeansMiniBatch.cpp @@ -131,11 +131,12 @@ SGVector CKMeansMiniBatch::mbchoose_rand(int32_t b, int32_t num) { SGVector chosen=SGVector(num); SGVector ret=SGVector(b); + auto rng = std::unique_ptr(new CRandom()); chosen.zero(); int32_t ch=0; while (chrandom(0, num - 1); if (chosen[n]==0) { chosen[n]+=1; diff --git a/src/shogun/distributions/classical/GaussianDistribution.cpp b/src/shogun/distributions/classical/GaussianDistribution.cpp index 20ab09aef83..9c562166d67 100644 --- a/src/shogun/distributions/classical/GaussianDistribution.cpp +++ b/src/shogun/distributions/classical/GaussianDistribution.cpp @@ -91,7 +91,7 @@ SGMatrix CGaussianDistribution::sample(int32_t num_samples, /* allocate memory and sample from std normal */ samples=SGMatrix(m_dimension, num_samples); for (index_t i=0; istd_normal_distrib(); + samples.matrix[i] = m_rng->std_normal_distrib(); } /* map into desired Gaussian covariance */ diff --git a/src/shogun/evaluation/CrossValidationSplitting.cpp b/src/shogun/evaluation/CrossValidationSplitting.cpp index f4b940ec269..de2b6964b17 100644 --- a/src/shogun/evaluation/CrossValidationSplitting.cpp +++ b/src/shogun/evaluation/CrossValidationSplitting.cpp @@ -16,14 +16,12 @@ using namespace shogun; CCrossValidationSplitting::CCrossValidationSplitting() : CSplittingStrategy() { - m_rng = sg_rand; } CCrossValidationSplitting::CCrossValidationSplitting( CLabels* labels, index_t num_subsets) : CSplittingStrategy(labels, num_subsets) { - m_rng = sg_rand; } void CCrossValidationSplitting::build_subsets() @@ -35,7 +33,7 @@ void CCrossValidationSplitting::build_subsets() /* permute indices */ SGVector indices(m_labels->get_num_labels()); indices.range_fill(); - CMath::permute(indices, m_rng); + CMath::permute(indices, m_rng.get()); index_t num_subsets=m_subset_indices->get_num_elements(); @@ -60,5 +58,5 @@ void CCrossValidationSplitting::build_subsets() /* finally shuffle to avoid that subsets with low indices have more * elements, which happens if the number of class labels is not equal to * the number of subsets (external random state important for threads) */ - m_subset_indices->shuffle(m_rng); + m_subset_indices->shuffle(m_rng.get()); } diff --git a/src/shogun/evaluation/CrossValidationSplitting.h b/src/shogun/evaluation/CrossValidationSplitting.h index 62a97c808a2..9394342dc92 100644 --- a/src/shogun/evaluation/CrossValidationSplitting.h +++ b/src/shogun/evaluation/CrossValidationSplitting.h @@ -45,9 +45,6 @@ class CCrossValidationSplitting: public CSplittingStrategy /** implementation of the standard cross-validation splitting strategy */ virtual void build_subsets(); - - /** custom rng if using cross validation across different threads */ - CRandom * m_rng; }; } diff --git a/src/shogun/evaluation/StratifiedCrossValidationSplitting.cpp b/src/shogun/evaluation/StratifiedCrossValidationSplitting.cpp index b7bfb9e9628..206f4829d2f 100644 --- a/src/shogun/evaluation/StratifiedCrossValidationSplitting.cpp +++ b/src/shogun/evaluation/StratifiedCrossValidationSplitting.cpp @@ -18,7 +18,6 @@ using namespace shogun; CStratifiedCrossValidationSplitting::CStratifiedCrossValidationSplitting() : CSplittingStrategy() { - m_rng = sg_rand; } CStratifiedCrossValidationSplitting::CStratifiedCrossValidationSplitting( @@ -70,7 +69,6 @@ CStratifiedCrossValidationSplitting::CStratifiedCrossValidationSplitting( } } - m_rng = sg_rand; } void CStratifiedCrossValidationSplitting::build_subsets() @@ -124,7 +122,7 @@ void CStratifiedCrossValidationSplitting::build_subsets() label_indices.get_element(i); // external random state important for threads - current->shuffle(m_rng); + current->shuffle(m_rng.get()); SG_UNREF(current); } @@ -152,5 +150,5 @@ void CStratifiedCrossValidationSplitting::build_subsets() /* finally shuffle to avoid that subsets with low indices have more * elements, which happens if the number of class labels is not equal to * the number of subsets (external random state important for threads) */ - m_subset_indices->shuffle(m_rng); + m_subset_indices->shuffle(m_rng.get()); } diff --git a/src/shogun/evaluation/StratifiedCrossValidationSplitting.h b/src/shogun/evaluation/StratifiedCrossValidationSplitting.h index 7898784e457..7843bbedc2a 100644 --- a/src/shogun/evaluation/StratifiedCrossValidationSplitting.h +++ b/src/shogun/evaluation/StratifiedCrossValidationSplitting.h @@ -47,9 +47,6 @@ class CStratifiedCrossValidationSplitting: public CSplittingStrategy /** implementation of the stratified cross-validation splitting strategy */ virtual void build_subsets(); - - /** custom rng if using cross validation across different threads */ - CRandom * m_rng; }; } diff --git a/src/shogun/mathematics/Math.cpp b/src/shogun/mathematics/Math.cpp index adf58828ab0..ae6ffb4b7fc 100644 --- a/src/shogun/mathematics/Math.cpp +++ b/src/shogun/mathematics/Math.cpp @@ -36,6 +36,8 @@ int32_t CMath::LOGACCURACY = 0; // 100000 steps per integer int32_t CMath::LOGRANGE = 0; // range for logtable: log(1+exp(x)) -25 <= x <= 0 +CRandom* CMath::m_rng = new CRandom(12345); + const float64_t CMath::NOT_A_NUMBER = NAN; const float64_t CMath::INFTY = INFINITY; // infinity const float64_t CMath::ALMOST_INFTY = +1e+300; //a large number @@ -54,7 +56,6 @@ const float64_t CMath::F_MIN_VAL64=(DBL_MIN * DBL_EPSILON); #ifdef USE_LOGCACHE float64_t* CMath::logtable = NULL; #endif -uint32_t CMath::seed = 0; CMath::CMath() : CSGObject() diff --git a/src/shogun/mathematics/Math.h b/src/shogun/mathematics/Math.h index 021b4bb214a..143506084b5 100644 --- a/src/shogun/mathematics/Math.h +++ b/src/shogun/mathematics/Math.h @@ -123,8 +123,6 @@ static inline complex128_t function(complex128_t a) \ namespace shogun { - /** random number generator */ - extern CRandom* sg_rand; /** @brief Class which collects generic mathematical functions */ class CMath : public CSGObject @@ -1001,11 +999,9 @@ class CMath : public CSGObject static void init_random(uint32_t initseed=0) { if (initseed==0) - seed = CRandom::generate_seed(); + m_rng->set_seed(CRandom::generate_seed()); else - seed=initseed; - - sg_rand->set_seed(seed); + m_rng->set_seed(initseed); } /** Returns random number @@ -1013,7 +1009,8 @@ class CMath : public CSGObject */ static inline uint64_t random() { - return sg_rand->random_64(); + uint64_t result = m_rng->random_64(); + return result; } /** Returns random number @@ -1021,7 +1018,8 @@ class CMath : public CSGObject */ static inline uint64_t random(uint64_t min_value, uint64_t max_value) { - return sg_rand->random(min_value, max_value); + uint64_t result = m_rng->random(min_value, max_value); + return result; } /** Returns random number between minimum and maximum value @@ -1031,7 +1029,8 @@ class CMath : public CSGObject */ static inline int64_t random(int64_t min_value, int64_t max_value) { - return sg_rand->random(min_value, max_value); + int64_t result = m_rng->random(min_value, max_value); + return result; } /** Returns random number between minimum and maximum value @@ -1041,7 +1040,8 @@ class CMath : public CSGObject */ static inline uint32_t random(uint32_t min_value, uint32_t max_value) { - return sg_rand->random(min_value, max_value); + uint32_t result = m_rng->random(min_value, max_value); + return result; } /** Returns random number between minimum and maximum value @@ -1051,7 +1051,8 @@ class CMath : public CSGObject */ static inline int32_t random(int32_t min_value, int32_t max_value) { - return sg_rand->random(min_value, max_value); + int32_t result = m_rng->random(min_value, max_value); + return result; } /** Returns random number between minimum and maximum value @@ -1061,7 +1062,8 @@ class CMath : public CSGObject */ static inline float32_t random(float32_t min_value, float32_t max_value) { - return sg_rand->random(min_value, max_value); + float32_t result = m_rng->random(min_value, max_value); + return result; } /** Returns random number between minimum and maximum value @@ -1071,7 +1073,8 @@ class CMath : public CSGObject */ static inline float64_t random(float64_t min_value, float64_t max_value) { - return sg_rand->random(min_value, max_value); + float64_t result = m_rng->random(min_value, max_value); + return result; } /** Returns random number between minimum and maximum value @@ -1081,7 +1084,8 @@ class CMath : public CSGObject */ static inline floatmax_t random(floatmax_t min_value, floatmax_t max_value) { - return sg_rand->random(min_value, max_value); + floatmax_t result = m_rng->random(min_value, max_value); + return result; } /// Returns a Gaussian or Normal random number. @@ -1112,7 +1116,8 @@ class CMath : public CSGObject /// http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Polar_form static inline float64_t normal_random(float64_t mean, float64_t std_dev) { - return sg_rand->normal_distrib(mean, std_dev); + float64_t result = m_rng->normal_distrib(mean, std_dev); + return result; } /// Convenience method for generating Standard Normal random numbers @@ -1126,7 +1131,8 @@ class CMath : public CSGObject /// Double: Mean = 0 and Standard Deviation = 1 static inline float64_t randn_double() { - return sg_rand->std_normal_distrib(); + float64_t result = m_rng->std_normal_distrib(); + return result; } //@} @@ -1948,12 +1954,6 @@ class CMath : public CSGObject return c.imag(); } - /// returns number generator seed - inline static uint32_t get_seed() - { - return CMath::seed; - } - /// returns range of logtable inline static uint32_t get_log_range() { @@ -2092,12 +2092,11 @@ class CMath : public CSGObject static const float32_t F_MIN_VAL32; static const float64_t F_MIN_VAL64; - protected: - /// range for logtable: log(1+exp(x)) -LOGRANGE <= x <= 0 - static int32_t LOGRANGE; + static CRandom* m_rng; - /// random generator seed - static uint32_t seed; + protected: + /// range for logtable: log(1+exp(x)) -LOGRANGE <= x <= 0 + static int32_t LOGRANGE; #ifdef USE_LOGCACHE diff --git a/src/shogun/mathematics/Random.h b/src/shogun/mathematics/Random.h index 7241a8d915a..444f41e7a2b 100644 --- a/src/shogun/mathematics/Random.h +++ b/src/shogun/mathematics/Random.h @@ -13,10 +13,11 @@ #include +#include #include -#include #include -#include +#include +#include /* opaque pointers */ struct SFMT_T; @@ -31,7 +32,7 @@ namespace shogun * number generator. * * */ - class CRandom : public CSGObject + class CRandom { public: /** default ctor */ diff --git a/src/shogun/mathematics/linalg/ratapprox/tracesampler/NormalSampler.cpp b/src/shogun/mathematics/linalg/ratapprox/tracesampler/NormalSampler.cpp index ea804e1bc4b..bcae35d6912 100644 --- a/src/shogun/mathematics/linalg/ratapprox/tracesampler/NormalSampler.cpp +++ b/src/shogun/mathematics/linalg/ratapprox/tracesampler/NormalSampler.cpp @@ -43,7 +43,7 @@ SGVector CNormalSampler::sample(index_t idx) const SGVector s(m_dimension); for (index_t i=0; istd_normal_distrib(); + s[i] = m_rng->std_normal_distrib(); return s; } diff --git a/src/shogun/mathematics/linalg/ratapprox/tracesampler/ProbingSampler.cpp b/src/shogun/mathematics/linalg/ratapprox/tracesampler/ProbingSampler.cpp index 944d316eed7..5324d98131d 100644 --- a/src/shogun/mathematics/linalg/ratapprox/tracesampler/ProbingSampler.cpp +++ b/src/shogun/mathematics/linalg/ratapprox/tracesampler/ProbingSampler.cpp @@ -201,7 +201,7 @@ SGVector CProbingSampler::sample(index_t idx) const { if (m_coloring_vector[i]==idx) { - float64_t x=sg_rand->std_normal_distrib(); + float64_t x = m_rng->std_normal_distrib(); s[i]=(x>0)-(x<0); } } diff --git a/src/shogun/statistical_testing/MMD.cpp b/src/shogun/statistical_testing/MMD.cpp index 61db75e527f..abb79224172 100644 --- a/src/shogun/statistical_testing/MMD.cpp +++ b/src/shogun/statistical_testing/MMD.cpp @@ -51,14 +51,17 @@ struct CMMD::Self stype = DEFAULT_STYPE; null_approximation_method = DEFAULT_NULL_APPROXIMATION_METHOD; strategy=unique_ptr(new CKernelSelectionStrategy()); + seed = DEFAULT_NUM_OF_SEED; } index_t num_null_samples; EStatisticType stype; ENullApproximationMethod null_approximation_method; std::unique_ptr strategy; + int32_t seed; static constexpr index_t DEFAULT_NUM_NULL_SAMPLES = 250; + static constexpr int32_t DEFAULT_NUM_OF_SEED = 12345; static constexpr EStatisticType DEFAULT_STYPE = ST_UNBIASED_FULL; static constexpr ENullApproximationMethod DEFAULT_NULL_APPROXIMATION_METHOD = NAM_PERMUTATION; }; @@ -136,6 +139,16 @@ index_t CMMD::get_num_null_samples() const return self->num_null_samples; } +void CMMD::set_random_seed(int32_t p_seed) +{ + self->seed = p_seed; +} + +index_t CMMD::get_random_seed() const +{ + return self->seed; +} + void CMMD::set_statistic_type(EStatisticType stype) { self->stype=stype; diff --git a/src/shogun/statistical_testing/MMD.h b/src/shogun/statistical_testing/MMD.h index 61755fbc7ad..69b523d7583 100644 --- a/src/shogun/statistical_testing/MMD.h +++ b/src/shogun/statistical_testing/MMD.h @@ -222,6 +222,16 @@ class CMMD : public CTwoSampleTest /** @return Number of null-samples */ index_t get_num_null_samples() const; + /** + * Method to sets random seed for CrossValidation. + * + * @param p_seed seed for random generator. + */ + void set_random_seed(int32_t p_seed); + + /** @return seed of random */ + index_t get_random_seed() const; + /** * Method that sets the type of the estimator for MMD^2 * diff --git a/src/shogun/statistical_testing/kernelselection/internals/MaxCrossValidation.cpp b/src/shogun/statistical_testing/kernelselection/internals/MaxCrossValidation.cpp index 41958b55f62..87eaf01ad1b 100644 --- a/src/shogun/statistical_testing/kernelselection/internals/MaxCrossValidation.cpp +++ b/src/shogun/statistical_testing/kernelselection/internals/MaxCrossValidation.cpp @@ -97,12 +97,14 @@ void MaxCrossValidation::compute_measures() auto Ny=estimator->get_num_samples_q(); auto num_null_samples=estimator->get_num_null_samples(); auto stype=estimator->get_statistic_type(); + auto seed = estimator->get_random_seed(); CrossValidationMMD compute(Nx, Ny, num_folds, num_null_samples); compute.m_stype=stype; compute.m_alpha=alpha; compute.m_num_runs=num_runs; compute.m_rejections=rejections; - + compute.m_kfold_x->set_seed(seed); + compute.m_kfold_y->set_seed(seed); if (kernel_mgr.same_distance_type()) { CDistance* distance=kernel_mgr.get_distance_instance(); diff --git a/src/shogun/structure/FactorGraphDataGenerator.cpp b/src/shogun/structure/FactorGraphDataGenerator.cpp index 63f4a19b59d..ebbfcb4a8b6 100644 --- a/src/shogun/structure/FactorGraphDataGenerator.cpp +++ b/src/shogun/structure/FactorGraphDataGenerator.cpp @@ -104,7 +104,7 @@ void CFactorGraphDataGenerator::truncate_energy(float64_t &A, float64_t &B, floa CFactorGraph* CFactorGraphDataGenerator::random_chain_graph(SGVector &assignment_expect, float64_t &min_energy_expect, int32_t N) { - CMath::init_random(17); + m_rng->set_seed(17); // ftype SGVector card(2); @@ -133,8 +133,8 @@ CFactorGraph* CFactorGraphDataGenerator::random_chain_graph(SGVector &assig for (int32_t x = 0; x < N; ++x) { SGVector data(2); - data[0] = CMath::random(0.0, 1.0); - data[1] = CMath::random(0.0, 1.0); + data[0] = m_rng->random(0.0, 1.0); + data[1] = m_rng->random(0.0, 1.0); SGVector var_index(1); var_index[0] = y * N + x; @@ -150,10 +150,10 @@ CFactorGraph* CFactorGraphDataGenerator::random_chain_graph(SGVector &assig if (x > 0) { SGVector data(4); - float64_t A = CMath::random(0.0, 1.0);//E(0,0)->A - float64_t C = CMath::random(0.0, 1.0);//E(1,0)->C - float64_t B = CMath::random(0.0, 1.0);//E(0,1)->B - float64_t D = CMath::random(0.0, 1.0);//E(1,1)->D + float64_t A = m_rng->random(0.0, 1.0); // E(0,0)->A + float64_t C = m_rng->random(0.0, 1.0); // E(1,0)->C + float64_t B = m_rng->random(0.0, 1.0); // E(0,1)->B + float64_t D = m_rng->random(0.0, 1.0); // E(1,1)->D // Add truncation to ensure submodularity truncate_energy(A, B, C, D); @@ -173,10 +173,10 @@ CFactorGraph* CFactorGraphDataGenerator::random_chain_graph(SGVector &assig if (x == 0 && y > 0) { SGVector data(4); - float64_t A = CMath::random(0.0, 1.0);//E(0,0)->A - float64_t C = CMath::random(0.0, 1.0);//E(1,0)->C - float64_t B = CMath::random(0.0, 1.0);//E(0,1)->B - float64_t D = CMath::random(0.0, 1.0);//E(1,1)->D + float64_t A = m_rng->random(0.0, 1.0); // E(0,0)->A + float64_t C = m_rng->random(0.0, 1.0); // E(1,0)->C + float64_t B = m_rng->random(0.0, 1.0); // E(0,1)->B + float64_t D = m_rng->random(0.0, 1.0); // E(1,1)->D // Add truncation to ensure submodularity truncate_energy(A, B, C, D); @@ -355,7 +355,7 @@ void CFactorGraphDataGenerator::generate_data(int32_t len_label, int32_t len_fea // generate feature vector SGVector random_indices(len_feat); random_indices.range_fill(); - CMath::permute(random_indices); + CMath::permute(random_indices, m_rng.get()); SGVector v_feat(len_feat); v_feat.zero(); @@ -494,7 +494,7 @@ float64_t CFactorGraphDataGenerator::test_sosvm(EMAPInferType infer_type) SGMatrix feats_train; // Generate random data - sg_rand->set_seed(10); // fix the random seed + m_rng->set_seed(10); // fix the random seed generate_data(4, 12, 8, feats_train, labels_train); int32_t num_sample_train = labels_train.num_cols; diff --git a/src/shogun/structure/StochasticSOSVM.cpp b/src/shogun/structure/StochasticSOSVM.cpp index 5d07dfcae71..e32bca66603 100644 --- a/src/shogun/structure/StochasticSOSVM.cpp +++ b/src/shogun/structure/StochasticSOSVM.cpp @@ -108,7 +108,7 @@ bool CStochasticSOSVM::train_machine(CFeatures* data) m_debug_multiplier = 100; } - CMath::init_random(m_rand_seed); + m_rng->set_seed(m_rand_seed); // Main loop int32_t k = 0; @@ -117,7 +117,7 @@ bool CStochasticSOSVM::train_machine(CFeatures* data) for (int32_t si = 0; si < N; ++si) { // 1) Picking random example - int32_t i = CMath::random(0, N-1); + int32_t i = m_rng->random(0, N - 1); // 2) solve the loss-augmented inference for point i CResultSet* result = m_model->argmax(m_w, i); diff --git a/tests/unit/distribution/MixtureModel_unittest.cc b/tests/unit/distribution/MixtureModel_unittest.cc index d773495b3ed..42080da3994 100644 --- a/tests/unit/distribution/MixtureModel_unittest.cc +++ b/tests/unit/distribution/MixtureModel_unittest.cc @@ -40,9 +40,8 @@ using namespace shogun; TEST(MixtureModel,gaussian_mixture_model) { - sg_rand->set_seed(2); SGMatrix data(1,400); - + CMath::init_random(2); for (int32_t i=0;i<100;i++) data(0,i)=CMath::randn_double(); for (int32_t i=100;i<400;i++) diff --git a/tests/unit/ensemble/MajorityVote_unittest.cc b/tests/unit/ensemble/MajorityVote_unittest.cc index 3e9da8cf933..4999fcc998c 100644 --- a/tests/unit/ensemble/MajorityVote_unittest.cc +++ b/tests/unit/ensemble/MajorityVote_unittest.cc @@ -45,9 +45,10 @@ TEST(MajorityVote, binary_combine_vector) expected.zero(); v.zero(); + auto m_rng = std::unique_ptr(new CRandom()); for (index_t i = 0; i < num_classifiers; ++i) { - int32_t r = sg_rand->random(0, 1); + int32_t r = m_rng->random(0, 1); v[i] = (r == 0) ? -1 : r; if (max < ++expected[r]) @@ -72,12 +73,12 @@ TEST(MajorityVote, multiclass_combine_vector) v.zero(); hist.zero(); - + auto m_rng = std::unique_ptr(new CRandom()); int64_t max_label = -1; int64_t max = -1; for (index_t i = 0; i < num_classifiers; ++i) { - v[i] = sg_rand->random(0, 2); + v[i] = m_rng->random(0, 2); if (max < ++hist[index_t(v[i])]) { max = hist[index_t(v[i])]; diff --git a/tests/unit/ensemble/WeightedMajorityVote_unittest.cc b/tests/unit/ensemble/WeightedMajorityVote_unittest.cc index 25601a9b1e1..bcdfcfd8c61 100644 --- a/tests/unit/ensemble/WeightedMajorityVote_unittest.cc +++ b/tests/unit/ensemble/WeightedMajorityVote_unittest.cc @@ -11,6 +11,7 @@ void generate_random_ensemble_matrix(SGMatrix& em, const SGVector& w) { int32_t num_classes = 3; + auto m_rng = std::unique_ptr(new CRandom()); for (index_t i = 0; i < em.num_rows; ++i) { SGVector hist(num_classes); @@ -18,7 +19,7 @@ void generate_random_ensemble_matrix(SGMatrix& em, float64_t max = CMath::ALMOST_NEG_INFTY; for (index_t j = 0; j < em.num_cols; ++j) { - int32_t r = sg_rand->random(0, num_classes-1); + int32_t r = m_rng->random(0, num_classes - 1); em(i,j) = r; hist[r] += w[j]; // if there's a tie mark it the first element will be the winner @@ -69,10 +70,10 @@ TEST(WeightedMajorityVote, binary_combine_vector) expected.zero(); v.zero(); - + auto m_rng = std::unique_ptr(new CRandom()); for (index_t i = 0; i < num_classifiers; ++i) { - int32_t r = sg_rand->random(0, 1); + int32_t r = m_rng->random(0, 1); v[i] = (r == 0) ? -1 : r; expected[r] += weights[i]; @@ -95,6 +96,7 @@ TEST(WeightedMajorityVote, multiclass_combine_vector) SGVector weights(num_classifiers); weights.random(0.5, 2.0); CWeightedMajorityVote* mv = new CWeightedMajorityVote(weights); + auto m_rng = std::unique_ptr(new CRandom()); SGVector v(num_classifiers); SGVector hist(3); @@ -105,7 +107,7 @@ TEST(WeightedMajorityVote, multiclass_combine_vector) float64_t max = -1; for (index_t i = 0; i < num_classifiers; ++i) { - v[i] = sg_rand->random(0, 2); + v[i] = m_rng->random(0, 2); hist[index_t(v[i])] += weights[i]; if (max < hist[index_t(v[i])]) { diff --git a/tests/unit/environments/LinearTestEnvironment.h b/tests/unit/environments/LinearTestEnvironment.h index 89dd01f1c93..d349034391a 100644 --- a/tests/unit/environments/LinearTestEnvironment.h +++ b/tests/unit/environments/LinearTestEnvironment.h @@ -45,7 +45,6 @@ class LinearTestEnvironment : public ::testing::Environment public: virtual void SetUp() { - sg_rand->set_seed(17); mBinaryLabelData = std::shared_ptr( new GaussianCheckerboard(100, 2, 2)); } diff --git a/tests/unit/environments/MultiLabelTestEnvironment.h b/tests/unit/environments/MultiLabelTestEnvironment.h index dff40e9271d..12e50da1897 100644 --- a/tests/unit/environments/MultiLabelTestEnvironment.h +++ b/tests/unit/environments/MultiLabelTestEnvironment.h @@ -45,7 +45,6 @@ class MultiLabelTestEnvironment : public ::testing::Environment public: virtual void SetUp() { - sg_rand->set_seed(17); mMulticlassFixture = std::shared_ptr( new GaussianCheckerboard(100, 3, 3)); } diff --git a/tests/unit/evaluation/CrossValidation_multithread_unittest.cc b/tests/unit/evaluation/CrossValidation_multithread_unittest.cc index 4ec7bc025de..0c9d6020aa7 100644 --- a/tests/unit/evaluation/CrossValidation_multithread_unittest.cc +++ b/tests/unit/evaluation/CrossValidation_multithread_unittest.cc @@ -71,8 +71,6 @@ TEST(CrossValidation_multithread, LibSVM_unlocked) /*create simple linearly separable data*/ generate_data(mat, lab); - sg_rand->set_seed(1); - for (index_t i=0; i data(dim,n); for (index_t i=0; istd_normal_distrib(); + data.matrix[i] = m_rng->std_normal_distrib(); CDenseFeatures* orig_feats=new CDenseFeatures(data); CCSVFile* saved_features = new CCSVFile(fname, 'w'); @@ -60,6 +60,7 @@ TEST(StreamingDenseFeaturesTest, example_reading_from_file) SG_UNREF(orig_feats); SG_UNREF(feats); + SG_FREE(m_rng); std::remove(fname); } @@ -68,10 +69,10 @@ TEST(StreamingDenseFeaturesTest, example_reading_from_features) { index_t n=20; index_t dim=2; - + CRandom* m_rng = new CRandom(); SGMatrix data(dim,n); for (index_t i=0; istd_normal_distrib(); + data.matrix[i] = m_rng->std_normal_distrib(); CDenseFeatures* orig_feats=new CDenseFeatures(data); CStreamingDenseFeatures* feats = new CStreamingDenseFeatures(orig_feats); @@ -94,16 +95,18 @@ TEST(StreamingDenseFeaturesTest, example_reading_from_features) feats->end_parser(); SG_UNREF(feats); + SG_FREE(m_rng); } TEST(StreamingDenseFeaturesTest, reset_stream) { index_t n=20; index_t dim=2; - + CRandom* m_rng = new CRandom(); SGMatrix data(dim,n); for (index_t i=0; istd_normal_distrib(); + data.matrix[i] = m_rng->std_normal_distrib(); + SG_FREE(m_rng); CDenseFeatures* orig_feats=new CDenseFeatures(data); CStreamingDenseFeatures* feats=new CStreamingDenseFeatures(orig_feats); diff --git a/tests/unit/features/StreamingSparseFeatures_unittest.cc b/tests/unit/features/StreamingSparseFeatures_unittest.cc index 42b70d59bb0..34da51f628d 100644 --- a/tests/unit/features/StreamingSparseFeatures_unittest.cc +++ b/tests/unit/features/StreamingSparseFeatures_unittest.cc @@ -51,7 +51,7 @@ TEST(StreamingSparseFeaturesTest, parse_file) CLibSVMFile* fout = new CLibSVMFile(fname, 'w', NULL); fout->set_sparse_matrix(data, num_feat, num_vec, labels); SG_UNREF(fout); - SG_UNREF(rand); + SG_FREE(rand); CStreamingAsciiFile *file = new CStreamingAsciiFile(fname); CStreamingSparseFeatures *stream_features = diff --git a/tests/unit/io/CSVFile_unittest.cc b/tests/unit/io/CSVFile_unittest.cc index c823b3fa19b..43721520ef3 100644 --- a/tests/unit/io/CSVFile_unittest.cc +++ b/tests/unit/io/CSVFile_unittest.cc @@ -39,7 +39,7 @@ TEST(CSVFileTest, vector_int32) EXPECT_EQ(data_from_file[i], data[i]); } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); unlink("CSVFileTest_vector_int32_output.txt"); } @@ -71,7 +71,7 @@ TEST(CSVFileTest, vector_float64) EXPECT_NEAR(data_from_file[i], data[i], 1E-14); } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); unlink("CSVFileTest_vector_float64_output.txt"); } @@ -110,7 +110,7 @@ TEST(CSVFileTest, matrix_int32) } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); unlink("CSVFileTest_matrix_int32_output.txt"); } @@ -149,7 +149,7 @@ TEST(CSVFileTest, matrix_float64) } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); unlink("CSVFileTest_matrix_float64_output.txt"); } diff --git a/tests/unit/io/LibSVMFile_unittest.cc b/tests/unit/io/LibSVMFile_unittest.cc index 6c202f499a5..fddd21b24ce 100644 --- a/tests/unit/io/LibSVMFile_unittest.cc +++ b/tests/unit/io/LibSVMFile_unittest.cc @@ -85,7 +85,7 @@ TEST(LibSVMFileTest, sparse_matrix_int32) } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); SG_FREE(data); SG_FREE(labels); SG_FREE(data_from_file); @@ -171,7 +171,7 @@ TEST(LibSVMFileTest, sparse_matrix_float64) } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); SG_FREE(data); SG_FREE(labels); SG_FREE(data_from_file); diff --git a/tests/unit/io/ProtobufFile_unittest.cc b/tests/unit/io/ProtobufFile_unittest.cc index 915e5f6dc5b..6f720683191 100644 --- a/tests/unit/io/ProtobufFile_unittest.cc +++ b/tests/unit/io/ProtobufFile_unittest.cc @@ -42,7 +42,7 @@ TEST(ProtobufFileTest, vector_int32) EXPECT_EQ(data_from_file[i], data[i]); } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); unlink("ProtobufFileTest_vector_int32_output.txt"); } @@ -72,7 +72,7 @@ TEST(ProtobufFileTest, vector_float64) EXPECT_NEAR(data_from_file[i], data[i], 1E-14); } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); unlink("ProtobufFileTest_vector_float64_output.txt"); } @@ -109,7 +109,7 @@ TEST(ProtobufFileTest, matrix_int32) } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); unlink("ProtobufFileTest_matrix_int32_output.txt"); } @@ -146,7 +146,7 @@ TEST(ProtobufFileTest, matrix_float64) } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); unlink("ProtobufFileTest_matrix_float64_output.txt"); } @@ -200,7 +200,7 @@ TEST(ProtobufFileTest, sparse_matrix_int32) } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); SG_FREE(data); SG_FREE(data_from_file); @@ -257,7 +257,7 @@ TEST(ProtobufFileTest, sparse_matrix_float64) } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); SG_FREE(data); SG_FREE(data_from_file); @@ -300,7 +300,7 @@ TEST(ProtobufFileTest, DISABLED_string_list_char) } SG_UNREF(fin); - SG_UNREF(rand); + SG_FREE(rand); SG_FREE(strings); SG_FREE(data_from_file); diff --git a/tests/unit/lib/SGMatrix_unittest.cc b/tests/unit/lib/SGMatrix_unittest.cc index 72a986dd90a..c8a291cbc80 100644 --- a/tests/unit/lib/SGMatrix_unittest.cc +++ b/tests/unit/lib/SGMatrix_unittest.cc @@ -316,7 +316,6 @@ TEST(SGMatrixTest,is_symmetric_float32_true) { const index_t size=2; SGMatrix mat(size, size); - CMath::init_random(100); for (index_t i=0; i(size, size); CMath::init_random(100); + for (uint64_t i=0; i get_sinusoid_samples(int32_t num_samples, SGVectorset_seed(10); - + CMath::init_random(10); int32_t num_train_samples=100; SGVector lab(num_train_samples); SGMatrix data=get_sinusoid_samples(num_train_samples,lab); diff --git a/tests/unit/machine/kerneldensity_unittest.cc b/tests/unit/machine/kerneldensity_unittest.cc index 2ff9e07a7c2..909fd1d8c12 100644 --- a/tests/unit/machine/kerneldensity_unittest.cc +++ b/tests/unit/machine/kerneldensity_unittest.cc @@ -169,14 +169,14 @@ TEST(KernelDensity,dual_tree) TEST(KernelDensity,dual_tree_single_tree_equivalence) { - sg_rand->set_seed(1); + CRandom* m_rng = new CRandom(1); SGMatrix data(5,100); - sg_rand->fill_array_oo(data.matrix,500); + m_rng->fill_array_oo(data.matrix, 500); CDenseFeatures* feats=new CDenseFeatures(data); SGMatrix test(5,20); - sg_rand->fill_array_oo(test.matrix,100); + m_rng->fill_array_oo(test.matrix, 100); CDenseFeatures* testfeats=new CDenseFeatures(test); @@ -195,4 +195,5 @@ TEST(KernelDensity,dual_tree_single_tree_equivalence) SG_UNREF(testfeats); SG_UNREF(feats); SG_UNREF(k); + SG_FREE(m_rng); } \ No newline at end of file diff --git a/tests/unit/mathematics/Math_unittest.cc b/tests/unit/mathematics/Math_unittest.cc index f8684cc579b..2c226008899 100644 --- a/tests/unit/mathematics/Math_unittest.cc +++ b/tests/unit/mathematics/Math_unittest.cc @@ -388,9 +388,9 @@ TEST(CMath, permute) { SGVector v(4); v.range_fill(0); - CMath::init_random(2); - CMath::permute(v); - + CRandom* random = new CRandom(2); + CMath::permute(v, random); + SG_FREE(random); EXPECT_EQ(v[0], 2); EXPECT_EQ(v[1], 1); EXPECT_EQ(v[2], 3); @@ -403,7 +403,7 @@ TEST(CMath, permute_with_random) v.range_fill(0); CRandom* random = new CRandom(2); CMath::permute(v, random); - SG_UNREF(random); + SG_FREE(random); EXPECT_EQ(v[0], 2); EXPECT_EQ(v[1], 1); diff --git a/tests/unit/mathematics/Random_unittest.cc b/tests/unit/mathematics/Random_unittest.cc index bc85f666b19..b55e3a53c8a 100644 --- a/tests/unit/mathematics/Random_unittest.cc +++ b/tests/unit/mathematics/Random_unittest.cc @@ -21,7 +21,7 @@ TEST(Random, uint32_t) { CRandom* prng = new CRandom(12345); uint32_t r = prng->random_32(); - SG_UNREF(prng); + SG_FREE(prng); EXPECT_EQ(1811630862U, r); } @@ -29,7 +29,7 @@ TEST(Random, uint64_t) { CRandom* prng = new CRandom(12345); uint64_t r = prng->random_64(); - SG_UNREF(prng); + SG_FREE(prng); EXPECT_EQ(18328733385137801998U, r); } @@ -39,7 +39,7 @@ TEST(Random, fill_array_uint32) uint32_t t = 2228230814U; SGVector rv(2*SFMT_N32+1); prng->fill_array(rv.vector, rv.vlen); - SG_UNREF(prng); + SG_FREE(prng); EXPECT_EQ(t, rv[SFMT_N32]); } @@ -51,7 +51,7 @@ TEST(Random, fill_array_uint32_simd) uint32_t t = 2228230814U; SGVector rv(2*SFMT_N32); prng->fill_array(rv.vector, rv.vlen); - SG_UNREF(prng); + SG_FREE(prng); EXPECT_EQ(t, rv[SFMT_N32]); } @@ -63,7 +63,7 @@ TEST(Random, fill_array_uint64) uint64_t t = 9564086722318310046U; SGVector rv(2*SFMT_N64+1); prng->fill_array(rv.vector, rv.vlen); - SG_UNREF(prng); + SG_FREE(prng); EXPECT_EQ(t, rv[SFMT_N64]); } @@ -75,7 +75,7 @@ TEST(Random, fill_array_uint64_simd) uint64_t t = 9564086722318310046U; SGVector rv(2*SFMT_N64); prng->fill_array(rv.vector, rv.vlen); - SG_UNREF(prng); + SG_FREE(prng); EXPECT_EQ(t, rv[SFMT_N64]); } @@ -87,7 +87,7 @@ TEST(Random, fill_array_oc) float64_t t = 0.25551924513287405; SGVector rv(2*dsfmt_get_min_array_size()+1); prng->fill_array_oc(rv.vector, rv.vlen); - SG_UNREF(prng); + SG_FREE(prng); EXPECT_DOUBLE_EQ(t, rv[dsfmt_get_min_array_size()]); } @@ -99,7 +99,7 @@ TEST(Random, fill_array_oc_simd) float64_t t = 0.25551924513287405; SGVector rv(2*dsfmt_get_min_array_size()); prng->fill_array_oc(rv.vector, rv.vlen); - SG_UNREF(prng); + SG_FREE(prng); EXPECT_DOUBLE_EQ(t, rv[dsfmt_get_min_array_size()]); } @@ -110,7 +110,7 @@ TEST(Random, normal_distrib) CRandom* prng = new CRandom(12345); float64_t t = 75.567130769021162; float64_t r = prng->normal_distrib(100.0, 10.0); - SG_UNREF(prng); + SG_FREE(prng); EXPECT_DOUBLE_EQ(t, r); } @@ -127,88 +127,93 @@ TEST(Random, random_uint64_1_2) TEST(Random, random_uint64_0_10) { - CMath::init_random(17); + CRandom* prng = new CRandom(17); int rnds[10] = {0,0,0,0,0,0}; for (int32_t i=0; i<10000; i++) { - uint64_t r=CMath::random((uint64_t) 0, (uint64_t) 9); + uint64_t r = prng->random((uint64_t)0, (uint64_t)9); rnds[r]++; } for (int32_t i=0; i<10; i++) { EXPECT_TRUE(rnds[i]>0); } + SG_FREE(prng); } TEST(Random, random_int64_1_2) { - CMath::init_random(17); + CRandom* prng = new CRandom(17); for (int32_t i=0; i<10000; i++) { - int64_t r=CMath::random((int64_t) 1, (int64_t) 2); + int64_t r = prng->random((int64_t)1, (int64_t)2); EXPECT_TRUE(r == 1 || r == 2); } } TEST(Random, random_int64_0_10) { - CMath::init_random(17); + CRandom* prng = new CRandom(17); int rnds[10] = {0,0,0,0,0,0}; for (int32_t i=0; i<10000; i++) { - int64_t r=CMath::random((int64_t) 0, (int64_t) 9); + int64_t r = prng->random((int64_t)0, (int64_t)9); rnds[r]++; } for (int32_t i=0; i<10; i++) { EXPECT_TRUE(rnds[i]>0); } + SG_FREE(prng); } TEST(Random, random_uint32_1_2) { - CMath::init_random(17); + CRandom* prng = new CRandom(17); for (int32_t i=0; i<10000; i++) { - uint32_t r=CMath::random((uint32_t) 1, (uint32_t) 2); + uint32_t r = prng->random((uint32_t)1, (uint32_t)2); EXPECT_TRUE(r == 1 || r == 2); } + SG_FREE(prng); } TEST(Random, random_uint32_0_10) { - CMath::init_random(17); + CRandom* prng = new CRandom(17); int rnds[10] = {0,0,0,0,0,0}; for (int32_t i=0; i<10000; i++) { - uint32_t r=CMath::random((uint32_t) 0, (uint32_t) 9); + uint32_t r = prng->random((uint32_t)0, (uint32_t)9); rnds[r]++; } for (int32_t i=0; i<10; i++) { EXPECT_TRUE(rnds[i]>0); } + SG_FREE(prng); } TEST(Random, random_int32_1_2) { - CMath::init_random(17); + CRandom* prng = new CRandom(17); for (int32_t i=0; i<10000; i++) { - int32_t r=CMath::random((int32_t) 1, (int32_t) 2); + int32_t r = prng->random((int32_t)1, (int32_t)2); EXPECT_TRUE(r == 1 || r == 2); } + SG_FREE(prng); } TEST(Random, random_int64_range) { - CMath::init_random(17); + CRandom* prng = new CRandom(17); int rnds[array_len]; for (uint32_t i=0; irandom((int64_t)0, (int64_t)array_len - 1); rnds[r]++; } @@ -216,17 +221,18 @@ TEST(Random, random_int64_range) double pbin=double(rnds[i])/n_runs*100*array_len; EXPECT_GE(pbin, 99.0); } + SG_FREE(prng); } TEST(Random, random_uint64_range) { - CMath::init_random(17); + CRandom* prng = new CRandom(17); int rnds[array_len]; for (uint32_t i=0; irandom((uint64_t)0, (uint64_t)array_len - 1); rnds[r]++; } @@ -234,17 +240,18 @@ TEST(Random, random_uint64_range) double pbin=double(rnds[i])/n_runs*100*array_len; EXPECT_GE(pbin, 99.0); } + SG_FREE(prng); } TEST(Random, random_int32_range) { - CMath::init_random(17); + CRandom* prng = new CRandom(17); int rnds[array_len]; for (uint32_t i=0; irandom((int32_t)0, (int32_t)array_len - 1); rnds[r]++; } @@ -252,17 +259,18 @@ TEST(Random, random_int32_range) double pbin=double(rnds[i])/n_runs*100*array_len; EXPECT_GE(pbin, 99.0); } + SG_FREE(prng); } TEST(Random, random_uint32_range) { - CMath::init_random(17); + CRandom* prng = new CRandom(17); int rnds[array_len]; for (uint32_t i=0; irandom((uint32_t)0, (uint32_t)array_len - 1); rnds[r]++; } @@ -270,6 +278,7 @@ TEST(Random, random_uint32_range) double pbin=double(rnds[i])/n_runs*100*array_len; EXPECT_GE(pbin, 99.0); } + SG_FREE(prng); } TEST(Random, random_uint32_random_range) @@ -289,12 +298,11 @@ TEST(Random, random_uint32_random_range) double pbin=double(rnds[i])/n_runs*100*array_len; EXPECT_GE(pbin, 99.0); } - SG_UNREF(prng); + SG_FREE(prng); } TEST(Random, random_float64_range) { - CMath::init_random(17); int rnds[array_len]; for (uint32_t i=0; irandom((float64_t)0, (float64_t)1.0); min=CMath::min(min, r); max=CMath::max(max, r); } EXPECT_GE(max, 0.99999); EXPECT_LE(min, 0.00001); + SG_FREE(prng); } TEST(Random, random_std_normal_quantiles) { - CRandom* rand=new CRandom(); + CRandom* prng = new CRandom(); int64_t m=10000000; SGVector counts(10); @@ -335,12 +344,13 @@ TEST(Random, random_std_normal_quantiles) for (int64_t i=0; istd_normal_distrib(), 1); + float64_t quantile = + CStatistics::normal_cdf(prng->std_normal_distrib(), 1); index_t idx=(int32_t)(quantile*counts.vlen); counts[idx]++; } - SG_UNREF(rand); + SG_FREE(prng); for (index_t i=0; i a(10); a.random(-1024.0, 1024.0); floatmax_t sum_a=0; diff --git a/tests/unit/mathematics/ajd/JADiagOrth_unittest.cc b/tests/unit/mathematics/ajd/JADiagOrth_unittest.cc index ea21f9a38f3..c02c234d839 100644 --- a/tests/unit/mathematics/ajd/JADiagOrth_unittest.cc +++ b/tests/unit/mathematics/ajd/JADiagOrth_unittest.cc @@ -27,8 +27,6 @@ TEST(CJADiagOrth, diagonalize) C_dims[2] = 30; SGNDArray< float64_t > C(C_dims, 3); - CMath::init_random(17); - for (int i = 0; i < C_dims[2]; i++) { Eigen::Map tmp(C.get_matrix(i),C_dims[0], C_dims[1]); diff --git a/tests/unit/mathematics/linalg/ConjugateOrthogonalCGSolver_unittest.cc b/tests/unit/mathematics/linalg/ConjugateOrthogonalCGSolver_unittest.cc index b12f88df43e..044f2e50fe8 100644 --- a/tests/unit/mathematics/linalg/ConjugateOrthogonalCGSolver_unittest.cc +++ b/tests/unit/mathematics/linalg/ConjugateOrthogonalCGSolver_unittest.cc @@ -28,11 +28,11 @@ TEST(ConjugateOrthogonalCGSolver, solve) // diagonal non-Hermintian matrix with random complex entries SGVector diag(size); - sg_rand->set_seed(100.0); + auto m_rng = std::unique_ptr(new CRandom(100)); for (index_t i=0; istd_normal_distrib(); - float64_t imag=sg_rand->std_normal_distrib(); + float64_t real = m_rng->std_normal_distrib(); + float64_t imag = m_rng->std_normal_distrib(); diag[i]=complex128_t(real, imag); } A->set_diagonal(diag); @@ -40,7 +40,7 @@ TEST(ConjugateOrthogonalCGSolver, solve) // vector b of the system SGVector b(size); for (index_t i=0; istd_normal_distrib(); + b[i] = m_rng->std_normal_distrib(); // Solve with COCG CConjugateOrthogonalCGSolver* cocg_linear_solver diff --git a/tests/unit/mathematics/linalg/DirectSparseLinearSolver_unittest.cc b/tests/unit/mathematics/linalg/DirectSparseLinearSolver_unittest.cc index adfe740eebc..f47095ec146 100644 --- a/tests/unit/mathematics/linalg/DirectSparseLinearSolver_unittest.cc +++ b/tests/unit/mathematics/linalg/DirectSparseLinearSolver_unittest.cc @@ -28,9 +28,11 @@ TEST(DirectSparseLinearSolver, solve) CSparseMatrixOperator* A=new CSparseMatrixOperator(sm); SGVector diag(size); float64_t difficulty=5; - + auto m_rng = std::unique_ptr(new CRandom()); for (index_t i=0; istd_normal_distrib()), difficulty)+0.0001; + diag[i] = + CMath::pow(CMath::abs(m_rng->std_normal_distrib()), difficulty) + + 0.0001; A->set_diagonal(diag); CDirectSparseLinearSolver* linear_solver=new CDirectSparseLinearSolver(); diff --git a/tests/unit/mathematics/linalg/LanczosEigenSolver_unittest.cc b/tests/unit/mathematics/linalg/LanczosEigenSolver_unittest.cc index 4efaaf46672..8af7fecbea4 100644 --- a/tests/unit/mathematics/linalg/LanczosEigenSolver_unittest.cc +++ b/tests/unit/mathematics/linalg/LanczosEigenSolver_unittest.cc @@ -80,13 +80,15 @@ TEST(LanczosEigenSolver, compute_big_diag_matrix) SGSparseMatrix sm(size, size); CSparseMatrixOperator* op=new CSparseMatrixOperator(sm); SG_REF(op); + auto m_rng = std::unique_ptr(new CRandom()); // set its diagonal SGVector diag(size); for (index_t i=0; istd_normal_distrib()), difficulty) - +min_eigenvalue; + diag[i] = + CMath::pow(CMath::abs(m_rng->std_normal_distrib()), difficulty) + + min_eigenvalue; } op->set_diagonal(diag); diff --git a/tests/unit/mathematics/linalg/LogDetEstimator_unittest.cc b/tests/unit/mathematics/linalg/LogDetEstimator_unittest.cc index 6de74a8e120..d3107677886 100644 --- a/tests/unit/mathematics/linalg/LogDetEstimator_unittest.cc +++ b/tests/unit/mathematics/linalg/LogDetEstimator_unittest.cc @@ -120,7 +120,7 @@ TEST(LogDetEstimator, sample_ratapp_dense) mat(1,0)=0.5; mat(1,1)=1000.0; - sg_rand->set_seed(1); + CMath::init_random(1); float64_t accuracy=1E-5; CDenseMatrixOperator* op=new CDenseMatrixOperator(mat); @@ -169,10 +169,11 @@ TEST(LogDetEstimator, sample_ratapp_probing_sampler) const index_t size=16; SGMatrix mat(size, size); + auto m_rng = std::unique_ptr(new CRandom(1)); mat.set_const(0.0); for (index_t i=0; istd_normal_distrib())*1000; + float64_t value = CMath::abs(m_rng->std_normal_distrib()) * 1000; mat(i,i)=value<1.0?10.0:value; } @@ -256,10 +257,11 @@ TEST(LogDetEstimator, sample_ratapp_probing_sampler_cgm) const index_t size=16; SGMatrix mat(size, size); + auto m_rng = std::unique_ptr(new CRandom(1)); mat.set_const(0.0); for (index_t i=0; istd_normal_distrib())*1000; + float64_t value = CMath::abs(m_rng->std_normal_distrib()) * 1000; mat(i,i)=value<1.0?10.0:value; } @@ -347,12 +349,14 @@ TEST(LogDetEstimator, sample_ratapp_big_diag_matrix) CSparseMatrixOperator* op=new CSparseMatrixOperator(sm); SG_REF(op); + auto m_rng = std::unique_ptr(new CRandom(1)); // set its diagonal SGVector diag(size); for (index_t i=0; istd_normal_distrib()), difficulty) - +min_eigenvalue; + diag[i] = + CMath::pow(CMath::abs(m_rng->std_normal_distrib()), difficulty) + + min_eigenvalue; } op->set_diagonal(diag); @@ -406,10 +410,12 @@ TEST(LogDetEstimator, sample_ratapp_big_matrix) // set its diagonal SGVector diag(size); + auto m_rng = std::unique_ptr(new CRandom(1)); for (index_t i=0; istd_normal_distrib()), difficulty) - +min_eigenvalue; + sm(i, i) = + CMath::pow(CMath::abs(m_rng->std_normal_distrib()), difficulty) + + min_eigenvalue; } // set its subdiagonal float64_t entry=min_eigenvalue/2; diff --git a/tests/unit/mathematics/linalg/ProbingSampler_unittest.cc b/tests/unit/mathematics/linalg/ProbingSampler_unittest.cc index 63b755af982..35712ce2576 100644 --- a/tests/unit/mathematics/linalg/ProbingSampler_unittest.cc +++ b/tests/unit/mathematics/linalg/ProbingSampler_unittest.cc @@ -90,13 +90,14 @@ TEST(ProbingSampler, probing_samples_big_diag_matrix) SGSparseMatrix sm(size, size); CSparseMatrixOperator* op=new CSparseMatrixOperator(sm); SG_REF(op); - + auto m_rng = std::unique_ptr(new CRandom()); // set its diagonal SGVector diag(size); for (index_t i=0; istd_normal_distrib()), difficulty) - +min_eigenvalue; + diag[i] = + CMath::pow(CMath::abs(m_rng->std_normal_distrib()), difficulty) + + min_eigenvalue; } op->set_diagonal(diag); diff --git a/tests/unit/multiclass/BaggingMachine_unittest.cc b/tests/unit/multiclass/BaggingMachine_unittest.cc index 8fe4a846942..29e5a6999ed 100644 --- a/tests/unit/multiclass/BaggingMachine_unittest.cc +++ b/tests/unit/multiclass/BaggingMachine_unittest.cc @@ -83,7 +83,7 @@ TEST(BaggingMachine, mock_train) TEST(BaggingMachine,classify_CART) { - sg_rand->set_seed(1); + CMath::init_random(1); SGMatrix data(4,14); //vector = [Outlook Temperature Humidity Wind] diff --git a/tests/unit/multiclass/MulticlassOCAS_unittest.cc b/tests/unit/multiclass/MulticlassOCAS_unittest.cc index 6fa2a975e0c..b6bfee84f12 100644 --- a/tests/unit/multiclass/MulticlassOCAS_unittest.cc +++ b/tests/unit/multiclass/MulticlassOCAS_unittest.cc @@ -15,27 +15,27 @@ extern MultiLabelTestEnvironment* multilabel_test_env; #ifdef HAVE_LAPACK TEST(MulticlassOCASTest,train) { - CMath::init_random(5); - float64_t C = 1.0; - std::shared_ptr mockData = - multilabel_test_env->getMulticlassFixture(); - - CDenseFeatures* train_feats = mockData->get_features_train(); - CDenseFeatures* test_feats = mockData->get_features_test(); - CMulticlassLabels* ground_truth = - (CMulticlassLabels*)mockData->get_labels_test(); - CMulticlassOCAS* mocas = new CMulticlassOCAS(C, train_feats, ground_truth); - mocas->parallel->set_num_threads(1); - mocas->set_epsilon(1e-5); - mocas->train(); - - CMulticlassLabels* pred = (CMulticlassLabels*)mocas->apply(test_feats); - CMulticlassAccuracy evaluate = CMulticlassAccuracy(); - float64_t result = evaluate.evaluate(pred, ground_truth); - EXPECT_GT(result, 0.99); - - SG_UNREF(mocas); - SG_UNREF(pred); + CMath::init_random(17); + float64_t C = 1.0; + std::shared_ptr mockData = + multilabel_test_env->getMulticlassFixture(); + + CDenseFeatures* train_feats = mockData->get_features_train(); + CDenseFeatures* test_feats = mockData->get_features_test(); + CMulticlassLabels* ground_truth = + (CMulticlassLabels*)mockData->get_labels_test(); + CMulticlassOCAS* mocas = new CMulticlassOCAS(C, train_feats, ground_truth); + mocas->parallel->set_num_threads(1); + mocas->set_epsilon(1e-5); + mocas->train(); + + CMulticlassLabels* pred = (CMulticlassLabels*)mocas->apply(test_feats); + CMulticlassAccuracy evaluate = CMulticlassAccuracy(); + float64_t result = evaluate.evaluate(pred, ground_truth); + EXPECT_GT(result, 0.99); + + SG_UNREF(mocas); + SG_UNREF(pred); } #endif // HAVE_LAPACK #endif //USE_GPL_SHOGUN diff --git a/tests/unit/multiclass/tree/CARTree_unittest.cc b/tests/unit/multiclass/tree/CARTree_unittest.cc index fd0293ffa39..5e1c0af9b56 100644 --- a/tests/unit/multiclass/tree/CARTree_unittest.cc +++ b/tests/unit/multiclass/tree/CARTree_unittest.cc @@ -546,7 +546,7 @@ TEST(CARTree, form_t1_test) TEST(CARTree,cv_prune_simple) { - sg_rand->set_seed(10); + CMath::init_random(1); SGMatrix data(2,20); data(0,0)=2; data(1,0)=2; diff --git a/tests/unit/multiclass/tree/RandomCARTree_unittest.cc b/tests/unit/multiclass/tree/RandomCARTree_unittest.cc index 86c97d3e9e2..dff490ad801 100644 --- a/tests/unit/multiclass/tree/RandomCARTree_unittest.cc +++ b/tests/unit/multiclass/tree/RandomCARTree_unittest.cc @@ -51,7 +51,7 @@ using namespace shogun; TEST(RandomCARTree, classify_nominal) { - sg_rand->set_seed(2); + CMath::init_random(2); SGMatrix data(4,14); //vector = [Outlook Temperature Humidity Wind] diff --git a/tests/unit/multiclass/tree/RandomForest_unittest.cc b/tests/unit/multiclass/tree/RandomForest_unittest.cc index 075735136e8..91d417b9f30 100644 --- a/tests/unit/multiclass/tree/RandomForest_unittest.cc +++ b/tests/unit/multiclass/tree/RandomForest_unittest.cc @@ -142,8 +142,7 @@ void generate_nm_data(SGMatrix& data, SGVector& lab) TEST(RandomForest,classify_nominal_test) { - sg_rand->set_seed(1); - + CMath::init_random(1); SGMatrix data(4,14); SGVector lab(14); @@ -212,8 +211,7 @@ TEST(RandomForest,classify_nominal_test) TEST(RandomForest,classify_non_nominal_test) { - sg_rand->set_seed(1); - + CMath::init_random(1); SGMatrix data(4,14); SGVector lab(14); diff --git a/tests/unit/preprocessor/RescaleFeatures_unittest.cc b/tests/unit/preprocessor/RescaleFeatures_unittest.cc index ac95f57747b..3289df56b0d 100644 --- a/tests/unit/preprocessor/RescaleFeatures_unittest.cc +++ b/tests/unit/preprocessor/RescaleFeatures_unittest.cc @@ -18,7 +18,7 @@ TEST(RescaleFeatures, apply_to_feature_matrix) index_t num_vectors = 10; SGVector min(num_features), range(num_features); SGVector v(num_features*num_vectors), ev; - sg_rand->set_seed(12345); + CMath::init_random(12345); v.random(-1024, 1024); ev = v.clone(); diff --git a/tests/unit/statistical_testing/KernelSelection_unittest.cc b/tests/unit/statistical_testing/KernelSelection_unittest.cc index 21a97f07994..e217b0d9e35 100644 --- a/tests/unit/statistical_testing/KernelSelection_unittest.cc +++ b/tests/unit/statistical_testing/KernelSelection_unittest.cc @@ -50,7 +50,7 @@ TEST(KernelSelectionMaxMMD, linear_time_single_kernel_streaming) const float64_t difference=0.5; const index_t num_kernels=10; - sg_rand->set_seed(12345); + CMath::init_random(12345); auto gen_p=new CMeanShiftDataGenerator(0, dim, 0); auto gen_q=new CMeanShiftDataGenerator(difference, dim, 0); @@ -83,7 +83,7 @@ TEST(KernelSelectionMaxMMD, quadratic_time_single_kernel_dense) const float64_t difference=0.5; const index_t num_kernels=10; - sg_rand->set_seed(12345); + CMath::init_random(12345); auto gen_p=some(0, dim, 0); auto gen_q=some(difference, dim, 0); @@ -117,7 +117,7 @@ TEST(KernelSelectionMaxMMD, linear_time_weighted_kernel_streaming) const float64_t difference=0.5; const index_t num_kernels=10; - sg_rand->set_seed(12345); + CMath::init_random(12345); auto gen_p=new CMeanShiftDataGenerator(0, dim, 0); auto gen_q=new CMeanShiftDataGenerator(difference, dim, 0); @@ -156,7 +156,7 @@ TEST(KernelSelectionMaxTestPower, linear_time_single_kernel_streaming) const float64_t difference=0.5; const index_t num_kernels=10; - sg_rand->set_seed(12345); + CMath::init_random(12345); auto gen_p=new CMeanShiftDataGenerator(0, dim, 0); auto gen_q=new CMeanShiftDataGenerator(difference, dim, 0); @@ -189,7 +189,7 @@ TEST(KernelSelectionMaxTestPower, quadratic_time_single_kernel) const float64_t difference=0.5; const index_t num_kernels=10; - sg_rand->set_seed(12345); + CMath::init_random(12345); auto gen_p=new CMeanShiftDataGenerator(0, dim, 0); auto gen_q=new CMeanShiftDataGenerator(difference, dim, 0); @@ -222,7 +222,7 @@ TEST(KernelSelectionMaxTestPower, linear_time_weighted_kernel_streaming) const float64_t difference=0.5; const index_t num_kernels=10; - sg_rand->set_seed(12345); + CMath::init_random(12345); auto gen_p=new CMeanShiftDataGenerator(0, dim, 0); auto gen_q=new CMeanShiftDataGenerator(difference, dim, 0); @@ -265,8 +265,6 @@ TEST(KernelSelectionMaxCrossValidation, quadratic_time_single_kernel_dense) const float64_t train_test_ratio=3; const float64_t alpha=0.05; - sg_rand->set_seed(12345); - auto gen_p=some(0, dim, 0); auto gen_q=some(difference, dim, 0); auto feats_p=gen_p->get_streamed_features(m); @@ -304,7 +302,7 @@ TEST(KernelSelectionMaxCrossValidation, linear_time_single_kernel_dense) const float64_t train_test_ratio=3; const float64_t alpha=0.05; - sg_rand->set_seed(12345); + CMath::init_random(12345); auto gen_p=some(0, dim, 0); auto gen_q=some(difference, dim, 0); @@ -337,7 +335,7 @@ TEST(KernelSelectionMedianHeuristic, quadratic_time_single_kernel_dense) const float64_t difference=0.5; const index_t num_kernels=10; - sg_rand->set_seed(12345); + CMath::init_random(12345); auto gen_p=new CMeanShiftDataGenerator(0, dim, 0); auto gen_q=new CMeanShiftDataGenerator(difference, dim, 0); @@ -369,7 +367,7 @@ TEST(KernelSelectionMedianHeuristic, linear_time_single_kernel_dense) const float64_t difference=0.5; const index_t num_kernels=10; - sg_rand->set_seed(12345); + CMath::init_random(12345); auto gen_p=new CMeanShiftDataGenerator(0, dim, 0); auto gen_q=new CMeanShiftDataGenerator(difference, dim, 0); diff --git a/tests/unit/statistical_testing/LinearTimeMMD_unittest.cc b/tests/unit/statistical_testing/LinearTimeMMD_unittest.cc index 50bd9e44d45..86e3adf9876 100644 --- a/tests/unit/statistical_testing/LinearTimeMMD_unittest.cc +++ b/tests/unit/statistical_testing/LinearTimeMMD_unittest.cc @@ -318,8 +318,7 @@ TEST(LinearTimeMMD, perform_test_gaussian_biased_full) const index_t dim=3; // use fixed seed - sg_rand->set_seed(12345); - + CMath::init_random(12345); float64_t difference=0.5; // streaming data generator for mean shift distributions @@ -357,11 +356,8 @@ TEST(LinearTimeMMD, perform_test_gaussian_unbiased_full) const index_t n=30; const index_t dim=3; - // use fixed seed - sg_rand->set_seed(12345); - float64_t difference=0.5; - + CMath::init_random(12345); // streaming data generator for mean shift distributions auto gen_p=new CMeanShiftDataGenerator(0, dim, 0); auto gen_q=new CMeanShiftDataGenerator(difference, dim, 0); @@ -397,9 +393,7 @@ TEST(LinearTimeMMD, perform_test_gaussian_unbiased_incomplete) const index_t n=20; const index_t dim=3; - // use fixed seed - sg_rand->set_seed(12345); - + CMath::init_random(12345); float64_t difference=0.5; // streaming data generator for mean shift distributions diff --git a/tests/unit/statistical_testing/QuadraticTimeMMD_unittest.cc b/tests/unit/statistical_testing/QuadraticTimeMMD_unittest.cc index 58e4e1c1aa0..50fd9ffd82f 100644 --- a/tests/unit/statistical_testing/QuadraticTimeMMD_unittest.cc +++ b/tests/unit/statistical_testing/QuadraticTimeMMD_unittest.cc @@ -322,9 +322,7 @@ TEST(QuadraticTimeMMD, perform_test_permutation_biased_full) const index_t n=30; const index_t dim=3; - // use fixed seed - sg_rand->set_seed(12345); - + CMath::init_random(12345); float64_t difference=0.5; // streaming data generator for mean shift distributions @@ -361,9 +359,7 @@ TEST(QuadraticTimeMMD, perform_test_permutation_unbiased_full) const index_t n=30; const index_t dim=3; - // use fixed seed - sg_rand->set_seed(12345); - + CMath::init_random(12345); float64_t difference=0.5; // streaming data generator for mean shift distributions @@ -400,9 +396,7 @@ TEST(QuadraticTimeMMD, perform_test_permutation_unbiased_incomplete) const index_t n=20; const index_t dim=3; - // use fixed seed - sg_rand->set_seed(12345); - + CMath::init_random(12345); float64_t difference=0.5; // streaming data generator for mean shift distributions @@ -439,9 +433,7 @@ TEST(QuadraticTimeMMD, perform_test_spectrum) const index_t n=30; const index_t dim=3; - // use fixed seed - sg_rand->set_seed(12345); - + CMath::init_random(12345); float64_t difference=0.5; // streaming data generator for mean shift distributions @@ -509,11 +501,11 @@ TEST(QuadraticTimeMMD, precomputed_vs_nonprecomputed) mmd->set_num_null_samples(num_null_samples); mmd->set_null_approximation_method(NAM_PERMUTATION); - sg_rand->set_seed(12345); + CMath::init_random(12345); SGVector result_1=mmd->sample_null(); mmd->precompute_kernel_matrix(false); - sg_rand->set_seed(12345); + CMath::init_random(12345); SGVector result_2=mmd->sample_null(); ASSERT_EQ(result_1.size(), result_2.size()); @@ -528,8 +520,8 @@ TEST(QuadraticTimeMMD, multikernel_compute_statistic) const index_t dim=1; const index_t num_kernels=10; + CMath::init_random(12345); float64_t difference=0.5; - sg_rand->set_seed(12345); auto gen_p=some(0, dim, 0); auto gen_q=some(difference, dim, 0); @@ -566,8 +558,8 @@ TEST(QuadraticTimeMMD, multikernel_compute_variance_h1) const index_t dim=1; const index_t num_kernels=10; + CMath::init_random(12345); float64_t difference=0.5; - sg_rand->set_seed(12345); auto gen_p=some(0, dim, 0); auto gen_q=some(difference, dim, 0); @@ -604,8 +596,8 @@ TEST(QuadraticTimeMMD, multikernel_compute_test_power) const index_t dim=1; const index_t num_kernels=10; + CMath::init_random(12345); float64_t difference=0.5; - sg_rand->set_seed(12345); auto gen_p=some(0, dim, 0); auto gen_q=some(difference, dim, 0); @@ -646,6 +638,7 @@ TEST(QuadraticTimeMMD, multikernel_perform_test) const index_t num_null_samples=200; const index_t cache_size=10; + CMath::init_random(12345); float64_t difference=0.5; auto gen_p=some(0, dim, 0); @@ -661,7 +654,7 @@ TEST(QuadraticTimeMMD, multikernel_perform_test) float64_t tau=pow(2, sigma); mmd->multikernel()->add_kernel(new CGaussianKernel(cache_size, tau)); } - sg_rand->set_seed(12345); + CMath::init_random(12345); SGVector rejections_multiple=mmd->multikernel()->perform_test(alpha); mmd->multikernel()->cleanup(); @@ -670,7 +663,7 @@ TEST(QuadraticTimeMMD, multikernel_perform_test) { float64_t tau=pow(2, sigma); mmd->set_kernel(new CGaussianKernel(cache_size, tau)); - sg_rand->set_seed(12345); + CMath::init_random(12345); rejections_single[i]=mmd->perform_test(alpha); } diff --git a/tests/unit/statistical_testing/TwoDistributionTest_unittest.cc b/tests/unit/statistical_testing/TwoDistributionTest_unittest.cc index 0db451d8147..dc7da4c7328 100644 --- a/tests/unit/statistical_testing/TwoDistributionTest_unittest.cc +++ b/tests/unit/statistical_testing/TwoDistributionTest_unittest.cc @@ -140,12 +140,12 @@ TEST(TwoDistributionTest, compute_distance_streaming) mock_obj->set_num_samples_p(m); mock_obj->set_num_samples_q(n); - sg_rand->set_seed(12345); + CMath::init_random(12345); auto euclidean_distance=some(); auto distance=mock_obj->compute_distance(euclidean_distance); auto distance_mat1=distance->get_distance_matrix(); - sg_rand->set_seed(12345); + CMath::init_random(12345); auto feats_p=static_cast*>(gen_p->get_streamed_features(m)); auto feats_q=static_cast*>(gen_q->get_streamed_features(n)); euclidean_distance->init(feats_p, feats_q); @@ -175,12 +175,12 @@ TEST(TwoDistributionTest, compute_joint_distance_streaming) mock_obj->set_num_samples_p(m); mock_obj->set_num_samples_q(n); - sg_rand->set_seed(12345); + CMath::init_random(12345); auto euclidean_distance=some(); auto distance=mock_obj->compute_joint_distance(euclidean_distance); auto distance_mat1=distance->get_distance_matrix(); - sg_rand->set_seed(12345); + CMath::init_random(12345); auto feats_p=static_cast*>(gen_p->get_streamed_features(m)); auto feats_q=static_cast*>(gen_q->get_streamed_features(n)); diff --git a/tests/unit/statistical_testing/internals/CrossValidationMMD_unittest.cc b/tests/unit/statistical_testing/internals/CrossValidationMMD_unittest.cc index f8568adb795..2147fb1d937 100644 --- a/tests/unit/statistical_testing/internals/CrossValidationMMD_unittest.cc +++ b/tests/unit/statistical_testing/internals/CrossValidationMMD_unittest.cc @@ -90,7 +90,12 @@ TEST(CrossValidationMMD, biased_full) cv.m_alpha=alpha; cv.m_num_runs=num_runs; cv.m_rejections=SGMatrix(num_runs*num_folds, num_kernels); - sg_rand->set_seed(12345); + + // set seed like this is about to make CrossValidationSplitting will have a + // same seed during this test. Not sure if it's a good thing to do. + cv.m_kfold_x->set_seed(12345); + cv.m_kfold_y->set_seed(12345); + CMath::init_random(12345); cv(kernel_mgr); kernel_mgr.unset_precomputed_distance(); @@ -100,11 +105,15 @@ TEST(CrossValidationMMD, biased_full) auto kfold_p=some(new CBinaryLabels(dummy_labels_p), num_folds); auto kfold_q=some(new CBinaryLabels(dummy_labels_q), num_folds); + // set the seed for CrossValidationSplitting + kfold_p->set_seed(12345); + kfold_q->set_seed(12345); + auto permutation_mmd=PermutationMMD(); permutation_mmd.m_stype=stype; permutation_mmd.m_num_null_samples=num_null_samples; - sg_rand->set_seed(12345); + CMath::init_random(12345); for (auto k=0; k(num_runs*num_folds, num_kernels); - sg_rand->set_seed(12345); + + // set seed like this is about to make CrossValidationSplitting will have a + // same seed during this test. Not sure if it's a good thing to do. + cv.m_kfold_x->set_seed(12345); + cv.m_kfold_y->set_seed(12345); + CMath::init_random(12345); + CMath::init_random(12345); cv(kernel_mgr); kernel_mgr.unset_precomputed_distance(); @@ -199,7 +214,10 @@ TEST(CrossValidationMMD, unbiased_full) permutation_mmd.m_stype=stype; permutation_mmd.m_num_null_samples=num_null_samples; - sg_rand->set_seed(12345); + // set the seed for CrossValidationSplitting + kfold_p->set_seed(12345); + kfold_q->set_seed(12345); + CMath::init_random(12345); for (auto k=0; k(num_runs*num_folds, num_kernels); - sg_rand->set_seed(12345); + + // set seed like this is about to make CrossValidationSplitting will have a + // same seed during this test. Not sure if it's a good thing to do. + cv.m_kfold_x->set_seed(12345); + cv.m_kfold_y->set_seed(12345); + CMath::init_random(12345); + CMath::init_random(12345); + CMath::init_random(12345); cv(kernel_mgr); kernel_mgr.unset_precomputed_distance(); @@ -294,7 +319,10 @@ TEST(CrossValidationMMD, unbiased_incomplete) permutation_mmd.m_stype=stype; permutation_mmd.m_num_null_samples=num_null_samples; - sg_rand->set_seed(12345); + // set the seed for CrossValidationSplitting + kfold_p->set_seed(12345); + kfold_q->set_seed(12345); + CMath::init_random(12345); for (auto k=0; k(new CRandom()); SGMatrix data(dim, num_vec); for (auto i=0; irandom(0.0, 0.1); + data.matrix[i] = m_rng->random(0.0, 0.1); auto feats=some >(data); auto kernel=some(10, 2*sigma*sigma); diff --git a/tests/unit/statistical_testing/internals/PermutationMMD_unittest.cc b/tests/unit/statistical_testing/internals/PermutationMMD_unittest.cc index b250ca56fd6..5839ae903d7 100644 --- a/tests/unit/statistical_testing/internals/PermutationMMD_unittest.cc +++ b/tests/unit/statistical_testing/internals/PermutationMMD_unittest.cc @@ -91,7 +91,7 @@ TEST(PermutationMMD, biased_full_single_kernel) permutation_mmd.m_stype=stype; permutation_mmd.m_num_null_samples=num_null_samples; - sg_rand->set_seed(12345); + CMath::init_random(12345); SGVector result_1=permutation_mmd(kernel_matrix); auto compute_mmd=ComputeMMD(); @@ -101,7 +101,7 @@ TEST(PermutationMMD, biased_full_single_kernel) Map map(kernel_matrix.matrix, kernel_matrix.num_rows, kernel_matrix.num_cols); SGVector result_2(num_null_samples); - sg_rand->set_seed(12345); + CMath::init_random(12345); for (auto i=0; i perm(kernel_matrix.num_rows); @@ -115,7 +115,7 @@ TEST(PermutationMMD, biased_full_single_kernel) SGVector inds(kernel_matrix.num_rows); SGVector result_3(num_null_samples); - sg_rand->set_seed(12345); + CMath::init_random(12345); for (auto i=0; iset_seed(12345); + CMath::init_random(12345); SGVector result_1=permutation_mmd(kernel_matrix); auto compute_mmd=ComputeMMD(); compute_mmd.m_n_x=n; compute_mmd.m_n_y=m; compute_mmd.m_stype=stype; - + CMath::init_random(12345); Map map(kernel_matrix.matrix, kernel_matrix.num_rows, kernel_matrix.num_cols); SGVector result_2(num_null_samples); - sg_rand->set_seed(12345); + for (auto i=0; i perm(kernel_matrix.num_rows); @@ -195,7 +195,8 @@ TEST(PermutationMMD, unbiased_full_single_kernel) SGVector inds(kernel_matrix.num_rows); SGVector result_3(num_null_samples); - sg_rand->set_seed(12345); + + CMath::init_random(12345); for (auto i=0; iset_seed(12345); + CMath::init_random(12345); SGVector result_1=permutation_mmd(kernel_matrix); auto compute_mmd=ComputeMMD(); @@ -259,8 +260,9 @@ TEST(PermutationMMD, unbiased_incomplete_single_kernel) compute_mmd.m_stype=stype; Map map(kernel_matrix.matrix, kernel_matrix.num_rows, kernel_matrix.num_cols); + + CMath::init_random(12345); SGVector result_2(num_null_samples); - sg_rand->set_seed(12345); for (auto i=0; i perm(kernel_matrix.num_rows); @@ -272,9 +274,10 @@ TEST(PermutationMMD, unbiased_incomplete_single_kernel) result_2[i]=compute_mmd(permuted_km); } + CMath::init_random(12345); SGVector inds(kernel_matrix.num_rows); SGVector result_3(num_null_samples); - sg_rand->set_seed(12345); + for (auto i=0; iset_seed(12345); + CMath::init_random(12345); SGVector result_1=permutation_mmd(kernel_matrix); - sg_rand->set_seed(12345); + CMath::init_random(12345); SGVector result_2=permutation_mmd(Kernel(kernel)); EXPECT_TRUE(result_1.size()==result_2.size()); @@ -386,7 +389,7 @@ TEST(PermutationMMD, biased_full_multi_kernel) permutation_mmd.m_stype=stype; permutation_mmd.m_num_null_samples=num_null_samples; - sg_rand->set_seed(12345); + CMath::init_random(12345); SGMatrix null_samples=permutation_mmd(kernel_mgr); kernel_mgr.unset_precomputed_distance(); @@ -397,7 +400,7 @@ TEST(PermutationMMD, biased_full_multi_kernel) { CKernel* kernel=kernel_mgr.kernel_at(k); kernel->init(merged_feats, merged_feats); - sg_rand->set_seed(12345); + CMath::init_random(12345); SGVector curr_null_samples=permutation_mmd(kernel->get_kernel_matrix()); ASSERT_EQ(curr_null_samples.size(), null_samples.num_rows); @@ -452,7 +455,7 @@ TEST(PermutationMMD, unbiased_full_multi_kernel) permutation_mmd.m_stype=stype; permutation_mmd.m_num_null_samples=num_null_samples; - sg_rand->set_seed(12345); + CMath::init_random(12345); SGMatrix null_samples=permutation_mmd(kernel_mgr); kernel_mgr.unset_precomputed_distance(); @@ -463,7 +466,7 @@ TEST(PermutationMMD, unbiased_full_multi_kernel) { CKernel* kernel=kernel_mgr.kernel_at(k); kernel->init(merged_feats, merged_feats); - sg_rand->set_seed(12345); + CMath::init_random(12345); SGVector curr_null_samples=permutation_mmd(kernel->get_kernel_matrix()); ASSERT_EQ(curr_null_samples.size(), null_samples.num_rows); @@ -518,7 +521,7 @@ TEST(PermutationMMD, unbiased_incomplete_multi_kernel) permutation_mmd.m_stype=stype; permutation_mmd.m_num_null_samples=num_null_samples; - sg_rand->set_seed(12345); + CMath::init_random(12345); SGMatrix null_samples=permutation_mmd(kernel_mgr); kernel_mgr.unset_precomputed_distance(); @@ -529,7 +532,7 @@ TEST(PermutationMMD, unbiased_incomplete_multi_kernel) { CKernel* kernel=kernel_mgr.kernel_at(k); kernel->init(merged_feats, merged_feats); - sg_rand->set_seed(12345); + CMath::init_random(12345); SGVector curr_null_samples=permutation_mmd(kernel->get_kernel_matrix()); ASSERT_EQ(curr_null_samples.size(), null_samples.num_rows); diff --git a/tests/unit/statistical_testing/internals/WithinBlockPermutation_unittest.cc b/tests/unit/statistical_testing/internals/WithinBlockPermutation_unittest.cc index c65ea42df3d..8d4f1ae0d51 100644 --- a/tests/unit/statistical_testing/internals/WithinBlockPermutation_unittest.cc +++ b/tests/unit/statistical_testing/internals/WithinBlockPermutation_unittest.cc @@ -79,7 +79,8 @@ TEST(WithinBlockPermutation, biased_full) // compute using within-block-permutation functor operation compute=shogun::internal::mmd::WithinBlockPermutation(n, m, ST_BIASED_FULL); - sg_rand->set_seed(12345); + + CMath::init_random(12345); auto result_1=compute(mat); auto mmd=shogun::internal::mmd::ComputeMMD(); @@ -93,8 +94,10 @@ TEST(WithinBlockPermutation, biased_full) Map map(mat.matrix, mat.num_rows, mat.num_cols); PermutationMatrix perm(mat.num_rows); perm.setIdentity(); + SGVector perminds(perm.indices().data(), perm.indices().size(), false); - sg_rand->set_seed(12345); + + CMath::init_random(12345); CMath::permute(perminds); MatrixXf permuted = perm.transpose()*map*perm; SGMatrix permuted_km(permuted.data(), permuted.rows(), permuted.cols(), false); @@ -104,7 +107,8 @@ TEST(WithinBlockPermutation, biased_full) // shuffled samples, then compute a biased-full statistic on this matrix SGVector inds(mat.num_rows); std::iota(inds.vector, inds.vector+inds.vlen, 0); - sg_rand->set_seed(12345); + + CMath::init_random(12345); CMath::permute(inds); feats->add_subset(inds); kernel->init(feats, feats); @@ -148,7 +152,8 @@ TEST(WithinBlockPermutation, unbiased_full) // compute using within-block-permutation functor operation compute=shogun::internal::mmd::WithinBlockPermutation(n, m, ST_UNBIASED_FULL); - sg_rand->set_seed(12345); + + CMath::init_random(12345); auto result_1=compute(mat); auto mmd=shogun::internal::mmd::ComputeMMD(); @@ -163,7 +168,8 @@ TEST(WithinBlockPermutation, unbiased_full) PermutationMatrix perm(mat.num_rows); perm.setIdentity(); SGVector perminds(perm.indices().data(), perm.indices().size(), false); - sg_rand->set_seed(12345); + + CMath::init_random(12345); CMath::permute(perminds); MatrixXf permuted = perm.transpose()*map*perm; SGMatrix permuted_km(permuted.data(), permuted.rows(), permuted.cols(), false); @@ -173,7 +179,8 @@ TEST(WithinBlockPermutation, unbiased_full) // shuffled samples, then compute unbiased-full statistic on this matrix SGVector inds(mat.num_rows); std::iota(inds.vector, inds.vector+inds.vlen, 0); - sg_rand->set_seed(12345); + + CMath::init_random(12345); CMath::permute(inds); feats->add_subset(inds); kernel->init(feats, feats); @@ -216,7 +223,8 @@ TEST(WithinBlockPermutation, unbiased_incomplete) // compute using within-block-permutation functor operation compute=shogun::internal::mmd::WithinBlockPermutation(n, n, ST_UNBIASED_INCOMPLETE); - sg_rand->set_seed(12345); + + CMath::init_random(12345); auto result_1=compute(mat); auto mmd=shogun::internal::mmd::ComputeMMD(); @@ -231,7 +239,8 @@ TEST(WithinBlockPermutation, unbiased_incomplete) PermutationMatrix perm(mat.num_rows); perm.setIdentity(); SGVector perminds(perm.indices().data(), perm.indices().size(), false); - sg_rand->set_seed(12345); + + CMath::init_random(12345); CMath::permute(perminds); MatrixXf permuted = perm.transpose()*map*perm; SGMatrix permuted_km(permuted.data(), permuted.rows(), permuted.cols(), false); @@ -241,7 +250,8 @@ TEST(WithinBlockPermutation, unbiased_incomplete) // shuffled samples, then compute uniased-incomplete statistic on this matrix SGVector inds(mat.num_rows); std::iota(inds.vector, inds.vector+inds.vlen, 0); - sg_rand->set_seed(12345); + + CMath::init_random(12345); CMath::permute(inds); feats->add_subset(inds); kernel->init(feats, feats);