def PearsonCorrelationTF(x, y, prefix='pearson'):
'''Create a TF network that calculates the Pearson Correlation on two input
vectors. Returns a scalar tensor with the correlation [-1:1].'''
with tf.name_scope(prefix):
n = tf.to_float(tf.shape(x)[0])
x_sum = tf.reduce_sum(x)
y_sum = tf.reduce_sum(y)
xy_sum = tf.reduce_sum(tf.multiply(x, y))
x2_sum = tf.reduce_sum(tf.multiply(x, x))
y2_sum = tf.reduce_sum(tf.multiply(y, y))
r_num = tf.subtract(tf.multiply(n, xy_sum), tf.multiply(x_sum, y_sum))
r_den_x = tf.sqrt(tf.subtract(tf.multiply(n, x2_sum), tf.multiply(x_sum, x_sum)))
r_den_y = tf.sqrt(tf.subtract(tf.multiply(n, y2_sum), tf.multiply(y_sum, y_sum)))
r = tf.div(r_num, tf.multiply(r_den_x, r_den_y), name='r')
return r
评论列表
文章目录