我有一个矩阵SxN,其中每个K_ij是一个标量
[[K_11,K_12,K_13,..,K_1N],
[K_21,K_22,K_23,..,K_2N],
..,
[K_S1,K_S2,K_S3,..,K_SN]]
另一个矩阵SxD,每个X_i是一个Dx1向量
[X_1,
X_2,
...,
X_S]
我想要一个给我的结果
[[K_11 * X_1],[K_12 * X_1] ..., [K_1N * X_1],
[K_21 * X_2],[K_22 * X_2] ..., [K_2N * X_2],
[K_31 * X_3],[K_32 * X_2] ..., [K_3N * X_3],
......,
[K_S1 * X_S],[K_S2 * X_S] ..., [K_SN * X_S]]
其中*代表乘法
有什么有效的方法吗?
答案 0 :(得分:0)
我想这就是你想要的:
import tensorflow as tf
import numpy as np
K = tf.placeholder(tf.float32, [None, None]) # (S, N)
X = tf.placeholder(tf.float32, [None, None]) # (S, D)
# All-to-all product: (S, N, D)
result = K[:, :, tf.newaxis] * X[:, tf.newaxis, :]
# Test
with tf.Session() as sess:
# (2, 2)
K_val = np.array([[10., 20.],
[30., 40.]])
# (2, 3)
X_val = np.array([[1., 2., 3.],
[4., 5., 6.]])
# (2, 2, 3)
result_val = sess.run(result, feed_dict={K: K_val, X: X_val})
print(result_val)
输出:
[[[ 10. 20. 30.]
[ 20. 40. 60.]]
[[120. 150. 180.]
[160. 200. 240.]]]
答案 1 :(得分:-1)
或者(使用TF API):
tf.matmul(tf.expand_dims(in1, axis=2), tf.expand_dims(in2, axis=1))