Skip to content
Advertisement

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

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement