【问题标题】:Cheap way to turn covariance matrix in tensorflow to correlation matrix将张量流中的协方差矩阵转换为相关矩阵的廉价方法
【发布时间】:2022-01-24 14:18:49
【问题描述】:

我有 N 个协方差矩阵的形状为 [N,d,d] 的张量,我想将它们转换为相关矩阵。 tensorflow / keras 有什么便宜的实现吗?

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    您已经有了相关矩阵,因此您只需将该矩阵的每个元素除以相应的标准差乘积即可。 这些标准偏差出现在矩阵的对角线上,并且可以通过一些矩阵乘法有效地检索(更多关于数学on this wikipedia page):

    import tensorflow as tf
    
    def to_corr(cov):
        d_inv = tf.linalg.diag(1/tf.sqrt(tf.abs(tf.linalg.diag_part(cov))))
        corr = d_inv @ cov @ d_inv
        return corr
    

    完整性检查:

    import tensorflow_probability as tfp
    
    x = tf.random.normal(shape=(3,5,3))
    cov_matrix = tfp.stats.covariance(x, sample_axis=0, event_axis=-1)
    tf.debugging.assert_near(to_corr(cov_matrix),tfp.stats.correlation(x, sample_axis=0, event_axis=-1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 2019-04-10
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 2019-03-26
      相关资源
      最近更新 更多