A Function to Caculate Pearson Value in TensorFlow

The function is:

import tensorflow as tf
import numpy as np

def pearson(xx,yy):
    '''
    x = np.array([[[3],[2],[2]],[[5],[5],[1]]],dtype=np.float32)
    y = np.array([[[4],[3],[2]],[[1],[3],[1]]],dtype=np.float32)
    '''
    xx_mean = tf.reduce_mean(xx,1, True)
    xxx = xx - xx_mean
    xxx1 = tf.square(xxx)
    xm = tf.reduce_sum(xxx1,axis=1)
 
    yy_mean = tf.reduce_mean(yy,1, True);
    yyy = yy - yy_mean
    yyy1 = tf.square(yyy)
    ym = tf.reduce_sum(yyy1,axis=1)
    
    p2 = tf.sqrt(xm * ym)
    m = tf.multiply(xxx, yyy)
    p1 = tf.reduce_sum(m, axis=1)
    p = p1/(p2+0.001)
    p_mean = tf.reduce_mean(p)
    return p_mean

x = np.array([[[3],[2],[2]],[[5],[5],[1]]],dtype=np.float32)
y = np.array([[[4],[3],[2]],[[1],[3],[1]]],dtype=np.float32)


#mean: 4 batch, 2 documents, 3 sententces, word 3 dimensions

xx = tf.convert_to_tensor(x,dtype=tf.float32)
yy = tf.convert_to_tensor(y,dtype=tf.float32)

p = pearson(xx, yy)

z, pr = tf.contrib.metrics.streaming_pearson_correlation(xx, yy)

init = tf.global_variables_initializer() 
init_local = tf.local_variables_initializer()

with tf.Session() as sess:
    sess.run([init, init_local])
    print(sess.run(pr))
    print(sess.run(p))