首页 文章

如何在张量流中得到协方差矩阵?

提问于
浏览
4

如何在张量流中得到协方差矩阵?就像 numpy 中的 numpy.cov() 一样 .

例如,我想获得张量 A 的协方差矩阵,现在我必须使用numpy代替

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

无论如何得到张量流而不是numpy的 cov

它与问题how to compute covariance in tensorflow不同,他们的问题是计算两个向量的协方差,而我的是使用tensorflow API有效地计算矩阵的协方差矩阵(2D张量)

3 回答

  • 0

    这是几个月的晚了,但无论如何发布完整性 .

    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)
    
  • 7

    相当于 np.cov(data)

    import tensorflow as tf
    import numpy as np
    
    data = np.array([[1., 4, 2], [5, 6, 24], [15, 1, 5], [7,3,8], [9,4,7]])
    
    def tf_conv(x):
        x = x - tf.expand_dims(tf.reduce_mean(x, axis=1), 1)
        fact = tf.cast(tf.shape(x)[1] - 1, tf.float32)
        return tf.matmul(x, tf.conj(tf.transpose(x))) / fact
    
    with tf.Session() as sess:
        print(sess.run(tf_cov(tf.constant(data, dtype=tf.float32))))
    
  • 0

    回答自2019年.Tensorflow概率现在支持毫不费力的相关性和协方差 .

    https://www.tensorflow.org/probability/api_docs/python/tfp/stats/covariance

    x = tf.random_normal(shape=(100, 2, 3))
    y = tf.random_normal(shape=(100, 2, 3))
    
    # cov[i, j] is the sample covariance between x[:, i, j] and y[:, i, j].
    cov = tfp.stats.covariance(x, y, sample_axis=0, event_axis=None)
    
    # cov_matrix[i, m, n] is the sample covariance of x[:, i, m] and y[:, i, n]
    cov_matrix = tfp.stats.covariance(x, y, sample_axis=0, event_axis=-1)
    

相关问题