【发布时间】: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