将张量流中的协方差矩阵转换为相关矩阵的廉价方法

Cheap way to turn covariance matrix in tensorflow to correlation matrix

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

您已经有了相关矩阵,所以您需要做的就是将该矩阵的每个元素除以适当的标准差乘积。 这些标准偏差存在于矩阵的对角线上,可以通过几次矩阵乘法有效地检索(更多关于数学 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))