TensorFlow中tf.batch_matmul()的用法
TensorFlow中tf.batch_matmul()用法
如果有两个三阶张量,size分别为
a.shape = [100, 3, 4]
b.shape = [100, 4, 5]
c = tf.batch_matmul(a, b)
则c.shape = [100, 3, 5] //将每一对 3x4 的矩阵与 4x5 的矩阵分别相乘。batch_size不变
100为张量的batch_size。剩下的两个维度为数据的维度。
不过新版的tensorflow已经移除了上面的函数,使用时换为tf.matmul就可以了。与上面注释的方式是同样的。
附: 如果是更高维度。例如(a, b, m, n) 与(a, b, n, k)之间做matmul运算。则结果的维度为(a, b, m, k)。
TensorFlow如何实现batch_matmul
我们知道,在tensorflow早期版本中有tf.batch_matmul()函数,可以实现多维tensor和低维tensor的直接相乘,这在使用过程中非常便捷。
但是最新版本的tensorflow现在只有tf.matmul()函数可以使用,不过只能实现同维度的tensor相乘, 下面的几种方法可以实现batch matmul的可能。
例如: tensor A(batch_size,m,n), tensor B(n,k),实现batch matmul 使得A * B。
方法1: 利用tf.matmul()
对tensor B 进行增维和扩展
A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3)))
B = tf.Variable(tf.random_normal(shape=(3, 5)))
B_exp = tf.tile(tf.expand_dims(B,0),[batch_size, 1, 1]) #先进行增维再扩展
C = tf.matmul(A, B_exp)
方法2: 利用tf.reshape()
对tensor A 进行reshape操作,然后利用tf.matmul()
A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3)))
B = tf.Variable(tf.random_normal(shape=(3, 5)))
A = tf.reshape(A, [-1, 3])
C = tf.reshape(tf.matmul(A, B), [-1, 2, 5])
方法3: 利用tf.scan()
利用tf.scan() 对tensor按第0维进行展开的特性
A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3)))
B = tf.Variable(tf.random_normal(shape=(3, 5)))
initializer = tf.Variable(tf.random_normal(shape=(2,5)))
C = tf.scan(lambda a,x: tf.matmul(x, B), A, initializer)
方法4: 利用tf.einsum()
A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3)))
B = tf.Variable(tf.random_normal(shape=(3, 5)))
C = tf.einsum('ijk,kl->ijl',A,B)
(资源库 www.zyku.net)
原文链接:https://blog.csdn.net/yyhhlancelot/article/details/81191923
上一篇:教你用Python3+mysql8.0搭建Django框架
栏 目:Python教程
下一篇:OpenCv实现绘图功能
本文标题:TensorFlow中tf.batch_matmul()的用法
本文地址:https://www.zyku.net/python/9898.html
您可能感兴趣的文章
- 02-09浅谈tensorflow语义分割api的使用(deeplab训练citysca
- 07-05Linux rm命令
- 11-28禁止 Apache 显示目录列表的方法
- 03-31华为手机设置15秒锁屏方法
- 02-18关于MariaDB安装问题小记(CMake Error
- 12-09荣耀magic3如何截图
- 12-29初级会计师平台-初级会计师平台应用软
- 01-19百万超人答题-百万超人答题应用软件功
- 12-09红米手机在哪里看电池健康度
- 07-26阿里云API接口报错 Specified paramet
- 03-04wordpress把页面设置为首页之后分页失
- 03-04wordpress支持中文用户名的实现方法
- 09-14ios14.8更新内容介绍
- 02-01华为手机使用NFC功能给公交卡充值方法
- 12-25侯马生活-侯马生活应用软件功能介绍
- 02-19解决ecshop提示不支持jpeg类型图片的
- 12-01小米手机怎么设置早间新闻播报
- 12-05华为p50pro设置隐藏相册教程分享
- 09-19小米mix4设置深色模式步骤介绍
- 01-03脸型配发型-脸型配发型应用软件功能介
最近更新
阅读排行
猜你喜欢
- 03-20红魔6pro手机启用5g信号方法
- 11-01支付宝蚂蚁森林如何获取山杏皮肤
- 03-17详解MySQL主从复制实战 - 基于GTID的
- 02-20Ubuntu 下 MySQL 多实例配置
- 11-10支付宝小荷包使用方法介绍
- 02-18HTML5拖拉上传文件的简单实例
- 02-07小米11查看实时网速方法
- 01-13dedecms中sql标签调用数据实例分析
- 01-12中公教师-中公教师应用软件功能介绍
- 10-27iphone13虚拟home键如何调出