-
-
Notifications
You must be signed in to change notification settings - Fork 476
rand_distr: Fix dirichlet sample method for small alpha. #1209
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
745ace8
rand_distr: Fix dirichlet sample method for small alpha.
WarrenWeckesser c44ac16
Merge branch 'master' into dirichlet-small-alpha
WarrenWeckesser 4ecb35e
Refactor:
WarrenWeckesser 7513e83
Convert `Dirichlet` from an `enum` to a `struct` containing an `enum`.
WarrenWeckesser 030d2ad
Fix namespace qualifier for Serialize and Deserialize.
WarrenWeckesser 7c97f9b
Merge master and fix conflicts.
WarrenWeckesser 7fcb25f
Merge branch 'master' into dirichlet-small-alpha
WarrenWeckesser 2225652
Copy-edit a comment and make it a doc comment.
WarrenWeckesser c12db0b
Use an array for DirichletFromGamma.samplers
WarrenWeckesser File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -9,11 +9,160 @@ | |||||
|
|
||||||
| //! The dirichlet distribution. | ||||||
| #![cfg(feature = "alloc")] | ||||||
| use num_traits::Float; | ||||||
| use crate::{Distribution, Exp1, Gamma, Open01, StandardNormal}; | ||||||
| use rand::Rng; | ||||||
| use core::fmt; | ||||||
| use crate::{Beta, Distribution, Exp1, Gamma, Open01, StandardNormal}; | ||||||
| use alloc::{boxed::Box, vec, vec::Vec}; | ||||||
| use core::fmt; | ||||||
| use num_traits::{Float, NumCast}; | ||||||
| use rand::Rng; | ||||||
|
|
||||||
| #[derive(Clone, Debug, PartialEq)] | ||||||
| #[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))] | ||||||
| struct DirichletFromGamma<F> | ||||||
| where | ||||||
| F: Float, | ||||||
| StandardNormal: Distribution<F>, | ||||||
| Exp1: Distribution<F>, | ||||||
| Open01: Distribution<F>, | ||||||
| { | ||||||
| samplers: Box<[Gamma<F>]>, | ||||||
| } | ||||||
|
|
||||||
| impl<F> DirichletFromGamma<F> | ||||||
| where | ||||||
| F: Float, | ||||||
| StandardNormal: Distribution<F>, | ||||||
| Exp1: Distribution<F>, | ||||||
| Open01: Distribution<F>, | ||||||
| { | ||||||
| // Construct a new `Dirichlet` with the given alpha parameter `alpha`. | ||||||
| // | ||||||
| // This function is part of a private implementation detail. | ||||||
| // It assumes that the input is correct, so no validation is done. | ||||||
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||
| #[inline] | ||||||
| fn new(alpha: &[F]) -> DirichletFromGamma<F> { | ||||||
| let gamma_dists = alpha | ||||||
| .iter() | ||||||
| .map(|a| Gamma::new(*a, F::one()).unwrap()) | ||||||
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||
| .collect::<Vec<Gamma<F>>>() | ||||||
| .into_boxed_slice(); | ||||||
| DirichletFromGamma { | ||||||
| samplers: gamma_dists, | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| impl<F> Distribution<Vec<F>> for DirichletFromGamma<F> | ||||||
| where | ||||||
| F: Float, | ||||||
| StandardNormal: Distribution<F>, | ||||||
| Exp1: Distribution<F>, | ||||||
| Open01: Distribution<F>, | ||||||
| { | ||||||
| fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec<F> { | ||||||
| let n = self.samplers.len(); | ||||||
| let mut samples = vec![F::zero(); n]; | ||||||
| let mut sum = F::zero(); | ||||||
| for (s, g) in samples.iter_mut().zip(self.samplers.iter()) { | ||||||
| *s = g.sample(rng); | ||||||
| sum = sum + (*s); | ||||||
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||
| } | ||||||
| let invacc = F::one() / sum; | ||||||
| for s in samples.iter_mut() { | ||||||
| *s = (*s) * invacc; | ||||||
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||
| } | ||||||
| samples | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| #[derive(Clone, Debug, PartialEq)] | ||||||
| #[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))] | ||||||
| struct DirichletFromBeta<F> | ||||||
| where | ||||||
| F: Float, | ||||||
| StandardNormal: Distribution<F>, | ||||||
| Exp1: Distribution<F>, | ||||||
| Open01: Distribution<F>, | ||||||
| { | ||||||
| samplers: Box<[Beta<F>]>, | ||||||
| } | ||||||
|
|
||||||
| impl<F> DirichletFromBeta<F> | ||||||
| where | ||||||
| F: Float, | ||||||
| StandardNormal: Distribution<F>, | ||||||
| Exp1: Distribution<F>, | ||||||
| Open01: Distribution<F>, | ||||||
| { | ||||||
| // Construct a new `Dirichlet` with the given alpha parameter `alpha`. | ||||||
| // | ||||||
| // This function is part of a private implementation detail. | ||||||
| // It assumes that the input is correct, so no validation is done. | ||||||
| #[inline] | ||||||
| fn new(alpha: &[F]) -> DirichletFromBeta<F> { | ||||||
| // Form the right-to-left cumulative sum of alpha, exluding the | ||||||
| // first element of alpha. E.g. if alpha = [a0, a1, a2, a3], then | ||||||
| // after the call to `alpha_sum_rl.reverse()` below, alpha_sum_rl | ||||||
| // will hold [a1+a2+a3, a2+a3, a3]. | ||||||
| let mut alpha_sum_rl: Vec<F> = alpha | ||||||
| .iter() | ||||||
| .skip(1) | ||||||
| .rev() | ||||||
| // scan does the cumulative sum | ||||||
| .scan(F::zero(), |sum, x| { | ||||||
| *sum = *sum + *x; | ||||||
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||
| Some(*sum) | ||||||
| }) | ||||||
| .collect(); | ||||||
| alpha_sum_rl.reverse(); | ||||||
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||
| let beta_dists = alpha | ||||||
| .iter() | ||||||
| .zip(alpha_sum_rl.iter()) | ||||||
| .map(|t| Beta::new(*t.0, *t.1).unwrap()) | ||||||
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||
| .collect::<Vec<Beta<F>>>() | ||||||
| .into_boxed_slice(); | ||||||
| DirichletFromBeta { | ||||||
| samplers: beta_dists, | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| impl<F> Distribution<Vec<F>> for DirichletFromBeta<F> | ||||||
| where | ||||||
| F: Float, | ||||||
| StandardNormal: Distribution<F>, | ||||||
| Exp1: Distribution<F>, | ||||||
| Open01: Distribution<F>, | ||||||
| { | ||||||
| fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec<F> { | ||||||
| let n = self.samplers.len(); | ||||||
| let mut samples = vec![F::zero(); n + 1]; | ||||||
| let mut acc = F::one(); | ||||||
|
|
||||||
| for (s, beta) in samples.iter_mut().zip(self.samplers.iter()) { | ||||||
| let beta_sample = beta.sample(rng); | ||||||
| *s = acc * beta_sample; | ||||||
| acc = acc * (F::one() - beta_sample); | ||||||
vks marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
| } | ||||||
| samples[n] = acc; | ||||||
| samples | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| #[derive(Clone, Debug, PartialEq)] | ||||||
| #[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))] | ||||||
| enum DirichletRepr<F> | ||||||
| where | ||||||
| F: Float, | ||||||
| StandardNormal: Distribution<F>, | ||||||
| Exp1: Distribution<F>, | ||||||
| Open01: Distribution<F>, | ||||||
| { | ||||||
| /// Dirichlet distribution that generates samples using the gamma distribution. | ||||||
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||
| FromGamma(DirichletFromGamma<F>), | ||||||
|
|
||||||
| /// Dirichlet distribution that generates samples using the beta distribution. | ||||||
|
||||||
| /// Dirichlet distribution that generates samples using the beta distribution. | |
| /// Dirichlet distribution that generates samples using the Beta distribution. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done.
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
vks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.