【问题标题】:How to check if a matrix is invertible in tensorflow?如何检查矩阵在张量流中是否可逆?
【发布时间】:2019-07-17 10:04:58
【问题描述】:

在我的 Tensorflow 图中,如果矩阵是可逆的,我想对其进行反转。如果它不可逆,那,我想做点别的。

我找不到任何方法来检查矩阵是否可逆以便执行以下操作:

is_invertible = tf.is_invertible(mat)
tf.cond(is_invertible, f1, f2)

Tensorflow 中有 is_invertible 函数这样的东西吗? 当我尝试反转不可逆矩阵时,我还考虑过使用 Tensorflow 引发(虽然不是每次)InvalidArgumentError 的事实,但我无法利用这一点。

【问题讨论】:

    标签: python tensorflow linear-algebra inversion


    【解决方案1】:

    按照Efficient & pythonic check for singular matrix的建议,可以查看条件号。不幸的是,目前TensorFlow中并没有这样实现,但是模拟np.linalg.cond的基本实现并不难:

    import math
    import tensorflow as tf
    
    # Based on np.linalg.cond(x, p=None)
    def tf_cond(x):
        x = tf.convert_to_tensor(x)
        s = tf.linalg.svd(x, compute_uv=False)
        r = s[..., 0] / s[..., -1]
        # Replace NaNs in r with infinite unless there were NaNs before
        x_nan = tf.reduce_any(tf.is_nan(x), axis=(-2, -1))
        r_nan = tf.is_nan(r)
        r_inf = tf.fill(tf.shape(r), tf.constant(math.inf, r.dtype))
        tf.where(x_nan, r, tf.where(r_nan, r_inf, r))
        return r
    
    def is_invertible(x, epsilon=1e-6):  # Epsilon may be smaller with tf.float64
        x = tf.convert_to_tensor(x)
        eps_inv = tf.cast(1 / epsilon, x.dtype)
        x_cond = tf_cond(x)
        return tf.is_finite(x_cond) & (x_cond < eps_inv)
    
    m = [
        # Invertible matrix
        [[1., 2., 3.],
         [6., 5., 4.],
         [7., 7., 8.]],
        # Non-invertible matrix
        [[1., 2., 3.],
         [6., 5., 4.],
         [7., 7., 7.]],
    ]
    with tf.Graph().as_default(), tf.Session() as sess:
        print(sess.run(is_invertible(m)))
        # [ True False]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 2017-04-18
      • 2019-03-09
      • 2018-05-24
      • 2018-12-09
      相关资源
      最近更新 更多