前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >浅谈keras中的batch_dot,dot方法和TensorFlow的matmul

浅谈keras中的batch_dot,dot方法和TensorFlow的matmul

作者头像
砸漏
发布2020-10-21 10:12:02
2K0
发布2020-10-21 10:12:02
举报
文章被收录于专栏:恩蓝脚本恩蓝脚本

概述

在使用keras中的keras.backend.batch_dot和tf.matmul实现功能其实是一样的智能矩阵乘法,比如A,B,C,D,E,F,G,H,I,J,K,L都是二维矩阵,中间点表示矩阵乘法,AG 表示矩阵A 和G 矩阵乘法(A 的列维度等于G 行维度),WX=Z

代码语言:javascript
复制
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)
代码语言:javascript
复制
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)

示例

代码语言:javascript
复制
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].

代码语言:javascript
复制
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)

或者

代码语言:javascript
复制
import tensorflow as tf
a = tf.ones((3,4))
b = tf.ones((4,5))
c = tf.matmul(a, b)
print(c.shape)#(3,5)

如果增加维度:

代码语言:javascript
复制
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矩阵乘法

代码语言:javascript
复制
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方法是Theano中的复制

代码语言:javascript
复制
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).
代码语言:javascript
复制
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)

或者

代码语言:javascript
复制
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就是小编分享给大家的全部内容了,希望能给大家一个参考。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档