在 PyTorch 中,size
方法和屬性用于獲取張量的維度信息。下面是它們的用法和區別:
-
node_features.size
:- 這是一個屬性(attribute ),返回一個
torch.Size
對象,表示張量的維度。這是不可調用的,因此不能直接用于獲取特定維度的大小。 - 示例:
size_attr = node_features.size print(size_attr) # 輸出: torch.Size([3, 4])
- 這是一個屬性(attribute ),返回一個
-
node_features.size()
:- 這是一個方法(method),返回一個
torch.Size
對象,本質上是一個包含張量維度的元組(tuple)。這個方法是可調用的,返回的結果與size
屬性相同。 - 示例:
size_method = node_features.size() print(size_method) # 輸出: torch.Size([3, 4])
- 這是一個方法(method),返回一個
-
node_features.size(1)
:- 這是一個方法調用,它接受一個整數參數(維度索引)并返回該維度的大小。這個方法用于直接獲取特定維度的大小。
- This is a method call that takes an integer argument (the dimension index) and returns the size of that specific dimension. This is useful for obtaining the size of a particular dimension directly.
- 示例:
size_dim1 = node_features.size(1) print(size_dim1) # 輸出: 4
總結
node_features.size
:屬性,返回維度信息作為torch.Size
對象。Attribute that returns the dimensions as a torch.Size object.node_features.size()
:方法,返回維度信息作為torch.Size
對象(與屬性相同)。node_features.size(dimension)
:方法,返回指定維度的大小。 Method that returns the size of the specified dimension.
示例使用
下面是一個完整的示例來展示用法:
import torchnode_features = torch.tensor([[1.0, 2.0, 3.0, 4.0],[2.0, 3.0, 4.0, 5.0],[3.0, 4.0, 5.0, 6.0]])# 使用 size 屬性
size_attr = node_features.size
print(f"使用 size 屬性: {size_attr}") # 輸出: 使用 size 屬性: torch.Size([3, 4])# 使用 size 方法(無參數)
size_method = node_features.size()
print(f"使用 size 方法: {size_method}") # 輸出: 使用 size 方法: torch.Size([3, 4])# 使用 size 方法(帶維度參數)
size_dim1 = node_features.size(1)
print(f"維度 1 的大小: {size_dim1}") # 輸出: 維度 1 的大小: 4
為什么能輸入 1
在 node_features.size(1)
中,參數 1
表示你想獲取張量的第 1 個維度(從 0 開始計數)。對于這個特定的張量 node_features
,它的形狀是 [3, 4]
,其中:
0
維度的大小是3
(行數)1
維度的大小是4
(列數)
因此,node_features.size(1)
返回 4
,因為第 1 個維度有 4 個元素。
使用 size 屬性: <built-in method size of Tensor object at 0x7f0254cef400>
使用 size 方法: torch.Size([3, 4])
維度 1 的大小: 4
- 打印type(size_attr)得到<class ‘builtin_function_or_method’>
- 打印type(size_method)得到<class ‘torch.Size’>
- 如果調用不存在的維度會報錯
size_dim1 = node_features.size(2)
IndexError: Dimension out of range (expected to be in range of [-2, 1], but got 2)