I have a vector of volatilities and a matrix of correlations
volatilities = tf.constant([0.2, 0.4, 0.6], dtype=tf.float32)
correlations = tf.constant([[1, 0.25, 0.5], [0.25, 1, 0.3], [0.5, 0.3, 1]], dtype=tf.float32)
I want to create a covariance matrix using these values
covariance = tf.tensordot(volatilities, volatilities, axes=0) * correlations
So far, so good. Now I'm using this inside a batched training process, and the shapes of my volatilities and correlations are (batch_size, 3)
and (batch_size, 3, 3)
, respectively. I spent a lot of time trying to figure out how to get the covariance matrix. I tried first to obtain a volatility matrix of shape (batch_size, 3, 3)
, and then scalar multiplying with the correlations, but I did not succeed in getting the volatility matrix. The closest I get is a (3, 3)
tensor by doing this:
volatility_matrix = tf.tensordot(volatilities, volatilities, axes=[[0], [0]])
How do I computationally efficiently obtain my correlation matrix with the batch_size
dimension?
CodePudding user response:
As the post referred to by @Lescurel mentioned, this problem can be solved by using tf.einsum
:
volatility_matrix = tf.einsum("ij,ik->ijk", volas, volas)
solves the problem of obtaining the volatility matrix. From there, it's just scalar multiplication along the second axis. Specifically, to then get the covariance matrix, I did
covariance_matrix = tf.linalg.matmul(volatility_matrix, correlation_matrix)
CodePudding user response: