PyTorch – torch.linalg.cond()
為了計算矩陣相對於矩陣範數的條件數,我們可以使用 **torch.linalg.cond()** 方法。它返回一個包含計算出的條件數的新張量。它接受一個矩陣、一批矩陣以及一批矩陣的批次作為輸入。矩陣是一個二維 torch 張量。它支援 **float、double、cfloat** 和 **cdouble** 資料型別。
語法
torch.linalg.cond(M, p=None)
引數
M – 一個矩陣或一批矩陣。
p – 用於計算條件數的矩陣範數型別。預設矩陣範數是 2-範數。
它返回一個實值條件數張量。
步驟
我們可以使用以下步驟來計算矩陣的條件數:
匯入所需的庫。在以下所有示例中,所需的 Python 庫是 **torch**。確保你已經安裝了它。
import torch
定義一個矩陣。這裡,我們定義一個大小為 3×4 的隨機數矩陣(二維張量)。
M = torch.randn(3,4)
使用 **torch.linalg.cond(A, p = None)** 計算矩陣的條件數。A 是一個矩陣或一批矩陣。p 是矩陣範數型別。可以選擇將此值賦值給一個新變數。
Mcond = torch.linalg.cond(M)
列印包含條件數的計算張量。
print("Norm:", Mcond)示例 1
下面的程式演示瞭如何計算相對於預設矩陣範數的矩陣條件數。預設矩陣範數是 2-範數。
# Python program to compute the condition number of a matrix
# import required library
import torch
# define a matrix of size 3x4
M = torch.randn(3,4)
print("Matrix M:
", M)
# compute the condition number of above defined matrix
Mcond = torch.linalg.cond(M)
# print condition number of the matrix
print("Condition Number:
", Mcond)輸出
它將產生以下輸出:
Matrix M: tensor([[-0.3241, 1.6410, 1.5067, -1.4944], [-0.5977, -0.4599, 0.6367, 0.1683], [ 1.4590, 0.9267, -0.2186, -0.5963]]) Condition Number: tensor(7.4035)
示例 2
在這個程式中,我們計算相對於不同矩陣範數的條件數。
import torch
# define a matrix of size 3x3
M = torch.randn(3,3)
print("Matrix:
", M)
print("
Condition Number with different Norms:")
print(torch.linalg.cond(M))
print(torch.linalg.cond(M, p = 'fro'))
print(torch.linalg.cond(M, p = 'nuc'))
print(torch.linalg.cond(M, p = 1))
print(torch.linalg.cond(M, p = -1))
print(torch.linalg.cond(M, p = 2))
print(torch.linalg.cond(M, p = -2))
print(torch.linalg.cond(M, p = float('inf')))
print(torch.linalg.cond(M, p = float('-inf')))輸出
它將產生以下輸出:
Matrix: tensor([[-0.0328, 0.1970, -0.1466], [ 0.1721, 0.0765, 1.1714], [ 1.1040, 1.7493, 0.8331]]) Condition Number with different Norms: tensor(21.0871) tensor(23.1940) tensor(36.1807) tensor(27.7410) tensor(1.4686) tensor(21.0871) tensor(0.0474) tensor(37.5561) tensor(0.7646)
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP