PyTorch 张量学习
PyTorch 张量学习
文章目录
- PyTorch 张量学习
- 什么是张量?
- 张量的特点
- 基础示例
- 创建一维张量
- 从NumPy数组创建张量
- 创建2D张量(矩阵)
- 张量的属性
- 属性使用示例
- 张量的操作
- 基础操作
- 形状操作
- 综合操作示例
- 张量与 NumPy 的互操作
- 总结
什么是张量?
张量(Tensor)是PyTorch中的核心数据结构,可以理解为多维数组或矩阵的扩展。
张量的特点
-
多维性:张量可以有多个维度
- 0维张量:标量(单个数字)
- 1维张量:向量
- 2维张量:矩阵
- 3维及以上:更高维数组
-
数据类型统一:张量中的所有元素必须是相同的数据类型
-
GPU支持:张量可以在CPU或GPU上进行计算
-
自动求导:PyTorch张量支持自动微分,这对深度学习至关重要
基础示例
创建一维张量
import torch# 创建一维张量
tensor = torch.tensor([10, 20, 30])
print(tensor)
从NumPy数组创建张量
import numpy as np
import torch# NumPy数组转张量
numpy_array = np.array([5, 15, 25])
tensor = torch.from_numpy(numpy_array)
print(tensor)
创建2D张量(矩阵)
2D张量(二维张量)就是矩阵,它有两个维度:行和列。
import torch# 创建4x5矩阵
tensor_2d = torch.tensor([[1, 3, 5, 7, 9],[2, 4, 6, 8, 10],[11, 13, 15, 17, 19],[12, 14, 16, 18, 20]
])
print("2D Tensor:", tensor_2d)
print("Shape:", tensor_2d.shape)
张量的属性
属性 | 说明 | 示例 |
---|---|---|
.shape | 获取张量的形状 | tensor.shape |
.size() | 获取张量的形状 | tensor.size() |
.dtype | 获取张量的数据类型 | tensor.dtype |
.device | 查看张量所在的设备 (CPU/GPU) | tensor.device |
.dim() | 获取张量的维度数 | tensor.dim() |
.requires_grad | 是否启用梯度计算 | tensor.requires_grad |
.numel() | 获取张量中的元素总数 | tensor.numel() |
.is_cuda | 检查张量是否在 GPU 上 | tensor.is_cuda |
.T | 获取张量的转置(适用于 2D 张量) | tensor.T |
.item() | 获取单元素张量的值 | tensor.item() |
.is_contiguous() | 检查张量是否连续存储 | tensor.is_contiguous() |
属性使用示例
import torch# 创建2x3张量
tensor = torch.tensor([[7, 8, 9], [10, 11, 12]], dtype=torch.float32)# 基本属性
print("Tensor:", tensor)
print("Shape:", tensor.shape)
print("Size:", tensor.size())
print("Data Type:", tensor.dtype)
print("Device:", tensor.device)
print("Dimensions:", tensor.dim())
print("Total Elements:", tensor.numel())# 高级属性
print("Requires Grad:", tensor.requires_grad)
print("Is CUDA:", tensor.is_cuda)
print("Is Contiguous:", tensor.is_contiguous())# 获取单元素值
single_value = torch.tensor(42)
print("Single Element:", single_value.item())# 转置
tensor_T = tensor.T
print("Transposed:", tensor_T)
张量的操作
基础操作
操作 | 说明 | 示例代码 |
---|---|---|
+, -, *, / | 元素级加法、减法、乘法、除法 | z = x + y |
torch.matmul(x, y) | 矩阵乘法 | z = torch.matmul(x, y) |
torch.dot(x, y) | 向量点积(仅适用于 1D 张量) | z = torch.dot(x, y) |
torch.sum(x) | 求和 | z = torch.sum(x) |
torch.mean(x) | 求均值 | z = torch.mean(x) |
torch.max(x) | 求最大值 | z = torch.max(x) |
torch.min(x) | 求最小值 | z = torch.min(x) |
torch.argmax(x, dim) | 返回最大值的索引(指定维度) | z = torch.argmax(x, dim=1) |
torch.softmax(x, dim) | 计算 softmax(指定维度) | z = torch.softmax(x, dim=1) |
形状操作
操作 | 说明 | 示例代码 |
---|---|---|
x.view(shape) | 改变张量的形状(不改变数据) | z = x.view(3, 4) |
x.reshape(shape) | 类似于 view,但更灵活 | z = x.reshape(3, 4) |
x.t() | 转置矩阵 | z = x.t() |
x.unsqueeze(dim) | 在指定维度添加一个维度 | z = x.unsqueeze(0) |
x.squeeze(dim) | 去掉指定维度为 1 的维度 | z = x.squeeze(0) |
torch.cat((x, y), dim) | 按指定维度连接多个张量 | z = torch.cat((x, y), dim=1) |
综合操作示例
import torch# 创建2x3张量
tensor = torch.tensor([[15, 25, 35], [45, 55, 65]], dtype=torch.float32)
print("原始张量:", tensor)# 1. 索引和切片
print("\n索引和切片:")
print("第一行:", tensor[0])
print("第一行第一列:", tensor[0, 0])
print("第二列:", tensor[:, 1])# 2. 形状变换
print("\n形状变换:")
reshaped = tensor.view(3, 2)
print("改变形状:", reshaped)
flattened = tensor.flatten()
print("展平:", flattened)# 3. 数学运算
print("\n数学运算:")
print("加5:", tensor + 5)
print("乘3:", tensor * 3)
print("求和:", tensor.sum().item())# 4. 张量操作
print("\n张量操作:")
tensor2 = torch.tensor([[2, 2, 2], [2, 2, 2]], dtype=torch.float32)
print("矩阵乘法:", torch.matmul(tensor, tensor2.T))# 5. 条件筛选
print("\n条件筛选:")
print("大于30:", tensor[tensor > 30])
张量与 NumPy 的互操作
操作 | 说明 | 示例代码 |
---|---|---|
torch.from_numpy(ndarray) | 将 NumPy 数组转换为张量 | x = torch.from_numpy(np_array) |
x.numpy() | 将张量转换为 NumPy 数组(仅限 CPU 张量) | np_array = x.numpy() |
总结
本指南涵盖了PyTorch张量的基础知识,包括创建、属性、操作以及与NumPy的互操作。张量是深度学习的核心概念,熟练掌握张量操作是学习PyTorch的重要基础。