当你有一个大小为(K,M)的P矩阵和一个大小为(M,N,N)的张量A时,如果你想计算一个大小为(K,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.]]]
上面的代码可以修改为在你的问题中包含问题的解决方案。