脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - tensorflow 用矩阵运算替换for循环 用tf.tile而不写for的方法

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

2021-03-22 00:50guotong1988 Python

今天小编就为大家分享一篇tensorflow 用矩阵运算替换for循环 用tf.tile而不写for的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

如下所示:

?
1
2
3
4
5
6
7
# 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实现更高速的版本

?
1
2
3
4
5
# 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]

以上这篇tensorflow 用矩阵运算替换for循环 用tf.tile而不写for的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/guotong1988/article/details/78284560

延伸 · 阅读

精彩推荐