Keras中batch_dot与dot方法及TensorFlow matmul的矩阵乘法解析

季宁
季宁
发布时间:2026-10-14| 5人浏览过
原创

本文详细对比Keras后端函数batch_dot、dot与TensorFlow的matmul在矩阵乘法中的行为差异。通过多维数组示例,解析batch_dot沿最后两维运算、dot处理高维广播及matmul的等效性,帮助开发者正确选择函数以避免维度错误。

概述

概述

batch_dot与matmul的功能等价性

在Keras中调用keras.backend.batch_dot与使用TensorFlow的tf.matmul,两者在实现智能矩阵乘法功能上是一致的。假设A、B、C、D、E、F、G、H、I、J、K、L均为二维矩阵,中间点号代表矩阵乘法操作,例如AG表示矩阵A与G相乘(要求A的列维度等于G的行维度),结果记为WX=Z。


import keras.backend as K
import tensorflow as tf
import numpy as np

w = K.variable(np.random.randint(10,size=(10,12,4,5)))
k = K.variable(np.random.randint(10,size=(10,12,5,8)))
z = K.batch_dot(w,k)
print(z.shape) #(10, 12, 4, 8)


import keras.backend as K
import tensorflow as tf
import numpy as np

w = tf.Variable(np.random.randint(10,size=(10,12,4,5)),dtype=tf.float32)
k = tf.Variable(np.random.randint(10,size=(10,12,5,8)),dtype=tf.float32)
z = tf.matmul(w,k)
print(z.shape) #(10, 12, 4, 8)

多维矩阵乘法示例与维度错误分析

示例


from keras import backend as K
a = K.ones((3,4,5,2))
b = K.ones((2,5,3,7))
c = K.dot(a, b)
print(c.shape)

程序运行后输出如下结果:

ValueError: Dimensions must be equal, but are 2 and 3 for ‘MatMul' (op: ‘MatMul') with input shapes: [60,2], [3,70].


from keras import backend as K
a = K.ones((3,4))
b = K.ones((4,5))
c = K.dot(a, b)
print(c.shape)#(3,5)

或者出现以下错误提示:


import tensorflow as tf
a = tf.ones((3,4))
b = tf.ones((4,5))
c = tf.matmul(a, b)
print(c.shape)#(3,5)

若增加输入矩阵的维度,操作方式如下:


from keras import backend as K
a = K.ones((2,3,4))
b = K.ones((7,4,5))
c = K.dot(a, b)
print(c.shape)#(2, 3, 7, 5)

此类矩阵乘法是沿着两个矩阵的最后两个维度执行乘法运算,而非逐元素(element-wise)的矩阵乘法。


from keras import backend as K
a = K.ones((1, 2, 3 , 4))
b = K.ones((8, 7, 4, 5))
c = K.dot(a, b)
print(c.shape)#(1, 2, 3, 8, 7, 5)

Keras dot方法的来源与高维处理

Keras中的dot方法源自Theano框架的复制实现。


from keras import backend as K
a = K.ones((1, 2, 4))
b = K.ones((8, 7, 4, 5))
c = K.dot(a, b)
print(c.shape)# (1, 2, 8, 7, 5).

from keras import backend as K
a = K.ones((9, 8, 7, 4, 2))
b = K.ones((9, 8, 7, 2, 5))
c = K.batch_dot(a, b)
print(c.shape) #(9, 8, 7, 4, 5)

或者采用以下调用方式:


import tensorflow as tf
a = tf.ones((9, 8, 7, 4, 2))
b = tf.ones((9, 8, 7, 2, 5))
c = tf.matmul(a, b)
print(c.shape) #(9, 8, 7, 4, 5)

以上内容为关于Keras中batch_dot、dot方法以及TensorFlow matmul的简要介绍,希望能为读者提供有价值的参考,同时也欢迎大家继续支持本站获取更多技术分享。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。