如何计算张量流中张量的形状

时间:2017-04-20 19:05:00

标签: python tensorflow

为了清楚地理解张量流中的张量,我需要清楚地理解张量的形状是如何定义的。

这些是tensorflow文档中的一些示例:

3 # a rank 0 tensor; this is a scalar with shape [] [1. ,2., 3.] # a rank 1 tensor; this is a vector with shape [3] [[1., 2., 3.], [4., 5., 6.]] # a rank 2 tensor; a matrix with shape [2, 3] [[[1., 2., 3.]], [[7., 8., 9.]]] # a rank 3 tensor with shape [2, 1, 3]

以下对我的理解是否正确:

为了找到张量的形状,我们从最外面的列表开始,并计算内部的元素(或列表)的数量。这个计数是第一个维度。然后,我们对内部列表重复此过程,并找到张量的下一个维度。

如果我错了,请纠正我。

1 个答案:

答案 0 :(得分:1)

是的,您的理解是正确的。如果您有一个有效的张量,您的算法将返回张量的正确尺寸。您可以通过以下方式在python中编写它

def get_shape(arr):
    res = []
    while isinstance((arr), list):
        res.append(len(arr))
        arr = arr[0]
    return res

请注意,如果是arr的任意值,您还需要确保尺寸匹配([[1, 2, 3], [4, 5]]不是有效的张量)

相关问题