2017-08-25 4 views

Répondre

1

Vous pouvez utiliser la définition de la covariance de deux variables aléatoires X et Y avec les valeurs attendues x0 et y0:

cov_xx = 1/(N-1) * Sum_i ((x_i - x0)^2)

cov_yy = 1/(N-1) * Sum_i ((y_i - y0)^2)

cov_xy = 1/(N-1) * Sum_i ((x_i - x0) * (y_i - y0))

Le point crucial est pour estimer x0 et y0 son e, puisque normalement vous ne connaissez pas la distribution de probabilité. Dans de nombreux cas, la moyenne des x_i ou y_i est estimée à x_0 ou y_0, respectivement, c'est-à-dire que la distribution est estimée être uniforme.

Ensuite, vous pouvez calculer les éléments de la matrice de covariance comme suit:

import tensorflow as tf 

x = tf.constant([1, 4, 2, 5, 6, 24, 15], dtype=tf.float64) 
y = tf.constant([8, 5, 4, 6, 2, 1, 1], dtype=tf.float64) 

cov_xx = 1/(tf.shape(x)[0] - 1) * tf.reduce_sum((x - tf.reduce_mean(x))**2) 
cov_yy = 1/(tf.shape(x)[0] - 1) * tf.reduce_sum((y - tf.reduce_mean(y))**2) 
cov_xy = 1/(tf.shape(x)[0] - 1) * tf.reduce_sum((x - tf.reduce_mean(x)) * (y - tf.reduce_mean(y))) 

with tf.Session() as sess: 
    sess.run([cov_xx, cov_yy, cov_xy]) 
    print(cov_xx.eval(), cov_yy.eval(), cov_xy.eval()) 

Bien sûr, si vous avez besoin de la covariance sous une forme matricielle, vous pouvez modifier la dernière partie comme suit:

with tf.Session() as sess: 
    sess.run([cov_xx, cov_yy, cov_xy]) 
    print(cov_xx.eval(), cov_yy.eval(), cov_xy.eval()) 
    cov = tf.constant([[cov_xx.eval(), cov_xy.eval()], [cov_xy.eval(), 
     cov_yy.eval()]]) 
    print(cov.eval()) 

Pour vérifier les éléments de la façon dont tensorflow, vous pouvez vérifier avec numpy:

import numpy as np 

x = np.array([1,4,2,5,6, 24, 15], dtype=float) 
y = np.array([8,5,4,6,2,1,1], dtype=float) 

pc = np.cov(x,y) 
print(pc) 
0

La fonction contrib.metrics.streaming_covariance crée une opération update_op, qui met à jour les variables sous-jacentes et renvoie la covariance mise à jour. Donc, votre code devrait être:

x = tf.constant([1, 4, 2, 5, 6, 24, 15], dtype=tf.float32) 
y = tf.constant([8, 5, 4, 6, 2, 1, 1], dtype=tf.float32) 

z, op = tf.contrib.metrics.streaming_covariance(x,y) 

with tf.Session() as sess: 
    tf.global_variables_initializer().run() 
    tf.local_variables_initializer().run() 

    sess.run([op]) 
    print(sess.run([z])) 

#Output 
[-17.142859]