PyTorch 常用函式備忘
阿新 • • 發佈:2021-12-02
PyTorch 常用函式備忘
# basic operation x: torch.Tensor x.shape -> torch.Size x.ndim -> int # 軸數 x.T x.numel() -> int # total size x.reshape(*shape) -> Tensor x.sum(), x.mean() x.sum(axis=int) # 沿某維求和,會將軸數減少1 x.sum(axis=int, keepdims=True) # 沿某維求和,將該軸長度保留為1 # x.sum() == x.sum(axis=[0, 1]) # x.mean() == x.sum()/x.numel() x.cumsum(axis=int) # 沿某個軸計算x元素的累積總和,不會沿任何軸降低輸入張量的維度,axis引數必須指定 x[slice] # same as numpy len(x) == x.shape[0] x.clone() torch.norm(x) -> Tensor0D # L2範數,可用於向量和矩陣(弗羅⻉尼烏斯範數) torch.abs(x).sum() # L1範數 # constructor torch.arange(int) -> Tensor torch.zeros(tuple) -> Tensor torch.ones(tuple) -> Tensor torch.randn(*shape) -> Tensor # 每個元素都從均值為0、標準差為1的標準高斯(正態)分佈中隨機取樣 torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) # from list torch.tensor(numpy.ndarray) <=> x.numpy() torch.zeros_like(Tensor) -> Tensor # arithmetical operation # Y += X better than Y = Y+X a: torch.Tensor b: torch.Tensor a+b, a-b, a*b, a/b, a**b # a*b 哈達瑪積,對應位相乘 a==b, a<b, a>b torch.exp(a) # matrix operation a: torch.Tensor b: torch.Tensor torch.cat(tuple[Tensor], dim=int) # 按dim維連線各矩陣 torch.dot(Tensor1D, Tensor1D) -> Tensor0D # 僅支援1D Tensor,輸出0D Tensor torch.mv(Tensor2D, Tensor1D) -> Tensor1D torch.mm(Tensor2D, Tensor2D) -> Tensor2D