@tf_export("matmul")
def matmul(a,b,transpose_a=False,transpose_b=False,adjoint_a=False,adjoint_b=False,a_is_sparse=False,b_is_sparse=False,name=None):"""Multiplies matrix `a` by matrix `b`, producing `a` * `b`.将矩阵a与矩阵b相乘,得出a * b。The inputs must, following any transpositions, be tensors of rank >= 2where the inner 2 dimensions specify valid matrix multiplication arguments,and any further outer dimensions match.在进行任何换位后,输入必须为(秩?)> = 2的张量,其中内部2维指定有效的矩阵乘法自变量,并且任何其他外部维匹配。Both matrices must be of the same type. The supported types are:`float16`, `float32`, `float64`, `int32`, `complex64`, `complex128`.两种矩阵必须属于同一类型。 支持的类型有:`float16`,`float32`,`float64`,`int32`,`complex64`,`complex128`。Either matrix can be transposed or adjointed (conjugated and transposed) onthe fly by setting one of the corresponding flag to `True`. These are `False`by default.通过将相应标志之一设置为“ True”,可以即时对矩阵进行转置或连接(共轭和转置)。 这些默认为False。If one or both of the matrices contain a lot of zeros, a more efficientmultiplication algorithm can be used by setting the corresponding`a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default.This optimization is only available for plain matrices (rank-2 tensors) withdatatypes `bfloat16` or `float32`.如果一个或两个矩阵都包含大量零,则可以通过将相应的“ a_is_sparse”或“ b_is_sparse”标志,设置为“ True”来使用更有效的乘法算法。 这些默认为False。此优化仅适用于数据类型为bfloat16或float32的普通矩阵(秩2张量)。For example:```python# 2-D tensor `a`# [[1, 2, 3],#  [4, 5, 6]]a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])# 2-D tensor `b`# [[ 7,  8],#  [ 9, 10],#  [11, 12]]b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])# `a` * `b`# [[ 58,  64],#  [139, 154]]c = tf.matmul(a, b)# 3-D tensor `a`# [[[ 1,  2,  3],#   [ 4,  5,  6]],#  [[ 7,  8,  9],#   [10, 11, 12]]]a = tf.constant(np.arange(1, 13, dtype=np.int32),shape=[2, 2, 3])# 3-D tensor `b`# [[[13, 14],#   [15, 16],#   [17, 18]],#  [[19, 20],#   [21, 22],#   [23, 24]]]b = tf.constant(np.arange(13, 25, dtype=np.int32),shape=[2, 3, 2])# `a` * `b`# [[[ 94, 100],#   [229, 244]],#  [[508, 532],#   [697, 730]]]c = tf.matmul(a, b)# Since python >= 3.5 the @ operator is supported (see PEP 465).# In TensorFlow, it simply calls the `tf.matmul()` function, so the# following lines are equivalent:由于python> = 3.5,因此支持@运算符(请参阅PEP 465)。在TensorFlow中,它仅调用`tf.matmul()`函数,因此以下几行是等效的:d = a @ b @ [[10.], [11.]]d = tf.matmul(tf.matmul(a, b), [[10.], [11.]])Args:a: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`,`complex128` and rank > 1.类型为`float16`,`float32`,`float64`,`int32,`complex64`,`complex128`和秩> 1的`Tensor`。b: `Tensor` with same type and rank as `a`.具有与a相同类型和秩的Tensor。transpose_a: If `True`, `a` is transposed before multiplication.如果为True,则在相乘之前对a进行转置。transpose_b: If `True`, `b` is transposed before multiplication.如果为True,则在相乘之前将b换位。adjoint_a: If `True`, `a` is conjugated and transposed beforemultiplication.如果为True,则在相乘之前对a进行共轭和转置。adjoint_b: If `True`, `b` is conjugated and transposed beforemultiplication.如果为True,则在相乘之前对b进行共轭和转置。a_is_sparse: If `True`, `a` is treated as a sparse matrix.如果为True,则将a视为稀疏矩阵。b_is_sparse: If `True`, `b` is treated as a sparse matrix.如果为True,则将b视为稀疏矩阵。name: Name for the operation (optional).操作名称(可选)。Returns:A `Tensor` of the same type as `a` and `b` where each inner-most matrix isthe product of the corresponding matrices in `a` and `b`, e.g. if alltranspose or adjoint attributes are `False`:与`a`和`b`具有相同类型的`张量`,其中每个最里面的矩阵是`a`和`b`中对应矩阵的乘积,例如 如果所有转置或伴随属性均为False:`output`[..., i, j] = sum_k (`a`[..., i, k] * `b`[..., k, j]),for all indices i, j.Note: This is matrix product, not element-wise product.这是矩阵乘积,而不是元素乘积。Raises:ValueError: If transpose_a and adjoint_a, or transpose_b and adjoint_bare both set to True."""with ops.name_scope(name, "MatMul", [a, b]) as name:if transpose_a and adjoint_a:raise ValueError("Only one of transpose_a and adjoint_a can be True.")if transpose_b and adjoint_b:raise ValueError("Only one of transpose_b and adjoint_b can be True.")if context.executing_eagerly():if not isinstance(a, (ops.EagerTensor, _resource_variable_type)):a = ops.convert_to_tensor(a, name="a")if not isinstance(b, (ops.EagerTensor, _resource_variable_type)):b = ops.convert_to_tensor(b, name="b")else:a = ops.convert_to_tensor(a, name="a")b = ops.convert_to_tensor(b, name="b")# TODO(apassos) remove _shape_tuple here when it is not needed.a_shape = a._shape_tuple()  # pylint: disable=protected-accessb_shape = b._shape_tuple()  # pylint: disable=protected-accessif (not a_is_sparse andnot b_is_sparse) and ((a_shape is None or len(a_shape) > 2) and(b_shape is None or len(b_shape) > 2)):# BatchMatmul does not support transpose, so we conjugate the matrix and# use adjoint instead. Conj() is a noop for real matrices.if transpose_a:a = conj(a)adjoint_a = Trueif transpose_b:b = conj(b)adjoint_b = Truereturn gen_math_ops.batch_mat_mul(a, b, adj_x=adjoint_a, adj_y=adjoint_b, name=name)# Neither matmul nor sparse_matmul support adjoint, so we conjugate# the matrix and use transpose instead. Conj() is a noop for real# matrices.if adjoint_a:a = conj(a)transpose_a = Trueif adjoint_b:b = conj(b)transpose_b = Trueuse_sparse_matmul = Falseif a_is_sparse or b_is_sparse:sparse_matmul_types = [dtypes.bfloat16, dtypes.float32]use_sparse_matmul = (a.dtype in sparse_matmul_types and b.dtype in sparse_matmul_types)if ((a.dtype == dtypes.bfloat16 or b.dtype == dtypes.bfloat16) anda.dtype != b.dtype):# matmul currently doesn't handle mixed-precision inputs.use_sparse_matmul = Trueif use_sparse_matmul:ret = sparse_matmul(a,b,transpose_a=transpose_a,transpose_b=transpose_b,a_is_sparse=a_is_sparse,b_is_sparse=b_is_sparse,name=name)# sparse_matmul always returns float32, even with# bfloat16 inputs. This prevents us from configuring bfloat16 training.# casting to bfloat16 also matches non-sparse matmul behavior better.if a.dtype == dtypes.bfloat16 and b.dtype == dtypes.bfloat16:ret = cast(ret, dtypes.bfloat16)return retelse:return gen_math_ops.mat_mul(a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)


