double BLM::log_likelihood(const Vec & beta, Vec *g, Mat *h, bool initialize_derivs)const{ const BLM::DatasetType &data(dat()); if(initialize_derivs){if(g){ *g=0; if(h){ *h=0;}}} double ans = 0; for(int i = 0; i < data.size(); ++i){ // y and n had been defined as uint's but y-n*p was computing // -n, which overflowed int y = data[i]->y(); int n = data[i]->n(); const Vec & x(data[i]->x()); double eta = x.dot(beta) - log_alpha_; double p = logit_inv(eta); double loglike = dbinom(y, n, p, true); ans += loglike; if(g){ g->axpy(x, y-n*p); // g += (y-n*p) * x; if(h){ h->add_outer(x,x, -n*p*(1-p)); // h += -npq * x x^T }}} return ans; }
double BLM::logp(uint y, uint n, const Vec &x, bool logscale)const{ double eta = predict(x); double p = logit_inv(eta); return dbinom(y, n, p, logscale); }
static inline bool keep_flip(double logp_old, double logp_new){ if(!std::isfinite(logp_new)) return false; double pflip = logit_inv(logp_new - logp_old); double u = runif(0,1); return u < pflip ? true : false; }
// Element-by-element application of the inverse logit function. // Args: // logits: A vector of real numbers, each representing the chance of an // event on the logit scale. // Returns: // The probability associated with each element of the argument, computed // using the inverse logit transformation. inline Vector logit_inv(const Vector &logits) { Vector ans(logits); for (int i = 0; i < ans.size(); ++i) ans[i] = logit_inv(ans[i]); return ans; }