我有一个问题,我不知道如何计算两个张量的协方差。我已经尝试过 contrib.metrics.streaming_covariance 。但是总是返回 0 。必须存在一些错误。
I have a problem that I don't know how to compute the covariance of two tensor. I have tried the contrib.metrics.streaming_covariance. But is always returns 0. There must be some errors.
推荐答案您可以使用两个随机变量 X的协方差的定义。 和 Y 的期望值为 x0 和 y0 :
You could use the definition of the covariance of two random variables X and Y with the expected values x0 and y0:
cov_xx = 1 /(N-1)* Sum_i((x_i-x0)^ 2)
cov_yy = 1 /(N-1)* Sum_i((y_i-y0)^ 2)
cov_xy = 1 /(N-1)* Sum_i((x_i-x0)*(y_i-y0))
关键点是估计 x0 和 y0 $在这里,因为您通常不知道概率分布。在许多情况下, x_i 或 y_i 的平均值估计为 x_0 或 y_0 ,即分布估计是均匀的。
The crucial point is to estimate x0 and y0 here, since you normally do not know the probability distribution. In many cases, the mean of the x_i or y_i is estimated to be x_0 or y_0, respectively, i.e. the distribution is estimated to be uniform.
然后您可以如下计算协方差矩阵的元素:
Then you can compute the elements of the covariance matrix as follows:
import tensorflow as tf x = tf.constant([1, 4, 2, 5, 6, 24, 15], dtype=tf.float64) y = tf.constant([8, 5, 4, 6, 2, 1, 1], dtype=tf.float64) cov_xx = 1 / (tf.shape(x)[0] - 1) * tf.reduce_sum((x - tf.reduce_mean(x))**2) cov_yy = 1 / (tf.shape(x)[0] - 1) * tf.reduce_sum((y - tf.reduce_mean(y))**2) cov_xy = 1 / (tf.shape(x)[0] - 1) * tf.reduce_sum((x - tf.reduce_mean(x)) * (y - tf.reduce_mean(y))) with tf.Session() as sess: sess.run([cov_xx, cov_yy, cov_xy]) print(cov_xx.eval(), cov_yy.eval(), cov_xy.eval())当然,如果您需要矩阵形式,您可以修改最后一部分,如下所示:
Of course, if you need the covariance in a matrix form, you can modify the last part as follows:
with tf.Session() as sess: sess.run([cov_xx, cov_yy, cov_xy]) print(cov_xx.eval(), cov_yy.eval(), cov_xy.eval()) cov = tf.constant([[cov_xx.eval(), cov_xy.eval()], [cov_xy.eval(), cov_yy.eval()]]) print(cov.eval())要验证TensorFlow方式的元素,可以使用numpy进行检查:
To verify the elements of the TensorFlow way, you can check with numpy:
import numpy as np x = np.array([1,4,2,5,6, 24, 15], dtype=float) y = np.array([8,5,4,6,2,1,1], dtype=float) pc = np.cov(x,y) print(pc)更多推荐
如何计算张量流的协方差?
发布评论