簡體   English   中英

從 coo_matrix 創建塊矩陣

[英]Creating block matrix from coo_matrix

我有一個大小為 nxn 的 torch.sparse_coo。

如何將其擴展為 ndxnd torch.sparse_coo 矩陣,其中每個條目都被相同值的 dxd 矩陣替換?

我想在不轉換成密集的情況下這樣做。

謝謝!

我假設您正在嘗試平鋪它而不是擴展維度,盡管從問題中還不清楚。 通過操縱底層索引和數據張量,這將很容易做到。

import itertools
import torch

def tile_sparse_tensor(sparse_tensor, d):
    
    # Get shape and number of non-zero values in the sparse tensor
    m, n = sparse_tensor.shape
    nnz = sparse_tensor.values().size()[0]
    
    # If the tensor is empty, return an empty tensor
    if nnz == 0:
        return torch.sparse_coo_tensor(
            size=(d * m, d * n)
        )
    
    # Create an empty index tensor to fill
    stacked_index = torch.empty(
        (2, nnz * d * d),
        dtype=int
    )
    
    # Construct the tiled indices
    for n_iter, (i, j) in enumerate(itertools.product(range(d), range(d))):
        
        offset = nnz * n_iter
        
        # Rows & columns, modified with the new block coordinates
        stacked_index[0, offset:offset + nnz] = sparse_tensor.indices()[0, :] + i * m
        stacked_index[1, offset:offset + nnz] = sparse_tensor.indices()[1, :] + j * n
        
    return torch.sparse_coo_tensor(
        stacked_index,
        torch.tile(sparse_tensor.values(), (d * d,))
    ).coalesce()

這應該通過構造一個適當大小的空張量並填充索引,然后只是平鋪數據來解決二維張量的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM