多维张量做tf.matmul

import tensorflow as tf
import numpy as np
# a = tf.random.uniform([2, 1, 2, 3])
# b = tf.random.uniform([1, 3, 3, 2])
# c = tf.matmul(a, b)

'''https://zhuanlan.zhihu.com/p/138731311'''


a = tf.random.uniform([3, 2, 3])
b = tf.random.uniform([3, 3, 2])
c = tf.matmul(a, b)
print(a)
print(b)
print('##############################################')
print(c)


c = tf.matmul(a[0],b[0])
print(c)
c = tf.matmul(a[1],b[1])
print(c)
c = tf.matmul(a[2],b[2])
print(c)


print('_______________________________________________________')

'''四维的情况'''
# a = tf.random.uniform([2, 1, 2, 3])
# b = tf.random.uniform([2, 3, 3, 2])
# c = tf.matmul(a, b)
# print(c.shape)

'''后面讨论多维 tf.matmul(a, b, transpose_b=True) 的情况:'''
'''transpose只是对最后两维做了转置,用于二维矩阵乘法能对的上。'''
tf.Tensor(
[[[0.22279859 0.93632984 0.42564   ]
  [0.2622099  0.8395437  0.59968674]]

 [[0.37575638 0.9383136  0.08132219]
  [0.3693179  0.93938255 0.61704004]]

 [[0.49982202 0.6911758  0.49174345]
  [0.41240907 0.86783767 0.26714265]]], shape=(3, 2, 3), dtype=float32)
tf.Tensor(
[[[0.860284   0.9210191 ]
  [0.76592994 0.9031868 ]
  [0.4583509  0.4927404 ]]

 [[0.121593   0.14072907]
  [0.10647845 0.54747546]
  [0.2521479  0.1317743 ]]

 [[0.64873385 0.7385361 ]
  [0.7959579  0.6605079 ]
  [0.2979567  0.48997307]]], shape=(3, 3, 2), dtype=float32)
##############################################
tf.Tensor(
[[[1.1039256  1.2606126 ]
  [1.1434736  1.295255  ]]

 [[0.16610473 0.5772997 ]
  [0.30051583 0.6475727 ]]

 [[1.0209166  1.0666047 ]
  [1.037903   1.0086854 ]]], shape=(3, 2, 2), dtype=float32)
tf.Tensor(
[[1.1039256 1.2606126]
 [1.1434736 1.295255 ]], shape=(2, 2), dtype=float32)
tf.Tensor(
[[0.16610473 0.5772997 ]
 [0.30051583 0.6475727 ]], shape=(2, 2), dtype=float32)
tf.Tensor(
[[1.0209166 1.0666047]
 [1.037903  1.0086854]], shape=(2, 2), dtype=float32)

Process finished with exit code 0

 链接:https://zhuanlan.zhihu.com/p/138731311

原文地址:https://www.cnblogs.com/DDBD/p/13920035.html