real T_kirkpatrick(real x[], int n) { int n_neg = 0; real sx_neg = 0; for (int i=0; i<n; i++) { if (x[i] < 0) { sx_neg += -x[i]; n_neg++; } } return - (sx_neg / n_neg) / logr(0.8); }
real randn() { static bool prepped = false; static real prepped_result = 0; if (prepped) { prepped = false; return prepped_result; } else { real u1 = randf(), u2 = randf(); real len = sqrtr(-2 * logr(u1)); prepped = true; prepped_result = len * sinr(2*M_PI*u2); return len * cosr(2*M_PI*u2); } }
MatrixXf EMclustering::expectation(MatrixXf x, gaussian_model model, double &llh) { //cerr<<"===="<<endl; MatrixXf mu(model.mu.rows(),model.mu.cols()); mu = model.mu; MatrixXf *sigma; sigma = new MatrixXf[clusternum]; //for(int i=0;i<clusternum;i++) // sigma[i] = model.sigma[i]; //cerr<<"1"<<endl; sigma = model.sigma; VectorXf w(model.weight.size()); w = model.weight; //cerr<<mu<<endl; //cerr<<w<<endl<<endl; //for(int i=0;i<clusternum;i++)cerr<<sigma[i]<<endl; //cerr<<endl; int n = x.cols(); int k = mu.cols(); MatrixXf logrho(n,k); logrho.setZero(n,k); //cerr<<logrho<<endl; //cerr<<logrho<<endl<<endl; for(int i=0;i<k;i++) { //cerr<<i<<endl; logrho.col(i) = loggausspdf(x,mu.col(i),sigma[i]); //cerr<<mu.col(i)<<endl; } //cerr<<logrho<<endl<<endl; w = w.array().log();//cerr<<w<<endl<<endl; MatrixXf tmp1(logrho.rows(),logrho.cols()); tmp1 = logrho.rowwise() + w.adjoint(); logrho = tmp1;//cerr<<logrho<<endl<<endl; VectorXf t(logrho.rows()); t = logsumexp(logrho,2);//cerr<<t<<endl<<endl; llh = t.sum()/n;//cerr<<llh<<endl<<endl; MatrixXf logr(logrho.rows(),logrho.cols()); logr = logrho.colwise() - t;//cerr<<logr<<endl<<endl; MatrixXf r(logrho.rows(),logrho.cols()); r = logr.array().exp();//cerr<<r<<endl<<endl; logrho.resize(0,0); mu.resize(0,0); w.resize(0); //for(int i=0;i<clusternum;i++)//.................. // sigma[i].resize(0,0); delete [] sigma; tmp1.resize(0,0); t.resize(0); logr.resize(0,0); //cerr<<r<<endl<<endl; //cerr<<llh<<endl; return r; }