tensorflow多维张量计算实例

今天小编就为大家分享一篇tensorflow多维张量计算实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

两个三维矩阵的乘法怎样计算呢?我通过实验发现,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))

运行结果:

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

再验证高维的张量乘法:

 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多维张量计算实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持html中文网。

以上就是tensorflow多维张量计算实例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python