温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

tensorflow多维张量计算实例

发布时间:2020-10-01 23:50:12 来源:脚本之家 阅读:146 作者:PROMINEM 栏目:开发技术

两个三维矩阵的乘法怎样计算呢?我通过实验发现,tensorflow把前面的维度当成是batch,对最后两维进行普通的矩阵乘法。也就是说,最后两维之前的维度,都需要相同。

首先计算shape为(2, 2, 3)乘以shape为(2, 3, 2)的张量。

import tensorflow as tf
import numpy as np
a = tf.constant(np.arange(1, 13, dtype=np.float32), shape=[2, 2, 3])
b = tf.constant(np.arange(1, 13, dtype=np.float32), shape=[2, 3, 2])
c = tf.matmul(a, b)
# c = tf.matmul(a, b)
sess = tf.Session()
print("a*b = ", sess.run(c))
c1 = tf.matmul(a[0, :, :], b[0, :, :])
print("a[1]*b[1] = ", sess.run(c1))

运行结果:

tensorflow多维张量计算实例

计算结果表明,两个三维矩阵相乘,对应位置的最后两个维度的矩阵乘法。

再验证高维的张量乘法:

import tensorflow as tf
import numpy as np
a = tf.constant(np.arange(1, 36, dtype=np.float32), shape=[3, 2, 2, 3])
b = tf.constant(np.arange(1, 36, dtype=np.float32), shape=[3, 2, 3, 2])
c = tf.matmul(a, b)
# c = tf.matmul(a, b)
sess = tf.Session()
print("a*b = ", sess.run(c))
c1 = tf.matmul(a[0, 0, :, :], b[0, 0, :, :])
print("a[1]*b[1] = ", sess.run(c1))

运行结果:

tensorflow多维张量计算实例

以上这篇tensorflow多维张量计算实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI