如何在 PyTorch 中建立元素從泊松分佈取樣的張量?


要建立元素從泊松分佈取樣的張量,我們應用 **torch.poisson()** 方法。此方法將元素為速率引數的張量作為輸入張量。它返回一個張量,其元素是從具有 **速率** 引數的泊松分佈中取樣的。

語法

torch.poisson(rates)

其中引數 **rates** 是速率引數的 torch 張量。速率引數用於從泊松分佈中取樣元素。

步驟

我們可以使用以下步驟來建立元素從泊松分佈取樣的張量:

  • 匯入所需的庫。在以下所有示例中,所需的 Python 庫為 **torch**。確保您已安裝它。

import torch
  • 定義速率引數的 torch 張量。我們如下定義 0 到 9 之間的速率引數。

rates = torch.randn(7).uniform_(0, 9)
  • 計算元素從具有上述速率的泊松分佈中取樣的張量。

poisson_tensor = torch.poisson(rates)
  • 列印計算出的泊松張量。

print("Poisson Tensor:
", poisson_tensor)

示例 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:
", poisson_tensor)

輸出

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.])

在上述示例中,我們建立了一個元素從具有 0 到 9 之間的速率引數的泊松分佈中取樣的張量。

示例 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:
", poisson_tensor)

輸出

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.]])

在上述示例中,我們建立了一個元素從具有 0 到 7 之間的速率引數的泊松分佈中取樣的張量。

更新於: 2022年1月27日

366 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.