在使用PyTorch做實驗時經常會用到生成隨機數Tensor的方法,比如:
torch.rand()
torch.randn()
torch.rand_like()
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]
a=torch.rand(3,3) print(a) #與a形狀類似的數組 b=torch.rand_like(a) print(b) #隨機產生1~9的數,形狀為3x3 c=torch.randint(1,10,(3,3)) print(c) #產生一個全為7的2x3的張量 d=torch.full([2,3],7) print(d)
torch.linspace()與torch.logspace():
#生成0到10的4個數構成的等差數列 a = torch.linspace(0,10,steps=4) print(a) #生成0到10的5個數構成的等差數列 b = torch.linspace(0,10,steps=5) print(b) #生成10的0次方為起始值,10的-1次方為終止值的8個數構成的等比數列 c = torch.logspace(0,-1,steps=8) print(c) #生成10的1次方為起始值,10的2次方為終止值的5個數構成的等比數列 d = torch.logspace(1,2,steps=5) print(d)
ones/zeros/eye:
#生成全為1形狀為3x3的張量 a = torch.ones(3,3) print(a) #生成全為0形狀為3x3的張量 b = torch.zeros(3,3) print(b) #生成形狀為4x4的單位矩陣張量 c = torch.eye(4,4) print(c)
randperm()
#產生0~9的10個隨機數的張量 a = torch.randperm(10) print(a) b = torch.randperm(2) print(b)
轉自:https://zhuanlan.zhihu.com/p/31231210