本文共 1920 字,大约阅读时间需要 6 分钟。
PyTorch 中的张量是一种强大的数据结构,类似于 NumPy 的 ndarray。与 NumPy 不同的是,PyTorch 张量能够在 GPU 或其他硬件加速器上运行,并且可以与 NumPy 数组共享相同的内存。这种设计使得 PyTorch 在性能和灵活性上具有显著优势。
张量可以通过多种方式初始化:
直接从数据初始化:PyTorch 可以自动从数据中推断数据类型并创建张量。
data = [[1, 2], [3, 4]]x_data = torch.tensor(data)
从 NumPy 数组初始化:张量可以从 NumPy 数组创建,反之亦然。
np_array = np.array(data)x_np = torch.from_numpy(np_array)
从另一个张量初始化:新张量会保留原张量的属性(形状、数据类型),除非显式指定。
x_ones = torch.ones_like(x_data) # 保留 x_data 的属性x_rand = torch.rand_like(x_data, dtype=torch.float) # 重写数据类型
使用随机或固定值初始化:通过指定形状来确定张量的维度。
shape = (2, 3)rand_tensor = torch.rand(shape)ones_tensor = torch.ones(shape)zeros_tensor = torch.zeros(shape)
张量的属性包括形状、数据类型和存储设备:
tensor = torch.rand(3, 4)print(f"Shape of tensor: {tensor.shape}")print(f"Datatype of tensor: {tensor.dtype}")print(f"Device tensor is stored on: {tensor.device}") 输出结果:
Shape of tensor: torch.Size([3, 4])Datatype of tensor: torch.float32Device tensor is stored on: cpu
PyTorch 提供了超过 100 个张量操作,涵盖算术、线性代数、矩阵操作等。以下是一些常见操作示例:
标准的 NumPy-like 切片和索引:
tensor = torch.ones(4, 4)print('First row: ', tensor[0])print('First column: ', tensor[:, 0])print('Last column:', tensor[..., -1])tensor[:, 1] = 0print(tensor) 张量连接:使用 torch.cat 或 torch.stack 来拼接张量。
t1 = torch.cat([tensor, tensor, tensor], dim=1)print(t1)
算术运算:包括矩阵乘法和元素-wise 相加。
y1 = tensor @ tensor.Ty2 = tensor.matmul(tensor.T)z1 = tensor * tensorz2 = tensor.mul(tensor)
单元素张量:使用 item() 方法将单元素张量转换为 Python 数值。
agg = tensor.sum()agg_item = agg.item()print(f"{agg_item} {type(agg_item)}") 就地操作:在某些情况下,可以使用就地操作来修改张量。
print(tensor, "\n")tensor.add_(5)print(tensor)
PyTorch 和 NumPy 可以互相转换,两者共享相同的内存:
t = torch.ones(5)print(f"t: {t}")n = t.numpy()print(f"n: {n}") 修改张量会反映到 NumPy 数组:
t.add_(1)print(f"t: {t}")print(f"n: {n}") PyTorch 的张量功能使其成为机器学习和深度学习中的强大工具。通过支持 GPU 加速和与 NumPy 的无缝集成,PyTorch 提供了高效灵活的数据处理能力。理解张量的初始化、属性和操作是掌握 PyTorch 的基础。
转载地址:http://ogxfk.baihongyu.com/