tensorflow中每个特征的高效多特征相似性

Efficient multi-feature similarity with each feature in tensorlflow

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

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 中编写高效的编码风格? 谢谢!!

你快到了。扩展维度并使用广播同时对每个特征执行操作:

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 张量时都有效。