首页 文章

Tensorflow中的稀疏矩阵三角形求解?

提问于
浏览
1

在Tensorflow中是否存在使用稀疏三角矩阵求解Ax = b的实现? (对应于tf.matrix_triangular_solve())

AFAIK,如果我们有A,例如,作为具有稀疏矩阵表示的下三角矩阵,我们需要使用tf.sparse_to_dense()将其转换为密集矩阵 .

但是,如果A具有非常大的维度,例如16416x16416,并且非常稀疏的条目,例如0.018%(大约45216个非零),则需要大量的存储器 .

我认为如果我们可以在Tensorflow中利用稀疏矩阵求解器(例如带有带状结构的矩阵)将会非常有用 .

对不起,如果我的问题不相关 . 例如,如果有任何解决方案,我将不胜感激任何帮助 .

谢谢 .

2 回答

  • 0

    我有同样的问题,我为它创建了一个自定义操作 . 只要你不想计算渐变到A和A仍然是固定的,那么这段代码应该有所帮助:

    import tensorflow as tf
    import numpy as np
    from scipy.sparse import linalg as sla
    import scipy
    
    lu = sla.splu(A)
    
    # Define custom py_func which takes also a grad op as argument:
    def py_func(func, inp, Tout, stateful=True, name=None, grad=None):
    
        rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))
    
        tf.RegisterGradient(rnd_name)(grad)
        g = tf.get_default_graph()
        with g.gradient_override_map({"PyFunc": rnd_name}):
            return tf.py_func(func, inp, Tout, stateful=stateful, name=name)
    
    
    def sparse_solve(x, lu, dtype=tf.float64, name=None):
    
        with tf.name_scope(name, 'SparseSolve', [x]) as name:
            solve_x = py_func(lu.solve,
                            [x],
                            [dtype],
                            name=name,
                            grad=_SparseSolveGrad(dtype, lu))
            return solve_x[0]
    
    class _SparseSolveGrad:
        def __init__(self, dtype, lu):
            self.dtype = dtype
            self.lu = lu
    
        def __call__(self, op, grad):
            x = op.inputs[0]
            y = tf.conj(tf.py_func(self.lu.solve, [tf.conj(grad)], self.dtype))
            return y
    

    该解决方案基于我在https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342找到的代码

    至少对我来说,解决方案非常快 . 如果您发现错误(例如在渐变计算中),请告诉我

  • 1

    TF中有very little support for sparse tensors . 因此,您目前唯一的方法(如您所确定的)是tf.sparse_to_dense()

相关问题