如何检查矩阵在tensorflow中是否可逆?

How to check if a matrix is invertible in tensorflow?

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

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

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

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

Efficient & pythonic check for singular matrix, you can check the condition number. Unfortunately, this is not currently implemented in TensorFlow as such, but it is not difficult to emulate the basic implementation of 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]