TensorFlow中tf.batch_matmul()的用法

作者:yyhhlancelot 时间:2022-06-06 10:33:37 

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)

来源:https://blog.csdn.net/yyhhlancelot/article/details/81191923

标签:TensorFlow,tf.batch,matmul
0
投稿

猜你喜欢

  • 分步启动数据库以重命名数据文件

    2009-03-25 12:33:00
  • python列表操作之extend和append的区别实例分析

    2023-08-02 15:14:30
  • golang 实现tcp转发代理的方法

    2023-08-06 02:46:55
  • Python OpenCV实现视频分帧

    2023-06-06 02:38:18
  • python关于变量名的基础知识点

    2023-07-27 14:21:43
  • WEB2.0网页制作标准教程(11)不用表格的菜单

    2008-02-19 19:36:00
  • Python实现RGB等图片的图像插值算法

    2023-03-30 17:11:55
  • Python数学建模StatsModels统计回归可视化示例详解

    2023-10-09 02:16:54
  • 可输入的select代码

    2009-12-26 18:25:00
  • 常见数据库系统比较 Oracle数据库

    2010-07-28 12:44:00
  • asp三天学好ADO对象之第三天

    2008-10-09 12:53:00
  • CI框架出现mysql数据库连接资源无法释放的解决方法

    2023-11-15 07:13:35
  • Python生成随机数的方法详解(最全)

    2023-05-04 12:36:08
  • SQL Server 2008升级报表服务器数据库

    2008-11-18 12:36:00
  • QQ在线客服网页代码大全

    2008-01-17 18:28:00
  • Python线程条件变量Condition原理解析

    2022-07-23 02:52:06
  • PHP的mysqli_select_db()函数讲解

    2023-06-07 18:59:44
  • PHP结构型模式之代理模式

    2023-05-25 06:55:34
  • python生成指定长度的随机数密码

    2021-01-24 23:53:17
  • asp随机提取access数据库记录的几种方法

    2007-09-06 19:42:00
  • asp之家 网络编程 m.aspxhome.com