Python PyTorch 中的 torch.normal() 方法
為了建立一個從具有給定**均值**和**標準差**的不同正態分佈中抽取的隨機數張量,我們使用**torch.normal()**方法。此方法接受兩個輸入引數 - **均值**和**標準差**。
**均值**是一個張量,包含每個輸出元素正態分佈的均值,以及
**標準差**是一個張量,包含每個輸出元素正態分佈的標準差。
它返回一個從具有給定**均值**和**標準差**的不同正態分佈中抽取的隨機數張量。
語法
torch.normal(mean, std)
步驟
我們可以使用以下步驟建立一個從不同正態分佈中抽取的隨機數張量:
匯入所需的庫。在以下所有示例中,所需的 Python 庫是**torch**。確保您已安裝它。
import torch
定義兩個 torch 張量 - **均值**和**標準差**。兩個張量中的元素數量必須相同。
mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)
計算使用給定的**均值**和**標準差**從不同正態分佈中抽取的隨機數張量。
tensor = torch.normal(mean, std)
列印計算出的隨機數張量。
print("Tensor:
",tensor)示例 1
# torch.normal(mean, std, *, generator=None, out=None) → Tensor
import torch
# define mean and std
mean=torch.arange(1., 11.)
std=torch.arange(1, 0, -0.1)
# print mean and std
print("Mean:
", mean)
print("STD:
", std)
# compute the tensor of random numbers
tensor = torch.normal(mean, std)
# print the computed tensor
print("Tensor:
",tensor)輸出
Mean: tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]) STD: tensor([1.0000, 0.9000, 0.8000, 0.7000, 0.6000, 0.5000,0.4000, 0.3000, 0.2000, 0.1000]) Tensor: tensor([ 0.8557, 1.1373, 2.5573, 3.3513, 4.3764, 5.4221, 6.5343, 7.9068, 8.6984, 10.1292])
請注意,在上面的示例中,**均值**和**標準差**都已給出,並且兩個張量上的元素都相同。
示例 2
# torch.normal(mean=0.0, std, *, out=None) → Tensor import torch tensor = torch.normal(mean=0.5, std=torch.arange(1., 6.)) print(tensor)
輸出
tensor([ 0.4357, 1.1931, 2.8821, -2.3777, -1.8948])
請注意,在上面的示例中,均值在所有抽取的元素中共享。
示例 3
# torch.normal(mean, std=1.0, *, out=None) → Tensor import torch tensor = torch.normal(mean=torch.arange(1., 6.)) print(tensor)
輸出
tensor([1.3951, 2.0769, 2.4525, 3.6972, 7.7257])
請注意,在上面的示例中,標準差作為引數給出。這裡,預設的**標準差**設定為 1。**標準差**在所有抽取的元素中共享。
示例 4
# torch.normal(mean, std, size, *, out=None) → Tensor import torch tensor = torch.normal(2, 3, size=(1, 4)) print(tensor)
輸出
tensor([1.3951, 2.0769, 2.4525, 3.6972, 7.7257])
請注意,在上面的示例中,均值和標準差在所有抽取的元素中共享。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP