网络编程
位置:首页>> 网络编程>> Python编程>> tensorflow 用矩阵运算替换for循环 用tf.tile而不写for的方法

tensorflow 用矩阵运算替换for循环 用tf.tile而不写for的方法

作者:guotong1988  发布时间:2021-08-11 11:43:55 

标签:tensorflow,for,tf.tile

如下所示:


# u [32,30,200]
# u_logits [400,32,30]
q_j_400 = []
for j in range(400):
q_j_400.append(tf.squeeze(tf.matmul(tf.transpose(u,[0,2,1]),tf.expand_dims(tf.nn.softmax(u_logits[j]),-1)),[2])) # tf.matmul [32,200,30],[32,30,1]
test_result = tf.stack(q_j_400)
test_result = tf.transpose(test_result,[1,0,2])

可以通过tf.tile实现更高速的版本


# u [32,30,200]
# u_logits [32,400,30]
u_tile = tf.tile(tf.expand_dims(u,1),[1,400,1,1])
u_logits = tf.expand_dims(tf.nn.softmax(u_logits,-1),-1)
test_result = tf.reduce_sum(u_logits * u_tile,-2) # [32,400,30,1]*[32,400,30,200]

来源:https://blog.csdn.net/guotong1988/article/details/78284560

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com