我有一个自定义层,我想通过自定义层的call()
方法打印未链接到返回的张量(如代码所示)的中间张量。我使用的代码是:
class Similarity(Layer):
def __init__(self, num1, num2):
super(Similarity, self).__init__()
self.num1 = num1
self.num2 = num2
# self.total = tf.Variable(initial_value=tf.zeros((16,self.num1, 1)), trainable=False)
def build(self, input_shape):
super(Similarity, self).build((None, self.num1, 1))
def compute_mask(self, inputs, mask=None):
# Just pass the received mask from previous layer, to the next layer or
# manipulate it if this layer changes the shape of the input
return mask
def call(self, inputs, mask=None):
print(">>", type(inputs), inputs.shape, inputs)
normalized = tf.nn.l2_normalize(inputs, axis = 2)
print("norm", normalized)
# multiply row i with row j using transpose
# element wise product
similarity = tf.matmul(normalized, normalized,
adjoint_b = True # transpose second matrix
)
print("SIM", similarity)
z=tf.linalg.band_part(similarity, 0, -1)*3 + tf.linalg.band_part(similarity, -1, 0)*2 - tf.linalg.band_part(similarity,0,0)*6 + tf.linalg.band_part(similarity,0,0)
# z = K.print_tensor(tf.reduce_sum(z, 2, keepdims=True))
z = tf.reduce_sum(z, 2, keepdims=True)
z = tf.argsort(z) # <----------- METHOD2: Reassigned the Z to the tensor I want to print temporarily
z = K.print_tensor(z)
print(z)
z=tf.linalg.band_part(similarity, 0, -1)*3 + tf.linalg.band_part(similarity, -1, 0)*2 - tf.linalg.band_part(similarity,0,0)*6 + tf.linalg.band_part(similarity,0,0)
z = K.print_tensor(tf.reduce_sum(z, 2, keepdims=True)) #<------------- THIS LINE WORKS/PRINTS AS Z is returned
# z = tf.reduce_sum(z, 2, keepdims=True)
@tf.function
#<------------- METHOD1: Want to print RANKT tensor but this DID NOT WORKED
def f(z):
rankt = K.print_tensor(tf.argsort(z))
# rankt = tf.reshape(rankt, (-1, self.num1))
# rankt = K.print_tensor(rankt)
return rankt
pt = f(z)
return z # <--------- The returned tensor
def compute_output_shape(self, input_shape):
print("IS", (None, self.num1, 1))
return (None, self.num1, 1)
更清楚
我使用了method1
,其中我使用了@tf.function
来打印rankt
张量,但是没有用。
第二,在method2
中,我暂时重新分配了z
(在{{1}之后返回张量),以便在call()
中执行它,并得到打印的值。之后,我将backprop
重新分配给原始操作符
总而言之,我不需要z
的值,但是我想打印一些依赖于z
的变量的值,但是我不能打印除z
答案 0 :(得分:0)
有tf.print
功能。
在急切模式下,它不返回任何内容,仅打印张量。在计算图构建期间使用时,它会返回TF运算符,这些运算符可以标识并打印张量值作为副作用。
答案 1 :(得分:0)
我已经晒了很多东西,但是找不到打印中间张量的任何东西。事实证明,我们只能打印链接到张量张量的张量(此处为z
)。所以我所做的是,我使用z
打印了K.print_tensor()
,然后使用那个张量(现在显然是列表形式)来执行我的计算(是侧面计算,而不是在逻辑中实现) )