【问题标题】:how to get covariance matrix in tensorflow?如何在张量流中获得协方差矩阵?
【发布时间】:2017-12-08 07:44:35
【问题描述】:

如何在张量流中获得协方差矩阵?喜欢numpy.cov() 中的numpy

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

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

有没有办法通过 tensorflow 而不是 numpy 获得cov

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

【问题讨论】:

标签: python machine-learning tensorflow


【解决方案1】:

这已经晚了几个月,但为了完整起见还是发布了。

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)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      相当于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))))
      

      【讨论】:

        【解决方案4】:

        跟进@Souradeep Nanda,如果您尝试使用它,您会发现 tfp.stats.covariance 仅具有 np.cov(..., rowvar=False) 的值(按元素),因此您将计算后必须乘以 2。 (这适用于 v0.11.1,在 2x2 矩阵上测试)。

        对于 3x3 矩阵,这些值不相等,因此您可能希望继续使用 np.cov。如果您没有将 rowvar=False 用于 np.cov() 版本,这也适用。我不知道为什么。

        【讨论】:

          【解决方案5】:

          我们可以使用tfp aka tensorflow-probability 来计算cov矩阵:

          import tensorflow-probability as tfp
          
          x=tf.random.normal(shape=(3,3))
          cov = tfp.stats.covariance(x)
          ## which are same as:
          np_cov = np.cov(tf.transpose(x_zero),bias=True)
          

          【讨论】:

            猜你喜欢
            • 2016-05-03
            • 2022-01-21
            • 1970-01-01
            • 2018-01-20
            • 1970-01-01
            • 2022-01-04
            • 2011-05-23
            • 1970-01-01
            • 2012-12-09
            相关资源
            最近更新 更多