首页 > 解决方案 > *variable.shape 在 python 中是什么意思

问题描述

我知道"*variable_name"协助打包和拆包。

但是variable_name.shape 是如何工作的呢?无法想象为什么以“”为前缀时会挤出第二个维度

print("top_class.shape {}".format(top_class.shape))
top_class.shape torch.Size([64, 1])

print("*top_class.shape {}".format(*top_class.shape))
*top_class.shape 64

标签: pythonpytorch

解决方案


因为numpy.array它广泛用于数学相关和图像处理程序,.shape描述了所有现有维度的数组大小:

>>> import numpy as np
>>> a = np.zeros((3,3,3))
>>> a
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])
>>> a.shape
(3, 3, 3)
>>> 

星号将元组“解包”成几个单独的参数,在你的情况下(64,1)变成64, 1,所以只有第一个被打印,因为只有一个格式规范。


推荐阅读