【发布时间】:2017-07-05 13:03:55
【问题描述】:
我有一个与在 Linux 上的 TensorFlow python 接口版本 1.1.0 中计算矩阵逆相关的问题。我现在要做的是,我有一个输入向量为tensorflow.float64,比如S 和一个值V。我将向量S 扩充为 形式的多项式形式,并希望对V 进行回归。我选择自己计算线性回归,而不是使用来自 tensorflow 的基础设施,其中回归以 进行。问题出现在 步骤中,在该步骤中,原始矩阵的逆乘法不会给出恒等式。但是,如果我将 作为包含与预处理输入相同的值的常量矩阵提供,则结果实际上是其自身的倒数。
下面的代码是带有参数control=True 的可运行版本,用于打开逆行为正确的常量输入矩阵版本。运行程序会输出三个矩阵,原始矩阵,tf.matrix_inverse 的“逆”矩阵,以及“逆”与原始矩阵相乘以恢复身份。 control=False 给出与control=True 运行相同的原始矩阵,但是,恢复的“身份”与control=False 不正确。我怀疑预处理过程中的数据流有问题。但是,受限于我使用 TensorFlow 的经验,我无法发现它。您介意为什么tf.matrix_inverse 不能按预期工作吗?
import tensorflow as tf
import pprint
def matrixInverse( control=False ):
'''Compute inverse of a matrix.
Parameters
----------
control : bool
whether to use control group or not.
'''
X = tf.constant( [ [100. , 100., 100., 100.],
[ 101.75497118 , 92.84824314 , 95.09528336 , 103.24955959],
[ 92.33287485 , 95.86868862 , 84.70664178 , 107.9505686 ],
[ 85.86109085 , 99.05621029 , 94.24396596 , 119.60257907] ], dtype=tf.float64 )
# extract input X
s = tf.slice( X, [ 2, 0 ], [ 1, 4 ])
s = tf.squeeze(s)
s1 = tf.multiply( tf.ones( 4, dtype=tf.float64 ), s )
s2 = tf.multiply( s, s )
s3 = tf.multiply( tf.multiply( s, s ), s )
A = tf.concat( [ tf.ones( 4, dtype=tf.float64 ), s1, s2, s3 ], 0 )
A = tf.reshape( A, [ 4, 4 ] )
# filter only the first element in the selected row
itm = tf.constant( [ True, False, False, False ], dtype=tf.bool )
A = tf.boolean_mask( tf.transpose(A), itm )
if control:
ATA = tf.constant([[ 1.00000000e+00, 9.23328748e+01, 8.52535978e+03, 7.87170977e+05],
[ 9.23328748e+01, 8.52535978e+03, 7.87170977e+05, 7.26817593e+07],
[ 8.52535978e+03, 7.87170977e+05, 7.26817593e+07, 6.71091579e+09],
[ 7.87170977e+05, 7.26817593e+07, 6.71091579e+09, 6.19638148e+11]], dtype = tf.float64)
else:
ATA = tf.matmul( tf.transpose( A ), A )
inverseATA = tf.matrix_inverse( ATA )
sess = tf.Session()
pprint.pprint( sess.run( [ ATA, inverseATA, tf.matmul( ATA, inverseATA ) ] ) )
【问题讨论】:
-
我删除了我的答案,无法重现我昨天得到的内容。但是发现A*AT的行列式非常接近于零,所以逆不存在。不一致是因为这个。
-
@vijaym 感谢您的评论。是的,我终于在您的回答之后找到了相同的结果。根本原因应该是原矩阵的可逆性。
标签: python python-2.7 tensorflow matrix-inverse