我有以下代码段。许多Sigma矩阵是由神经网络生成的,这些矩阵必须是正定的。所以在调试函数中检查。
奇怪的是,Sigma2没有给出一个*** LinAlgError:Matrix不是正确的错误,Sigma就是这样。要完成,前1499次迭代一切顺利。
但是np.sum(np.abs(Sigma-Sigma2))给出的值为19687.622918061788。因此,在Tensorflow中构建的Sigma似乎与Numpy中生成的Sigma2具有不同的值。这怎么可能?
# Because there is no tensorflow equivalent for np.eye()
identity = tf.Variable(tf.convert_to_tensor(np.eye(mu_shape[-1].value), dtype=tf.float32))
Sigma = tf.batch_matmul(L,tf.matrix_transpose(L)) + 1e-4*identity
# Check positive definite
def _debug_print_func(Sigma,L):
try:
C = np.linalg.cholesky(Sigma)
except np.linalg.LinAlgError:
Sigma2 = np.matmul(L,np.transpose(L,axes=[0,1,3,2]))+1e-4*np.eye(4))
print 'LinAlgError'
# Sigma different from Sigma2??
pdb.set_trace()
return False
debug_print_op = tf.py_func(_debug_print_func, [Sigma,L], [tf.bool])
with tf.control_dependencies(debug_print_op):
Sigma = tf.identity(Sigma, name='out')
编辑: 也是一个小数字例子
在调试函数中我计算
W=np.matmul(L[0,0,:,:],L[0,0,:,:].T)+1e-4*np.eye(4)
然后我做
Sigma[0,0,:,:]-W
Sigma [0,0,:,:] - W给出
array([[ -2.39243686e-05, -2.29620725e-05, 1.46458477e-05, 2.68967569e-05],
[ -2.29620725e-05, -3.72494698e-05, 2.18125388e-05, 3.86031806e-05],
[ 1.46458477e-05, 2.18125388e-05, -3.83383453e-05, 2.45112851e-05],
[ 2.68967569e-05, 3.86031806e-05, 2.45112851e-05, -5.60631990e-05]])
所以Numpy和TensorFlow之间的所有元素似乎都有1e-5的顺序。这似乎使正定与否之间存在差异。
这是TensorFlow中的错误还是有办法解决这个问题?