[英]How to calculate squared sum quickly in Tensorflow2?
我用张量流做到了。 但它是一一计算的。 所以它不够快。 我试图让 fixed_mat 和 input_np 像 (1000, 101, 1088)。 它没有用......有什么建议来计算巨大的输入吗??? 感谢提前。
fixed_mat.shape
(101, 1088)
input_np.shape
(1000, 1088)
import tensorflow as tf
num = 2
res = tf.reduce_sum(tf.math.squared_difference(fixed_mat,
np.array([input_np[1]] * fixed_mat.shape[0])), 1)
vals, indice = tf.nn.top_k(tf.negative(res), num)
print(list(indice.numpy()), list(- vals.numpy()))
[13, 90] [1.3422034332504837, 1.8790145150615656]
如果你想加速 tensorflow 代码,你不应该使用 Eager 模式。 最好使用@tf.function
装饰器
请参阅本指南: https ://www.tensorflow.org/guide/function
此代码有效:
@tf.function
def my_tf_function(fixed_mat, input_np, num):
res = tf.reduce_sum(tf.math.squared_difference(
fixed_mat,
tf.gather(input_np, 1)), 1)
vals, indice = tf.nn.top_k(tf.negative(res), num)
return vals, indice
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.