概述

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

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

示例

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中的batch_dot,dot方法和TensorFlow的matmul

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就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签:
keras,batch_dot,dot方法,TensorFlow,matmul

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。