tensor属性

本文详细介绍了PyTorch中torch.Tensor的核心属性,包括数据类型dtype、设备device及内存布局layout。解析了不同数据类型及其对应的CPU和GPU版本,设备的指定方式,以及内存布局的概念。
部署运行你感兴趣的模型镜像

tensor attributes

每一个torch.Tensor 都有一个 torch.dtypetorch.devicetorch.layout

1、torch.dtype

torch.dtype 表示 torch.Tensor 的数据类型。PyTorch 共有9种数据类型,每种又分为CPU和GPU:

Data typedtypeCPU tensorGPU tensor
32-bit floating pointtorch.float32 or torch.floattorch.FloatTensortorch.cuda.FloatTensor
64-bit floating pointtorch.float64 or torch.doubletorch.DoubleTensortorch.cuda.DoubleTensor
16-bit floating pointtorch.float16 or torch.halftorch.HalfTensortorch.cuda.HalfTensor
8-bit integer (unsigned)torch.uint8torch.ByteTensortorch.cuda.ByteTensor
8-bit integer (signed)torch.int8torch.CharTensortorch.cuda.CharTensor
16-bit integer (signed)torch.int16 or torch.shorttorch.ShortTensortorch.cuda.ShortTensor
32-bit integer (signed)torch.int32 or torch.inttorch.IntTensortorch.cuda.IntTensor
64-bit integer (signed)torch.int64 or torch.longtorch.LongTensortorch.cuda.LongTensor
Booleantorch.booltorch.BoolTensortorch.cuda.BoolTensor

2、torch.decive

torch.device 表示分配torch.Tensor的设备。

torch.device 包含设备类型(cpu或 cuda)和可选的设备序号。若设备序号不存在,则表示该类型当前设备,即使在调用 torch.cuda.set_device() 后也是如此。例如,在‘cuda’上构建 torch.Tensor 等价于'cuda:X' ,X为 torch.cuda.current_device() 返回的结果。

torch.Tensor 的device可以通过 Tensor.device 属性访问。
torch.device 可通过字符串或字符串和序号构建。

#字符串构建

>>> torch.device('cuda:0')
device(type='cuda', index=0)

>>> torch.device('cpu')
device(type='cpu')

>>> torch.device('cuda')  # current cuda device
device(type='cuda')
#字符串和序号构建

>>> torch.device('cuda', 0)
device(type='cuda', index=0)

>>> torch.device('cpu', 0)
device(type='cpu', index=0)

注意

1.函数中的 torch.device 参数可以用字符串替换。

>> # Example of a function that takes in a torch.device
>> cuda1 = torch.device('cuda:1')
>> torch.randn((2,3), device=cuda1)
>> # You can substitute the torch.device with a string
>> torch.randn((2,3), device='cuda:1')

2.以 device 为参数的方法,通常接受一个字符串或是整型设备号作为参数。
下面三种表示方法等价:

>> torch.randn((2,3), device=torch.device('cuda:1'))
>> torch.randn((2,3), device='cuda:1')
>> torch.randn((2,3), device=1)  # legacy

3、torch.layout

torch.layout 表示 torch.Tensor 的内存布局。当前支持 torch.strided(稠密tensor)并且实验性的支持 torch.sparse__coo(稀疏COO tensor)。

torch.strided 表示稠密tensor,并且是最常用的内存布局。每个strided型的tensor都关联一个torch.Storage,后者保存数据。torch.Storage 是单个数据类型的连续一维数组。 stride是一个整数列表,第k个值表示在tensor的第k维上,从一个元素到达下一个元素在内存中所需的跳数。该概念使得可以有效地执行许多tensor操作。

示例:

>>> x = torch.Tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
>>> x.stride()
(5, 1)

>>> x.t().stride()
(1, 5)

您可能感兴趣的与本文相关的镜像

PyTorch 2.5

PyTorch 2.5

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

