Skip to content

Instantly share code, notes, and snippets.

@Shusei-E
Last active April 28, 2016 01:58
Show Gist options
  • Save Shusei-E/adbfd85aa67d9ac9ef6e122142c4239d to your computer and use it in GitHub Desktop.
Save Shusei-E/adbfd85aa67d9ac9ef6e122142c4239d to your computer and use it in GitHub Desktop.
DataGen with fixed variance
#include <iostream>
#include <fstream>
#include <string>
#include <random>
// Eigen
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main(){
int N=2000; // number of observations
int K=3; // number of mixture components
Vector3d mu(-0.8, 0.0, 2.0); // mean vector
double tau=1.5; //common variance
double pi[] = {0.5, 0.3, 0.2}; // mixture rate (sum is 1)
VectorXd pi_total(K);
double running_total = 0.0;
VectorXd genVec(N); // store generated data
VectorXd Z(N);
VectorXd class_(N);
// Create Z (here, Z is mu vector)
for(int i=0; i<sizeof(pi)/sizeof(pi[0]); i++){ //配列の要素数を求めている
running_total += pi[i];
pi_total[i] = running_total;
}
// Weighted Random Generation http://goo.gl/mr5d8G
double rnd;
random_device seed_gen; // http://cpprefjp.github.io/reference/random.html
mt19937 engine(seed_gen());
uniform_real_distribution<> dist1(0.0, 1.0);
for(int i=0; i<N; i++){
rnd = dist1(engine) * running_total;
for(int s=0; s<K; s++){
if (rnd < pi_total[s]){
Z[i] = mu[s];
class_[i] = s;
break;
}//end if
}//end for(s)
}//end for(i)
// Create Observations (genVec)
for(int i=0; i<N; i++){
normal_distribution<> norm_dist(Z[i], tau); //!!: Z is not the same as in the original
genVec[i] = norm_dist(engine);
}//end(i)
ofstream outputfileData("GeneratedData.txt");
outputfileData << genVec;
outputfileData.close();
ofstream outputfileClass("GeneratedClass.txt");
outputfileClass << class_;
outputfileClass.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment