【问题标题】:Understanding L2-norm output for 3D tensor - TensorFlow2了解 3D 张量的 L2 范数输出 - TensorFlow2
【发布时间】:2021-09-29 23:31:17
【问题描述】:

对于 Python 3.8 和 TensorFlow 2.5,我有一个形状为 (3, 3, 3) 的 3-D 张量,其目标是计算三个 (3, 3) 方阵中的每一个的 L2 范数。我想出的代码是:

a = tf.random.normal(shape = (3, 3, 3))

a.shape
# TensorShape([3, 3, 3])

a.numpy()
'''
array([[[-0.30071023,  0.9958398 , -0.77897555],
        [-1.4251901 ,  0.8463568 , -0.6138699 ],
        [ 0.23176959, -2.1303613 ,  0.01905925]],

       [[-1.0487134 , -0.36724553, -1.0881581 ],
        [-0.12025198,  0.20973174, -2.1444907 ],
        [ 1.4264063 , -1.5857363 ,  0.31582597]],

       [[ 0.8316077 , -0.7645084 ,  1.5271858 ],
        [-0.95836663, -1.868056  , -0.04956183],
        [-0.16384012, -0.18928945,  1.04647   ]]], dtype=float32)
'''

我使用的是轴 = 2,因为第三轴应该包含三个 3x3 方阵。我得到的输出是:

tf.math.reduce_euclidean_norm(input_tensor = a, axis = 2).numpy()
'''
array([[1.299587 , 1.7675754, 2.1430166],
       [1.5552354, 2.158075 , 2.15614  ],
       [1.8995634, 2.1001325, 1.0759989]], dtype=float32)
'''

这些值是如何计算的? L2-norm 的计算公式是this。我错过了什么?

另外,我期待三个 L2 范数值,三个 (3, 3) 矩阵中的每一个都有一个。我必须实现的代码是:

tf.math.reduce_euclidean_norm(a[0]).numpy()
# 3.0668826

tf.math.reduce_euclidean_norm(a[1]).numpy()
# 3.4241767

tf.math.reduce_euclidean_norm(a[2]).numpy()
# 3.0293021

有没有更好的方法来获得这个而不必显式引用张量'a'的每个索引?

谢谢!

【问题讨论】:

    标签: python-3.x numpy tensorflow2.x


    【解决方案1】:

    您链接的用于计算 L2 范数的公式看起来是正确的。你所拥有的基本上是这样的:

    np.sqrt(np.sum((a[0]**2)))
    # 3.0668826
    
    np.sqrt(np.sum((a[1]**2)))
    # 3.4241767
    
    np.sqrt(np.sum((a[2]**2)))
    # 3.0293021
    

    这可以通过以下方式向量化:

    np.sqrt(np.sum(a**2, axis=(1,2)))
    

    输出:

    array([3.0668826, 3.4241767, 3.0293021], dtype=float32)
    

    这实际上与使用 np.lingalg.norm 相同(如果您想使用 tensorflow,则为 tf.math.reduce_euclidean_norm

    np.linalg.norm(a, ord=None, axis=(1,2))
    

    输出:

    array([3.0668826, 3.4241767, 3.0293021], dtype=float32)
    

    默认关键字ord=None 用于根据documentation 计算L2 范数。 axis 关键字是指定我们要减少哪些维度,这应该从第一个代码 sn-p 中明确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 2023-01-11
      • 2018-05-03
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多