Skip to main content
 首页 » 编程设计

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

2024年09月03日26zdz8207

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

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

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

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

请您参考如下方法:

如 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]