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

yipeiwu_com6年前Python基础

如下所示:

# 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]

以上这篇tensorflow 用矩阵运算替换for循环 用tf.tile而不写for的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python遍历numpy数组的实例

在用python进行图像处理时,有时需要遍历numpy数组,下面是遍历数组的方法: [rows, cols] = num.shape for i in range(rows - 1...

python基础教程之Filter使用方法

python Filter Python中的内置函数filter()主要用于过滤序列。 和map类似,filter()也接收一个函数和序列,和map()不同的是,filter()把传入...

pandas 获取季度,月度,年度首尾日期的方法

可实现类似于sql中的dateadd、datesub的功能 两种获取日期的方式 z=datetime.datetime(2016,12,5) z=datetime.datetime....

Python读取本地文件并解析网页元素的方法

如下所示: from bs4 import BeautifulSoup path = './web/new_index.html' with open(path, 'r') as f...

在Python的web框架中中编写日志列表的教程

在Python的web框架中中编写日志列表的教程

MVVM模式不但可用于Form表单,在复杂的管理页面中也能大显身手。例如,分页显示Blog的功能,我们先把后端代码写出来: 在apis.py中定义一个Page类用于存储分页信息: c...