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

问题描述:

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

这些都是从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]

是以下矿井的理解是否正确:

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

如果我错了,请纠正我。

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

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

注意,在改编的任意值的情况下,你还需要确保的尺寸相符([[1, 2, 3], [4, 5]]不是有效的张量)