[英]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.