Tensorflow中矩阵的加权和

时间:2017-02-03 19:49:28

标签: numpy tensorflow

我有一个大小为(M,N,N)的三维张量A和一个大小为M的1维张量p。我想计算矩阵的加权和:

enter image description here

在NumPy中,我正在实现以下代码:

tf.matmul

我想在TensorFlow中做同样的事情,但我似乎没有找到任何内置的操作来执行相同的操作。我尝试了tf.mulmerge,但他们似乎没有给出所需的结果。有人可以在TensorFlow中建议我这样做的正确方法吗?

2 个答案:

答案 0 :(得分:0)

很明显,用显式广播做起来很容易。但我不确定这有多高效!

import numpy as np

A = np.array([[[1, 7],
              [4, 4]],
             [[2, 6],
              [5, 3]],
             [[3, 5],
              [6, 2]]])

p = np.array([4,3,2])

M = 3
N = 2

#numpy version
temp=np.array([p[m]*A[m] for m in range(M)])
B=sum(temp);

#tensorflow version
import tensorflow as tf
A_tf = tf.constant(A,dtype=tf.float64)
p_tf = tf.constant(p,dtype=tf.float64)
p_tf_broadcasted = tf.tile(tf.reshape(p_tf,[M,1,1]), tf.pack([1,N,N]))
B_tf = tf.reduce_sum(tf.mul(A_tf,p_tf_broadcasted), axis=0)

sess=tf.Session()
B_tf_ = sess.run(B_tf)


#make sure they're equal
B_tf_ == B


#array([[ True,  True],
#       [ True,  True]], dtype=bool)

答案 1 :(得分:0)

如果当您拥有大小为(K,N,N)的P矩阵和大小为(K,M)的张量A时,要计算大小为(M,N,N)的张量B,则可以遵循它。

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.]]]

可以修改上面的代码以在您的问题中包含问题的解决方案。

相关问题