Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get covariance matrix in tensorflow?

How could I get covariance matrix in tensorflow? Like numpy.cov() in numpy.

For example, I want to get covariance matrix of tensor A, now I have to use numpy instead

    A = sess.run(model.A, feed)
    cov = np.cov(np.transpose(A))

Is there anyway to get cov by tensorflow instead of numpy?

It is differnet from the problem how to compute covariance in tensorflow, where their problem is to compute covariance for two vector, while mine is to compute covariance matrix of a matrix(a 2D tensor) effectively using tensorflow API

like image 205
M.Zhu Avatar asked Dec 08 '17 07:12

M.Zhu


People also ask

How do you calculate covariance in a Jupyter notebook?

To compute the covariance between two variables we simply compute the dot product of the variance vectors and divide by the sample size.


1 Answers

This is months late but anyway posting for completeness.

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)
like image 154
Batta Avatar answered Sep 22 '22 01:09

Batta