按照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]