TensorFlow:在多个维度上采用L2范数



我有一个 TensorFlow 占位符,有 4 个维度,代表一批图像。每个图像为 32 x 32 像素,每个像素有 3 个颜色通道。第一个维度表示图像的数量。

X = tf.placeholder(tf.float32, [None, 32, 32, 3])

对于每个图像,我想采用所有图像像素的 L2 范数。因此,输出应该是具有一维的张量(即每个图像一个值(。tf.norm()(文档(接受轴参数,但当我想在轴 1、2 和 3 上采用范数时,它只允许我指定最多两个轴来获取范数。我该怎么做?

n = tf.norm(X, ord=2, axis=0)          # n.get_shape() is (?, ?, 3), not (?)
n = tf.norm(X, ord=2, axis=[1,2,3])    # ValueError

您不需要另一个答案中建议的扁平化。如果您仔细阅读文档,您将看到:

axis:如果 axis 为"无"(默认值(,则输入被视为向量 并且对整个值集计算单个向量范数 张量,即范数(tensor, ord=ord(等价于 范数(reshape(tensor, [-1](, ord=ord(

例:

import tensorflow as tf
import numpy as np
c = tf.constant(np.random.rand(3, 2, 3, 6))
d = tf.norm(c, ord=2)
with tf.Session() as sess:
    print sess.run(d)

我尝试了萨尔瓦多的答案,但看起来整个小批量返回一个数字,而不是每个图像一个数字。因此,看起来我们可能坚持每个维度的规范。

import tensorflow as tf
import numpy as np
batch = tf.constant(np.random.rand(3, 2, 3, 6))
x = tf.norm(batch, axis=3)
x = tf.norm(x, axis=2)
x = tf.norm(x, axis=1)
with tf.Session() as sess:
    result = sess.run(x)
print(result)

这可能会引入少量的数值不稳定性,但从理论上讲,这与一次获取整个图像的范数相同。

您也可以考虑只在 x 轴和 y 轴上取范数,以便每个通道得到一个范数。Tensorflow支持这是有原因的,而事实并非如此。

您可以像这样自行计算 L2 范数:

tf.sqrt(tf.reduce_sum(tf.pow(images,2), axis=(1,2,3)))

最新更新