# Pytorch distributions and the equivalent of `dbinom()` and `pbinom()` from R

I am new to pytorch and was trying to convert some code from R to Pytorch. Now in R there are functions
to estimate the score or likelihood under some probability distribution. For example, if I have a Binomial distribution with 10 trials and a probability of success of 0.5, then I could evaluate the probability of getting 4 successes out of 10 trials with:

`````` dbinom(4, size=10, prob=0.5)
``````

If I wanted to find the probability of getting 4 or less successes in 10 trials, I would use:

`````` pbinom(4, size=10, prob=0.5)
``````

What would the equivalent code be in Pytorch? I was thinking it would be `prob()` but I was not sure if that was dbinom or pbinom, or if there was a better way to code this? Thanks.

Point of fact, the actual lines of R code I am trying to replicate come from McElreath’s book,
Statistical Rethinking, and the R code is:

``````p_grid <- seq( from=0 , to=1 , length.out=20 )
likelihood <- dbinom( 6 , size=9 , prob=p_grid )
``````

There is Distribution.cdf abstract method, but it is not implemented for most distributions. scipy.stats is generally better, if you’re doing interactive work and don’t need gradients (see also: torch.from_numpy(), Tensor.numpy()).

As for density, Binomial(total_count=n,probs=p).log_prob(x).exp() would correspond to dbinom(x,n,p), I think.

1 Like