PyTorch 张量学习

PyTorch 张量学习

文章目录

什么是张量?

张量(Tensor)是PyTorch中的核心数据结构,可以理解为多维数组或矩阵的扩展。

张量的特点

  1. 多维性:张量可以有多个维度

    • 0维张量:标量(单个数字)
    • 1维张量:向量
    • 2维张量:矩阵
    • 3维及以上:更高维数组
  2. 数据类型统一:张量中的所有元素必须是相同的数据类型

  3. GPU支持:张量可以在CPU或GPU上进行计算

  4. 自动求导:PyTorch张量支持自动微分,这对深度学习至关重要

基础示例

创建一维张量

python 复制代码
import torch

# 创建一维张量
tensor = torch.tensor([10, 20, 30])
print(tensor)

从NumPy数组创建张量

python 复制代码
import numpy as np
import torch

# NumPy数组转张量
numpy_array = np.array([5, 15, 25])
tensor = torch.from_numpy(numpy_array)
print(tensor)

创建2D张量(矩阵)

2D张量(二维张量)就是矩阵,它有两个维度:行和列。

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

属性使用示例

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

综合操作示例

python 复制代码
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的重要基础。

相关推荐
Token架构师2 分钟前
给 Claude Code 套一层「进程外」策略:OpenShell 落地与审计日志分析
人工智能·安全·架构
TMT星球4 分钟前
旗舰手机的中场战事:AI为核,影像为王
人工智能·智能手机
霸道流氓气质5 分钟前
AI应用成本优化完全指南:Token压缩、语义缓存与模型路由的Java生产级实战
java·人工智能·缓存
Gu0Qiang6 分钟前
从 0 到 1 打造 AI 提示流编排器:别把大模型当机械拼图!Case #7 字段冻结陷阱与代码回滚复盘(开源系列 15)
人工智能·github
骇客野人6 分钟前
SDD AI-Native(Spec-Driven Development,规约驱动开发,AI 原生研发范式)
人工智能·ai-native
用户547455508126 分钟前
用开源的Toonflow和MiniMax H3一步步复刻万妖
人工智能
RobinDevNotes7 分钟前
JAX 分布式训练,和 PyTorch 有什么不一样
人工智能·深度学习·ajax
奕鼎竜瑆10 分钟前
[新手小白也能学会] 01-PyTorch框架使用(上)
人工智能·pytorch·python
2401_8501220411 分钟前
高温耐油热缩套管选型:材料、温度和油液要匹配
经验分享·笔记·科技·学习
用户8371332007614 分钟前
接口返回文章 ID 后,怎样确认发布真的完成了?
人工智能