tensorflow中张量乘法向量的matmul函数 [英] matmul function for vector with tensor multiplication in tensorflow

查看:67
本文介绍了tensorflow中张量乘法向量的matmul函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当我们将 1*n 维的向量 vm*n* 维的张量 T 相乘时k,我们期望得到一个维度为m*k/m*1*k的矩阵/张量.这意味着我们的张量有 m 个维度为 n*k 的矩阵切片,并且 v 与每个矩阵相乘,结果向量被堆叠一起.为了在 tensorflow 中进行乘法运算,我想出了以下公式.我只是想知道是否有任何内置函数可以直接执行此标准乘法?

In general when we multiply a vector v of dimension 1*n with a tensor T of dimension m*n*k, we expect to get a matrix/tensor of dimension m*k/m*1*k. This means that our tensor has m slices of matrices with dimension n*k, and v is multiplied to each matrix and the resulting vectors are stacked together. In order to do this multiplication in tensorflow, I came up with the following formulation. I am just wondering if there is any built-in function that does this standard multiplication straightforward?

T = tf.Variable(tf.random_normal((m,n,k)), name="tensor") 
v = tf.Variable(tf.random_normal((1,n)), name="vector")  
c = tf.stack([v,v]) # m times, here set m=2
output = tf.matmul(c,T)

推荐答案

你可以这样做:

tf.reduce_sum(tf.expand_dims(v,2)*T,1)

代码:

m, n, k = 2, 3, 4
T = tf.Variable(tf.random_normal((m,n,k)), name="tensor") 
v = tf.Variable(tf.random_normal((1,n)), name="vector")  


c = tf.stack([v,v]) # m times, here set m=2    
out1 = tf.matmul(c,T) 

out2 = tf.reduce_sum(tf.expand_dims(v,2)*T,1)
with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  n_out1 = sess.run(out1) 
  n_out2 = sess.run(out2)
  #both n_out1 and n_out2 matches

这篇关于tensorflow中张量乘法向量的matmul函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