通过结果可以看出,两个多维矩阵再相乘时,它们除了后两维之外的维度必须相同,否则怎能做到一一对应呢?
比如a的维度是(2,2,3),b的维度是(2,3,2),它们除了最后两维之外的维度2必须相同,而最后两维需要满足矩阵乘法要求,一个是(i,j),另一个必须是(j,k)。

相乘后,除后两维之外的维度不变,后两维变成(i,k),如(…,i,j)*(…,j,k)= (…,i,k)

参考文章:[tensorflow] 多维矩阵的乘法

tensorflow tf.matmul() (多维)矩阵相乘(多维矩阵乘法)相关推荐

  1. 两个3×3矩阵乘法例题_两个3×3矩阵相乘 三个矩阵相乘从左向右算还是从右算起...

    两个三乘三矩阵相乘怎么算,在线等 设A为m*p的矩阵,B为p*n的矩阵,那么称m*n的矩阵C为矩阵A与B的乘积,记作C=AB ,其中矩阵C中的第i行第j列元素可以表示为: 例如: 扩展资料: 注意事项 ...

  2. R语言使用psych包的fa函数对指定数据集进行因子分析(输入数据为相关性矩阵)、使用rotate参数指定进行斜交旋转提取因子、编写自定义函数通过因子模式矩阵与因子相关性矩阵相乘计算因子载荷矩阵

    R语言使用psych包的fa函数对指定数据集进行因子分析(输入数据为相关性矩阵).使用rotate参数指定进行斜交旋转提取因子.编写自定义函数通过因子模式矩阵与因子相关性矩阵相乘计算因子载荷矩阵 目录

  3. matlab里的矩阵和opencv里的矩阵的区别,opencv 矩阵相乘, matlab矩阵相乘,以及自己写的矩阵相乘的时间比较...

    直接上代码吧 matlab clc close all clear all tic; c = rand(7500,7500)*rand(7500,1);toc; Elapsed time is2.57 ...

  4. cuda矩阵相乘_CUDA计算矩阵相乘

    1.最简单的 kernel 函数 __global__ void MatrixMulKernel( float* Md, float* Nd, float* Pd, int Width) { int ...

  5. c语言编程任意矩阵相乘,c语言矩阵相乘

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 程序清单 #include&nbsp int&nbspmain(void) { &nbsp&nbsp&nbsp&a ...

  6. python的matmul_关于tf.matmul() 和tf.multiply() 的区别说明

    我就废话不多说了,大家还是直接看代码吧~ flyfish # a # [[1, 2, 3], # [4, 5, 6]] a = tf.constant([1, 2, 3, 4, 5, 6], shap ...

  7. torch.bmm() 与 torch.matmul()==>张量的相乘运算

    torch.bmm()强制规定维度和大小相同 torch.matmul()没有强制规定维度和大小,可以用利用广播机制进行不同维度的相乘操作 当进行操作的两个tensor都是3D时,两者等同. torc ...

  8. 【C语言】设计实现M*N矩阵和N*M矩阵相乘

    #include<stdio.h> int main() {int i,j,k,M,N,a[10][10],b[10][10],c[10][10]; //定义两个输入矩阵,一个输出矩阵 p ...

  9. C++设计矩阵,实现矩阵相乘和求逆矩阵

    矩阵变换是机器人学的基础,所以Jungle把这一节内容划分到"工业机器人"栏目.这一节Jungle用C++设计了矩阵的类Matrix,并设计了3个方法: 矩阵相加add 矩阵相乘m ...

最新文章

  1. Spark任务提交源码
  2. 超效率dea模型_【探索】基于超效率DEA模型的我国公立医院排行榜研究
  3. Entity Framework Relationships and Navigation Properties
  4. 我的创业分享 之 不要轻易选择创业
  5. java 对象等于_java 之类对象等于对象 | 学步园
  6. 程序员述职报告范文_物流人员述职报告范文(通用5篇)
  7. 人工智障学习笔记——梯度下降(2)优化算法
  8. SpringBoot项目请求路径中有正反斜杠的处理办法
  9. 好好学习 天天编程—C语言之我的第一个hello world(二)
  10. Android app内存管理的16点建议
  11. Cannot load supported formats: Cannot run program svn: CreateProcess error=2, μ
  12. Http分段下载实现
  13. 对话李国权:新加坡为什么能成为全球Web3.0创业的节点?
  14. radosgw bucket index sharding
  15. 免费下载pdf阅读器
  16. P2392 kkksc03考前临时抱佛脚
  17. python uiautomation_蜗牛笔记-文章-UIAutomation使用(一)
  18. 使用LoadLibrary动态加载DLL并使用其中的类
  19. 第六课 511遇见易语言大漠找字FindStrFastEx打多怪实例
  20. 靶场练习之hackinglab(鹰眼)-脚本题

热门文章

  1. 详解静态路由(入门类)
  2. sap 客户信贷配置与管理解析
  3. SAP ABAP ALV构建动态输出列与构建动态内表
  4. SAP推出下一代数字转型平台SAP HANA 2
  5. SAP、ORACLE、用友、金蝶四大ERP软件供应商的区别
  6. 多线程原来是这么简单
  7. 关于ABAP流程处理的一些命令的说明(stop,exit,return,check,reject)
  8. SAP FICO PA 模拟题
  9. 手把手教你搭建用户画像,数据分析效率提升百倍
  10. 围猎“下沉市场”,争抢「小镇青年」,尚美如何突围?