Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Distribution a templated class by sample type. #4

Closed
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add a running count of observations to DirichletCategorical.
  • Loading branch information
emilyfertig committed May 16, 2024
commit cb74c84f675328e26ce616ec9f82b202d8bf81ac
7 changes: 5 additions & 2 deletions cxx/distributions/dirichlet_categorical.hh
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,36 @@ class DirichletCategorical : public Distribution {
public:
double alpha = 1; // hyperparameter (applies to all categories)
std::vector<int> counts; // counts of observed categories
int n; // Total number of observations.
PRNG *prng;

DirichletCategorical(PRNG *prng, int k) { // k is number of categories
this->prng = prng;
counts = std::vector<int>(k, 0);
n = 0;
}
void incorporate(double x) {
assert(x >= 0 && x < counts.size());
counts[size_t(x)] += 1;
++n;
}
void unincorporate(double x) {
const size_t y = x;
assert(y < counts.size());
counts[y] -= 1;
--n;
assert(0 <= counts[y]);
assert(0 <= n);
}
double logp(double x) const {
assert(x >= 0 && x < counts.size());
const int n = std::accumulate(counts.cbegin(), counts.cend(), 0);
const double numer = log(alpha + counts[size_t(x)]);
const double denom = log(n + alpha * counts.size());
return numer - denom;
}
double logp_score() const {
const size_t k = counts.size();
const double a = alpha * k;
const int n = std::accumulate(counts.cbegin(), counts.cend(), 0);
const double lg = std::transform_reduce(
counts.cbegin(),
counts.cend(),
Expand Down