python - tensorflow 中的矩阵减法类似于矩阵乘法

标签 python tensorflow matrix matrix-multiplication

这是我的第一篇文章,我通常在文件中找到所有答案,但在这个问题上遇到了困难,感谢您的帮助!

我有两个矩阵 A 和 B。使用 tf.matmult 执行矩阵乘法运算很简单。但我想做矩阵减法,类似于矩阵乘法的工作原理。例如,如果我有的话。

A = tf.constant([[1, 1, 1, 2, 3, 1],[1,2,3,4,5,6],[4,3,2,1,6,5]])
B = tf.constant([[1,3,1],[2,1,1]])

#B*A
X = tf.matmult(B,A)
>>>X = [[8,10,12,15,24,24],[7,7,7,9,17,13]]

我想做的是做类似 matmult 的操作,但我想要减法和平方而不是乘法。例如...

对于 x11,其中下标 11 是矩阵 X 的第 1 行、第 1 列。

= (-b11 + a11)2 + (-b12 + a21)2 + (-b13 + a31)2

x12 = (-b11 + a12)2 + (-b 12 + a22)2 + (-b13 + a32) 2

等等类似于矩阵乘法的工作原理。

因此,如果我们采用上面的矩阵 A 和 B 并执行上述运算(称为 matmultsubtract),我们会得到,

tf.matmultsubtract(B,A) 给出:

[[(-1+1)2+(-3+1)2+(-1+4)2, (-1+1)2+(-3+2)2+(-1+3)2,...],

[(-2+1)2+(-1+1)2+(-1+4)2, ( -2+1)2+(-1+2)2+(-1+3)2, ...]]

如果通过手动迭代而不是 np.matmult 来使用 numpy 数组(您可以使用两个嵌套的 for 循环),这并不难,但是 tensorflow 的 for 循环有问题,我不知道该怎么做.

感谢您的帮助。

最佳答案

尝试可能不被视为矩阵减法的矢量化运算。

# shape=(2,3,6)
B_new = tf.tile(tf.expand_dims(B,axis=-1),multiples=[1,1,A.shape[1]])
# shape=(2,3,6)
A_new = tf.tile(tf.expand_dims(A,axis=0),multiples=[B.shape[0],1,1])
# shape=(2,6)
result = tf.reduce_sum(tf.square(A_new - B_new),axis=1)
with tf.Session() as sess:
    print(sess.run(result))

[[13  5  1  2 33 25]
 [10  6  6  9 42 42]]

关于python - tensorflow 中的矩阵减法类似于矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53952470/

相关文章:

c++ - 在 DX11 中缩放广告牌矩阵

javascript - html5矩阵变换的功能

python - 如何从 OpenVPN 中提取客户端证书信息?

python - 如何在 Python 中加载 Bloomberg Live 曲线

python - 无法使用 tf.reduce_sum() 优化,但使用 tf.reduce_mean() 成功

python - 导入错误 : cannot import name '_get_logger' Niftynet

python - Python 究竟是如何检查列表的?

python - 如何编写注册账户测试用例?

python-3.x - tensorflow 中的 'tf.contrib.rnn.DropoutWrapper' ' 到底是做什么的? (三个关键问题)

c - 未正确读取矩阵