Tensorflow中矩阵的加权和 [英] Weighted sum of matrices in Tensorflow
问题描述
我有一个大小为(M,N,N)的3维张量A和一个大小为M的1维张量p.我想计算矩阵的加权和:
I have a 3-dimensional tensor A of size (M,N,N) and an 1 dimensional tensor p of size M. I want to compute the weighted sum of matrices:
在NumPy中,我正在实现以下代码:
In NumPy I am implementing the following code:
import numpy as np
temp=np.array([p[m]*A[m] for m in range(M)])
B=sum(temp);
我想在TensorFlow中做同样的事情,但是我似乎找不到任何内置的操作来执行同样的事情.我尝试了tf.matmul
和tf.mul
,但是它们似乎没有给出期望的结果.有人可以建议我在TensorFlow中执行此操作的正确方法吗?
I want to do the same in TensorFlow but I don't seem to find any inbuilt operations to carry out the same. I tried tf.matmul
and tf.mul
but they don't seem to be giving the desired result. Can someone suggest me a right way to do this in TensorFlow?
推荐答案
如果当您具有大小为(K,M)
的P矩阵和大小为(M,N,N)
的张量A时要计算大小为(K,N,N)
的张量B ,您可以按照它进行操作.
If you want to compute a tensor B of size (K,N,N)
when you have a P matrix of size (K,M)
and a tensor A of size (M,N,N)
, you can follow it.
import tensorflow as tf
import numpy as np
K = 2
M = 3
N = 2
np.random.seed(0)
A = tf.constant(np.random.randint(1,5,(M,N,N)),dtype=tf.float64)
# when K.shape=(K,M)
P = tf.constant(np.random.randint(1,5,(K,M)),dtype=tf.float64)
# when K.shape=(M,)
# P = tf.constant(np.random.randint(1,5,(M,)),dtype=tf.float64)
P_new = tf.expand_dims(tf.expand_dims(P,-1),-1)
# if K.shape=(K,M) set axis=1,if K.shape=(M,) set axis=0,
B = tf.reduce_sum(tf.multiply(P_new , A),axis=1)
with tf.Session()as sess:
print(sess.run(P))
print(sess.run(A))
print(sess.run(B))
[[1. 4. 3.]
[1. 1. 1.]]
[[[1. 4.]
[2. 1.]]
[[4. 4.]
[4. 4.]]
[[2. 4.]
[2. 3.]]]
[[[23. 32.]
[24. 26.]]
[[ 7. 12.]
[ 8. 8.]]]
可以修改以上代码,以在您的问题中包含问题的解决方案.
The above code can be modified to include the solution of problem in your question.
这篇关于Tensorflow中矩阵的加权和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!