# How to create a tensor whose elements are sampled from a Poisson distribution in PyTorch?

PyTorchServer Side ProgrammingProgramming

To create a tensor whose elements are sampled from a Poisson distribution, we apply the torch.poisson() method. This method takes a tensor whose elements are rate parameters as input tensor. It returns a tensor whose elements are sampled from a Poisson distribution with the rate parameter.

### Syntax

torch.poisson(rates)

where the parameter rates is a torch tensor of rate parameters. Rate parameters are used to sample elements from a Poisson distribution.

## Steps

We could use the following steps to create a tensor whose elements are sampled from a Poisson distribution −

• Import the required library. In all the following examples, the required Python library is torch. Make sure you have already installed it.

import torch
• Define a torch tensor of rate parameters. We define the rate parameter between 0 and 9 as below.

rates = torch.randn(7).uniform_(0, 9)
• Compute the tensor whose elements are sampled from Poisson Distribution with rates defined above.

poisson_tensor = torch.poisson(rates)
• Print the computed Poisson Tensor.

print("Poisson Tensor:\n", poisson_tensor)

## Example 1

import torch

# rate parameter between 0 and 9
rates = torch.randn(7).uniform_(0, 9)
print(rates)

poisson_tensor = torch.poisson(rates)
print("Poisson Tensor:\n", poisson_tensor)

## Output

tensor([2.7700, 3.2705, 5.3056, 4.6312, 2.7052, 6.9287, 5.9278])
Poisson Tensor:
tensor([ 3., 2., 8., 1., 5., 10., 4.])

In the above example, we created a tensor whose elements are sampled from a Poisson distribution with rate parameters between 0 and 9.

## Example 2

import torch

# rate parameter between 0 and 7
rates = torch.rand(5, 5)*7
print(rates)

poisson_tensor = torch.poisson(rates)
print("Poisson Tensor:\n", poisson_tensor)

## Output

tensor([[0.0832, 6.8774, 3.1778, 3.7178, 3.0686],
[1.6273, 6.0398, 1.3534, 3.8841, 2.3612],
[3.8822, 3.6421, 0.0593, 4.1532, 6.2498],
[1.3848, 0.6932, 1.1505, 4.0900, 6.1998],
[4.7704, 0.7257, 2.4099, 6.0164, 3.5351]])
Poisson Tensor:
tensor([[0., 6., 2., 1., 2.],
[3., 9., 1., 3., 3.],
[3., 4., 0., 5., 6.],
[0., 3., 0., 3., 2.],
[2., 0., 4., 5., 5.]])

In the above example, we created a tensor whose elements are sampled from a Poisson distribution with rate parameters between 0 and 7.

Updated on 27-Jan-2022 06:48:25