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

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

本文详细对比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 相关产品和应用

全部下载

专题列表