M.Z*_*Zhu 4 python machine-learning tensorflow
如何在张量流中得到协方差矩阵?就像numpy.cov()在numpy.
例如,我想获得张量的协方差矩阵A,现在我必须使用numpy
A = sess.run(model.A, feed)
cov = np.cov(np.transpose(A))
Run Code Online (Sandbox Code Playgroud)
无论如何,cov通过tensorflow而不是numpy?
它与如何计算张量流中的协方差的问题不同,其中它们的问题是计算两个向量的协方差,而我的是使用tensorflow API有效地计算矩阵的协方差矩阵(2D张量)
这是几个月的晚了,但无论如何发布完整性.
import numpy as np
import tensorflow as tf
def tf_cov(x):
mean_x = tf.reduce_mean(x, axis=0, keep_dims=True)
mx = tf.matmul(tf.transpose(mean_x), mean_x)
vx = tf.matmul(tf.transpose(x), x)/tf.cast(tf.shape(x)[0], tf.float32)
cov_xx = vx - mx
return cov_xx
data = np.array([[1., 4, 2], [5, 6, 24], [15, 1, 5], [7,3,8], [9,4,7]])
with tf.Session() as sess:
print(sess.run(tf_cov(tf.constant(data, dtype=tf.float32))))
## validating with numpy solution
pc = np.cov(data.T, bias=True)
print(pc)
Run Code Online (Sandbox Code Playgroud)