首页 > python教程

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

时间:2020-09-14 python教程 查看: 865

概述

在使用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

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方法是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博客。

展开全文
上一篇:Python Switch Case三种实现方法代码实例
下一篇:基于PyTorch的permute和reshape/view的区别介绍
输入字:
相关知识
Python 实现图片色彩转换案例

我们在看动漫、影视作品中,当人物在回忆过程中,体现出来的画面一般都是黑白或者褐色的。本文将提供将图片色彩转为黑白或者褐色风格的案例详解,感兴趣的小伙伴可以了解一下。

python初学定义函数

这篇文章主要为大家介绍了python的定义函数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助,希望能够给你带来帮助

图文详解Python如何导入自己编写的py文件

有时候自己写了一个py文件,想要把它导入到另一个py文件里面,所以下面这篇文章主要给大家介绍了关于Python如何导入自己编写的py文件的相关资料,需要的朋友可以参考下

python二分法查找实例代码

二分算法是一种效率比较高的查找算法,其输入的是一个有序的元素列表,如果查找元素包含在列表中,二分查找返回其位置,否则返回NONE,下面这篇文章主要给大家介绍了关于python二分法查找的相关资料,需要的朋友可以参考下