numpy.matmul()是用于矩阵乘法的函数,但是如果使用此函数对计算图求导时会遇到问题。此时可使用At operator代替numpy.matmul()来保证计算图的正确性。At operator可以表示矩阵乘法的全梯度信息,而numpy.matmul()只能表示部分信息。
代码示例:
import tensorflow as tf import numpy as np
A = tf.constant(np.random.randn(3, 4).astype(np.float32)) B = tf.constant(np.random.randn(4, 5).astype(np.float32))
C1 = np.matmul(A.numpy(), B.numpy()) print(C1)
C2 = tf.matmul(A, B, transpose_a=True, transpose_b=True) dC2dA, dC2dB = tf.gradients(C2, [A, B]) print(C2.numpy()) print(dC2dA.numpy()) print(dC2dB.numpy())