Python PyTorch – 如何建立單位矩陣?
單位矩陣,也稱為單位陣,是一個“n ☓ n”的方陣,其主對角線上的元素為1,其餘元素為0。它是方陣的乘法單位元。因為任何方陣乘以單位矩陣都不會改變其值。在矩陣的概念中,單位矩陣也稱為單位陣。單位陣用作方陣在矩陣概念中的乘法單位元。任何方陣乘以單位矩陣,結果都不會改變。線上性代數中,大小為n的單位矩陣是n ☓ n的方陣,其主對角線上的元素為1,其餘元素為0。
要建立一個單位矩陣,我們使用**torch.eye()**方法。此方法將行數作為引數。列數預設設定為行數。您可以透過提供它作為引數來更改行數。此方法返回一個二維張量(矩陣),其對角線為1,所有其他元素為0。
語法
torch.eye(n)
其中**n**是矩陣的行數。預設情況下,列數與行數相同。我們可以提供第二個引數作為列數。
步驟
您可以使用以下步驟建立一個對角線為1,其餘元素為0的矩陣
匯入所需的庫。在以下所有示例中,所需的Python庫是**torch**。確保您已安裝它。
import torch
建立一個對角線為1,其餘元素為0的二維張量(矩陣)。
M = torch.eye(4)
列印上述計算出的矩陣(二維張量)
print(M)
示例1
在下面的示例中,我們將建立一個對角線為1,其餘元素為0的方陣集合。
# Import the required library import torch # Create a 2D tensor with 1's on the diagonal and 0's elsewhere t = torch.eye(4) # print the computed tensor print(t) # other way to do above task t1 = torch.eye(4,4) print(t1) t2 = torch.eye(3,4) print(t2) t3 = torch.eye(4,3) print(t3)
輸出
tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.]]) tensor([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.], [0., 0., 0.]])
示例2
# Create tensor with requires_grad true # Import the required library import torch # Create a 2D tensor with 1's on the diagonal and 0's elsewhere t = torch.eye(5, requires_grad = True) # print the above computed tensor print(t) # other way to do above task t1 = torch.eye(4,5, requires_grad = True) print(t1)
輸出
tensor([[1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]], requires_grad=True) tensor([[1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.]], requires_grad=True)
廣告