与tensorlflow中的每个特征具有高效的多特征相似性

时间:2018-05-08 08:58:30

标签: python tensorflow coding-style

我想计算张量流中每个特征的多特征相似度。 但我不知道如何有效地写它。 这是我的示例代码:

import numpy as np
import tensorflow as tf


num_data = 64
feat_dim = 6
A_feature = np.random.randn(10, feat_dim).astype(np.float32)
P_feature = np.random.randn(5, feat_dim).astype(np.float32)

#Python Version for each feature
out = np.zeros((len(P_feature),1))
for i in range(len(P_feature)):
    t = (A_feature-P_feature[i])
    t1 = t**2
    t2 = np.sum(t1,axis=1)
    t3 = np.sum(t2**2.0)**(1/2.0)
    out[i]=t3

#Half Tensorflow Version with only one feature result
P_dist2 = tf.norm(tf.reduce_sum(tf.square(tf.subtract(A_feature, P_feature[0])), 1),ord=2)
with tf.Session() as sess:
        pos_dist2_np = sess.run(P_dist2)

谁能告诉我如何在tensorflow中编写高效的编码风格? 谢谢!

1 个答案:

答案 0 :(得分:0)

你快到了。扩展尺寸并使用广播同时执行每个功能的操作:

aux = tf.subtract(A_feature[None, :, :], P_feature[:, None, :])  # Shape=(5, 10, feat_dim)
aux = tf.reduce_sum(tf.square(aux), -1)  # Shape=(5, 10)
P_dist3 = tf.norm(aux, ord=2, axis=-1)  # Shape=(5,)

with tf.Session() as sess:
    pos_dist3_np = sess.run(P_dist3)

请注意,当A_featureP_feature是NumPy数组和TensorFlow张量时,这都适用。