// Introduce dummy dimension so we can use broadcasting
f= tf.reshape(X, tf.pack([tf.shape(X)[0], 1, tf.shape(X)[1]]) )
f2= tf.reshape(X2, tf.pack([1, tf.shape(X2)[0], tf.shape(X2)[1]]) )
r = np.pi * (f-f2) / self.period
dist = tf.exp(-0.5*tf.reduce_sum(tf.square(tf.sin(r)/self.lengthscales),tf.rank(r)-1))
After Change
// Introduce dummy dimension so we can use broadcasting
f = tf.expand_dims(X, 1) // now N x 1 x D
f2 = tf.expand_dims(X2, 0) // now 1 x M x D
r = np.pi * (f-f2) / self.period
r = tf.reduce_sum(tf.square(tf.sin(r)/self.lengthscales), 2)