【PYG】 PyTorch中size方法和属性

在 PyTorch 中,size 方法和属性用于获取张量的维度信息。下面是它们的用法和区别:

  1. node_features.size

    • 这是一个属性(attribute ),返回一个 torch.Size 对象,表示张量的维度。这是不可调用的,因此不能直接用于获取特定维度的大小。

    • 示例:

      python 复制代码
      size_attr = node_features.size
      print(size_attr)  # 输出: torch.Size([3, 4])
  2. node_features.size()

    • 这是一个方法(method),返回一个 torch.Size 对象,本质上是一个包含张量维度的元组(tuple)。这个方法是可调用的,返回的结果与 size 属性相同。

    • 示例:

      python 复制代码
      size_method = node_features.size()
      print(size_method)  # 输出: torch.Size([3, 4])
  3. 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.

    • 示例:

      python 复制代码
      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.

示例使用

下面是一个完整的示例来展示用法:

python 复制代码
import torch

node_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)
相关推荐
我是小杰啊4 分钟前
幻视是什么?一款用自然语言搜索图片与视频的 AI 视觉问答工具
人工智能·计算机视觉·多模态·ai应用·视频搜索
就是一顿骚操作12 分钟前
神经网络可解释性积木:从特征可视化到归因地图
人工智能·深度学习·神经网络
kisshyshy12 分钟前
从无崖子到OpenAI:大模型间的“传功”,动了谁的奶酪?
人工智能·深度学习·设计模式
起予者汝也14 分钟前
Python 数据结构
开发语言·数据结构·python
LadenKiller15 分钟前
2026年量化工具增量,放回回测模拟实盘阶段判断
人工智能·python
用户4718444077515 分钟前
强化学习-从零定制强化学习环境:GridWorld 悬崖行走 + PPO 训练全解析
人工智能
不爱记笔记16 分钟前
音视频内容如何纳入Obsidian知识库?分享一套完整的输入层解决方案
人工智能·ai·chatgpt·音视频·知识库·知识管理·obsidian
茶马古道的搬运工17 分钟前
AI 深度技能之-解读OpenHuman(一)- Rust 写的个人 Agent 操作系统
人工智能
集芯微电科技有限公司18 分钟前
各种大小尺寸TFT-LCD面板供电偏压电源方案IC
人工智能·单片机·嵌入式硬件·神经网络·生成对抗网络
renhongxia118 分钟前
Scaling Law撞墙了吗?大模型的“规模法则”走向何方
人工智能·深度学习·机器学习·架构·机器人