简体   繁体   English

从 coo_matrix 创建块矩阵

[英]Creating block matrix from coo_matrix

I have a torch.sparse_coo of size nxn.我有一个大小为 nxn 的 torch.sparse_coo。

How can I expand it into a ndxnd torch.sparse_coo matrix, where each entry is replaced by a dxd matrix of the same value?如何将其扩展为 ndxnd torch.sparse_coo 矩阵,其中每个条目都被相同值的 dxd 矩阵替换?

I would like to do this without ever converting into dense.我想在不转换成密集的情况下这样做。

Thank you!谢谢!

I assume you're trying to tile it and not expand the dimensionality, although it's a bit unclear from the question.我假设您正在尝试平铺它而不是扩展维度,尽管从问题中还不清楚。 It'll be easy enough to do by manipulating the underlying indices and data tensors.通过操纵底层索引和数据张量,这将很容易做到。

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()

This should do the trick for a 2D tensor by constructing an empty tensor of appropriate size and filling out the indices, then just tiling the data.这应该通过构造一个适当大小的空张量并填充索引,然后只是平铺数据来解决二维张量的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM