從零開始深度學習Pytorch筆記——張量的創建(下)

我們介紹了Pytorch中的張量,並且講述了張量的各種創建方式,本文我們將繼續研究Pytorch的更多創建方式。

生成正態分佈(高斯分佈)數據的張量torch.normal(mean, std, out=None)參數:mean:均值,std:標準差
這種生成正態分佈數據的張量創建有4種模式:
(1)mean爲張量,std爲張量
(2)mean爲標量,std爲標量
(3)mean爲標量,std爲張量
(4)mean爲張量,std爲標量

#mean爲張量,std爲張量
mean = torch.arange(1,6,dtype=torch.float)
std = torch.arange(1,6,dtype=torch.float)
t = torch.normal(mean,std)
print("mean:{},std:{}".format(mean,std))
print(t)

此時的mean和std都是張量,可以理解爲其中的-0.6152是mean爲1,std爲1的正態分佈採樣得到,其他對應位置數據同理得到,只是從不同的正態分佈中採樣得到。

#mean爲標量,std爲標量
t = torch.normal(0.2,1.0,size=(5,))
print(t)

這裏生成的數據都是通過mean爲0.2,std爲1.0採樣得到的,長度爲5的一維張量。

#mean爲標量,std爲張量
mean = 2
std = torch.arange(1,4,dtype=torch.float)
t = torch.normal(mean,std)
print("mean:{},std:{}".format(mean,std))
print(t)

1.9759是mean爲2,std爲1的正態分佈採樣得到,其他對應位置數據同理得到,只是從不同的正態分佈中(均值不同,標準差相同)採樣得到。

#mean爲張量,std爲標量
mean = torch.arange(1,4,dtype=torch.float)
std = 2
t = torch.normal(mean,std)
print("mean:{},std:{}".format(mean,std))
print(t)

其中,0.2434是mean爲1,std爲2的正態分佈採樣得到,其他對應位置數據同理得到,只是從不同的正態分佈中(均值不同,標準差相同)採樣得到。
標準正態分佈數據的張量標準正態分佈指的是:均值爲0,標準差爲1
torch.randn()
torch.randn(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
size:張量的形狀例如創建一個長度爲6的標準正態分佈張量:torch.randn(6)創建一個二維的標準正態分佈張量:torch.randn(3,4)torch.randn_like()可以根據張量的形狀創建新的標準正態分佈張量
randn_like(input, dtype=None, layout=None, device=None, requires_grad=False)

a = torch.ones((3,4))
t = torch.randn_like(a)
print(t)

創建在 (0,1] 上均勻分佈的張量torch.rand()torch.rand(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
創建一個均勻分佈的長度爲5的一維張量:torch.rand(5)
創建一個均勻分佈的二維張量:torch.rand(3,4)
在區間上創建整數均勻分佈數據的張量torch.randint()和torch.randint_like()可以達到這個效果。

torch.randint(low=0, high, size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
在區間[low,high)上生成整數均勻分佈數據的張量

例如創建在[2,6)上均勻分佈的整數張量,長度爲4的一維張量:torch.randint(2, 6, (4,))

生成在[0,9) 上均勻分佈的整數張量,二維張量:
torch.randint(9, (3, 2))

生成0~n-1的隨機排列一維張量torch.randperm(n, out=None, dtype=torch.int64, layout=torch.strided, device=None, requires_grad=False)
torch.randperm(6)

生成伯努利分佈(0-1分佈,兩點分佈)的張量torch.bernoulli(input, *, generator=None, out=None)input:概率值例如先創建一個張量a,作爲之後的概率值輸入:a = torch.empty(3, 3).uniform_(0, 1)a然後通過a創建張量t:torch.bernoulli(a)#使用上面創建的張量a作爲概率值創建伯努利分佈

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章