如何计算张量流的协方差?

编程入门 行业动态 更新时间:2024-10-23 06:31:57
本文介绍了如何计算张量流的协方差?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个问题,我不知道如何计算两个张量的协方差。我已经尝试过 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

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)

更多推荐

如何计算张量流的协方差?

本文发布于:2023-11-25 22:41:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631640.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:协方差   张量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!