1. 程式人生 > >PyTorch 生成隨機數Tensor(標準分佈、標準正態、離散正態……)

PyTorch 生成隨機數Tensor(標準分佈、標準正態、離散正態……)

在使用PyTorch做實驗時經常會用到生成隨機數Tensor的方法,比如:

torch.rand()
torch.randn()
torch.normal()
torch.linespace()

均勻分佈

*torch.rand(sizes, out=None) → Tensor

返回一個張量,包含了從區間[0, 1]的均勻分佈中抽取的一組隨機數。張量的形狀由引數sizes定義。

引數:

sizes (int…) - 整數序列,定義了輸出張量的形狀
out (Tensor, optinal) - 結果張量

例子:

torch.rand(2, 3)
0.0836 0.6151 0.6958
0.6998 0.2560 0.0139
[torch.FloatTensor of size 2x3]

標準正態分佈

*torch.randn(sizes, out=None) → Tensor

返回一個張量,包含了從標準正態分佈(均值為0,方差為1,即高斯白噪聲)中抽取的一組隨機數。張量的形狀由引數sizes定義。

引數:

sizes (int…) - 整數序列,定義了輸出張量的形狀
out (Tensor, optinal) - 結果張量

例子:

torch.randn(2, 3)
0.5419 0.1594 -0.0413
-2.7937 0.9534 0.4561
[torch.FloatTensor of size 2x3]

離散正態分佈

torch.normal(means, std, out=None) → → Tensor

返回一個張量,包含了從指定均值means和標準差std的離散正態分佈中抽取的一組隨機數。

標準差std是一個張量,包含每個輸出元素相關的正態分佈標準差。

引數:

means (float, optional) - 均值
std (Tensor) - 標準差
out (Tensor) - 輸出張量

例子:

torch.normal(mean=0.5, std=torch.arange(1, 6))
-0.1505
-1.2949
-4.4880
-0.5697
-0.8996
[torch.FloatTensor of size 5]

線性間距向量

torch.linspace(start, end, steps=100, out=None) → Tensor

返回一個1維張量,包含在區間start和end上均勻間隔的step個點。

輸出張量的長度由steps決定。

引數:

start (float) - 區間的起始點
end (float) - 區間的終點
steps (int) - 在start和end間生成的樣本數
out (Tensor, optional) - 結果張量

例子:

torch.linspace(3, 10, steps=5)
3.0000
4.7500
6.5000
8.2500
10.0000
[torch.FloatTensor of size 5]