### PyTorch Tensor 的使用方法及功能介绍 PyTorch 是一种流行的深度学习框架,其核心数据结构是 `Tensor`。它类似于 NumPy 的 `ndarray`,但在 GPU 上运行效率更高,并且支持自动求导机制。 #### 1. 基础概念 `Tensor` 是一个多维数组,在 PyTorch 中用于存储和变换数据。可以通过多种方式创建 `Tensor` 对象[^1]。 例如: ```python import torch # 检查变量是否为 Tensor x = [2, 3, 5, 7, 4, 9] print(torch.is_tensor(x)) # 输出 False,因为 x 不是一个 Tensor 对象[^1] # 创建一个简单的 Tensor y = torch.tensor([2, 3, 5, 7, 4, 9]) print(y) # 输出 tensor([2, 3, 5, 7, 4, 9]) ``` #### 2. 创建 Tensor 的常见方法 以下是几种常见的创建 `Tensor` 的方法: - **指定尺寸初始化**:通过函数如 `ones`, `zeros`, 和 `eye` 初始化特定形状的张量。 ```python t_ones = torch.ones(2, 3) # 创建一个全为 1 的矩阵 (2x3) t_zeros = torch.zeros(2, 3) # 创建一个全为 0 的矩阵 (2x3) t_eye = torch.eye(3) # 创建单位矩阵 (3x3)[^2] ``` - **从现有数据创建**:可以从 Python 列表或 NumPy 数组中创建 `Tensor`。 ```python from_list = torch.tensor([[1, 2, 3], [4, 5, 6]]) # 从列表创建 Tensor[^4] print(from_list) import numpy as np from_numpy = torch.from_numpy(np.array([[1, 2], [3, 4]])) # 从 NumPy 数组创建 Tensor[^3][^4] print(from_numpy) ``` - **基于已有 Tensor 创建新 Tensor**:可以利用现有的 Tensor 来创建具有相同形状的新 Tensor。 ```python existing_tensor = torch.ones(3) random_tensor = torch.randn_like(existing_tensor) # 随机填充但保持相同的形状[^4] print(random_tensor) ``` #### 3. Tensor 属性 每个 `Tensor` 都有多个重要属性,包括但不限于: - `.shape`: 返回张量的维度大小。 - `.dtype`: 表示张量的数据类型。 - `.device`: 显示当前张量所在的设备(CPU 或 GPU)。 示例代码如下: ```python t = torch.rand((2, 3)) print(t.shape) # 输出 torch.Size([2, 3])[^4] print(t.dtype) # 默认情况下可能是 torch.float32 print(t.device) # 如果未显式移动到 GPU,则默认在 CPU 上 ``` #### 4. Tensor 转换与互操作性 PyTorch 提供了强大的工具来实现与其他库(尤其是 NumPy)之间的无缝转换。由于两者共享内存空间,因此这种转换非常高效。 - **NumPy 转 Tensor** ```python a_np = np.array([1, 2, 3]) a_torch = torch.from_numpy(a_np) print(a_torch) # 输出 tensor([1, 2, 3], dtype=torch.int32) ``` - **Tensor 转 NumPy** ```python b_torch = torch.ones(5) b_np = b_torch.numpy() print(b_np) # 输出 array([1., 1., 1., 1., 1.], dtype=float32) ``` 需要注意的是,当其中一个对象发生变化时,另一个会同步更新,这是因为它们共享底层内存[^2]。 #### 5. 自动求导 (`autograd`) PyTorch 的一大亮点在于它的自动求导能力。这使得神经网络训练过程中的反向传播变得简单而直观。 - 使用 `requires_grad=True` 参数启用梯度跟踪。 - 可以通过对叶子节点调用 `.backward()` 方法计算所有依赖项的梯度。 示例代码: ```python x = torch.tensor([2.0], requires_grad=True) y = x ** 2 + 3 * x + 1 y.backward() print(x.grad) # 计算并打印 y 关于 x 的导数[^3] ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值