torch.sparse_coo_tensor¶
- torch.sparse_coo_tensor(indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) Tensor¶
使用指定的
indices處的值,構造一個 COO (座標) 格式的稀疏張量。注意
當
is_coalesced未指定或為None時,此函式返回一個 非合併的張量。注意
如果未指定
device引數,則給定的values和 indices 張量(s) 的裝置必須匹配。但是,如果指定了該引數,則輸入張量將被轉換到指定的裝置,並由此決定構造的稀疏張量的裝置。- 引數
indices (array_like) – 張量的初始資料。可以是列表、元組、NumPy
ndarray、標量及其他型別。內部將轉換為torch.LongTensor。索引是矩陣中非零值的座標,因此應為二維,其中第一維表示張量的維度數,第二維表示非零值的數量。values (array_like) – 張量的初始值。可以是列表、元組、NumPy
ndarray、標量及其他型別。size (list, tuple, 或
torch.Size, 可選) – 稀疏張量的大小。如果未提供,則將推斷為足以容納所有非零元素的最小尺寸。
- 關鍵字引數
dtype (
torch.dtype, 可選) – 返回張量所需的資料型別。預設值: 如果為 None,則從values推斷資料型別。device (
torch.device, 可選) – 返回張量所需的裝置。預設值: 如果為 None,則使用預設張量型別的當前裝置(參見torch.set_default_device())。對於 CPU 張量型別,device將是 CPU;對於 CUDA 張量型別,將是當前的 CUDA 裝置。pin_memory (bool, 可選) – 如果設定,返回的張量將分配在鎖頁記憶體中。僅適用於 CPU 張量。預設值:
False。requires_grad (bool, 可選) – 如果自動微分應對返回張量上的操作進行記錄。預設值:
False。check_invariants (bool, 可選) – 是否檢查稀疏張量不變性。預設值: 由
torch.sparse.check_sparse_tensor_invariants.is_enabled()返回,初始值為 False。is_coalesced (bool, 可選) – 當為 ``True`` 時,呼叫者負責提供對應於合併張量的張量索引。如果
check_invariants標誌為 False,則在不滿足先決條件時不會引發錯誤,這將導致靜默的錯誤結果。要強制合併,請在結果張量上使用coalesce()。預設值: None:除了微不足道的情況(例如 nnz < 2)外,結果張量的 is_coalesced 設定為False`。
示例
>>> i = torch.tensor([[0, 1, 1], ... [2, 0, 2]]) >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) >>> torch.sparse_coo_tensor(i, v, [2, 4]) tensor(indices=tensor([[0, 1, 1], [2, 0, 2]]), values=tensor([3., 4., 5.]), size=(2, 4), nnz=3, layout=torch.sparse_coo) >>> torch.sparse_coo_tensor(i, v) # Shape inference tensor(indices=tensor([[0, 1, 1], [2, 0, 2]]), values=tensor([3., 4., 5.]), size=(2, 3), nnz=3, layout=torch.sparse_coo) >>> torch.sparse_coo_tensor(i, v, [2, 4], ... dtype=torch.float64, ... device=torch.device('cuda:0')) tensor(indices=tensor([[0, 1, 1], [2, 0, 2]]), values=tensor([3., 4., 5.]), device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, layout=torch.sparse_coo) # Create an empty sparse tensor with the following invariants: # 1. sparse_dim + dense_dim = len(SparseTensor.shape) # 2. SparseTensor._indices().shape = (sparse_dim, nnz) # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) # # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) tensor(indices=tensor([], size=(1, 0)), values=tensor([], size=(0,)), size=(1,), nnz=0, layout=torch.sparse_coo) # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and # sparse_dim = 1 >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) tensor(indices=tensor([], size=(1, 0)), values=tensor([], size=(0, 2)), size=(1, 2), nnz=0, layout=torch.sparse_coo)