void HDP::sample_first_level_concentration(double gamma_a, double gamma_b) { /// (p 585 in escobar and west) double shape = gamma_a; double scale = gamma_b; int n = 0; RNGScope scope; for (int k = 0; k < hdp_state_->num_topics_; ++k) { n += hdp_state_->beta_u_[k]; } double eta = Rf_rbeta(hdp_state_->gamma_ + 1, n); double pi = shape + hdp_state_->num_topics_ - 1; double rate = 1.0 / scale - log(eta); pi = pi / (pi + rate * n); unsigned int cc = Rf_rbinom(1,pi); if (cc == 1) hdp_state_->gamma_ = Rf_rgamma(shape + hdp_state_->num_topics_, 1.0 / rate); else hdp_state_->gamma_ = Rf_rgamma(shape + hdp_state_->num_topics_ - 1, 1.0 / rate); }
void MCMCPkPg::update_sigma_theta( PkPgModel& model, PkPgResult& Result ){ mat eIv( model.V, model.V ); eIv.eye(); eIv = eIv * model.epsilon; double sd =( 5.6644 / model.V ); for(size_t i = 0; i< model.N; i++ ){ rowvec theta_bar_old = Result.logTheta_bar_old.row( i ); rowvec theta_bar_now = Result.logTheta_bar.row( i ); rowvec theta_now = Result.logTheta.row( i ); rowvec theta_old = Result.logTheta_old.row( i ); if( cIter < 5000 ){ Result.SS_theta.slice( i ) = Result.SS_theta.slice( i ) + theta_now.t() * theta_now; } else if( cIter >= 5000 ){ Result.SS_theta.slice( i ) = Result.SS_theta.slice( i ) + theta_now.t() * theta_now; if( Rf_rbinom(1,0.01) == 1 ){ Result.Sigma_theta.slice(i) = sd * ( ( Result.SS_theta.slice( i ) - ( cIter + 2 ) * theta_bar_now.t()*theta_bar_now )/( cIter + 1 ) + eIv ) ; //sd * } else { Result.Sigma_theta.slice(i) = Result.SigmaTheta0; } // /(cIter); //+ sd * eIv; //Result.Sigma_theta.slice(i).print("Result.Sigma_theta.slice(i)"); } //else{ // if( cIter> 20 ){ //T0=10 // mat to = cIter*theta_old.t() * theta_bar_old; // mat tn=( cIter + 1 ) * theta_bar_now.t()*theta_bar_now; // mat tt=theta_now.t() * theta_now; // Result.Sigma_theta.slice( i ) = ( (cIter) / cIter+1 ) * Result.Sigma_theta.slice( i ) // + ( sd / ( cIter + 1 ) ) // * ( ( cIter + 1 ) * theta_bar_old.t() * theta_bar_old // - ( cIter + 2 ) * theta_bar_now.t() * theta_bar_now // + theta_now.t() * theta_now // + eIv ); // // } else { //} //} } }
void HDP::sample_second_level_concentration(double alpha_a, double alpha_b) { double shape = alpha_a; double scale = alpha_b; RNGScope scope; int n = 0; for (int k = 0; k < hdp_state_->num_topics_; ++k) { n += hdp_state_->beta_u_[k]; } double rate, sum_log_w, sum_s; for (int step = 0; step < 20; ++step) { sum_log_w = 0.0; sum_s = 0.0; for (int d = 0; d < num_docs_; ++d) { sum_log_w += log(Rf_rbeta(hdp_state_->alpha_ + 1, doc_states_[d]->doc_length_)); sum_s += (double)Rf_rbinom(1,doc_states_[d]->doc_length_ / (doc_states_[d]->doc_length_ + hdp_state_->alpha_)); } rate = 1.0 / scale - sum_log_w; hdp_state_->alpha_ = Rf_rgamma(shape + n - sum_s, 1.0 / rate); } }
Type rbinom(Type size, Type prob) { return Rf_rbinom(asDouble(size), asDouble(prob)); }