尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

Python-pytorch-基础入门

Python-pytorch-基础入门 PyTorch 基础入门张量Tensor 什么是张量张量Tensor是 PyTorch 的核心数据结构你可以把它理解为可以在 GPU 上加速运算的多维数组。它和 NumPy 的 ndarray 非常相似但多了三个关键能力自动求导Autograd——自动计算梯度GPU 加速——张量可以搬到 GPU 上实现百倍级提速动态计算图——每次前向传播都是一张新图调试方便术语维度示例标量Scalar0 维torch.tensor(3.14)向量Vector1 维torch.tensor([1, 2, 3])矩阵Matrix2 维torch.randn(3, 4)张量Tensor≥3 维torch.randn(2, 3, 4, 5) 创建张量importtorchimportnumpyasnp从数据创建# 从列表xtorch.tensor([1,2,3])# tensor([1, 2, 3])# 从嵌套列表2Dxtorch.tensor([[1,2],[3,4],[5,6]])# tensor([[1, 2],# [3, 4],# [5, 6]])# 从 NumPy 数组arrnp.array([1,2,3])xtorch.from_numpy(arr)# 共享内存xtorch.tensor(arr)# 复制数据# 指定数据类型xtorch.tensor([1,2,3],dtypetorch.float32)特殊张量# 全零 / 全一xtorch.zeros(3,4)# (3, 4) 的全零矩阵xtorch.ones(3,4)# (3, 4) 的全一矩阵xtorch.zeros_like(y)# 和 y 形状相同的全零# 单位矩阵xtorch.eye(3)# 3x3 单位矩阵# 未初始化效率更高但需立即赋值xtorch.empty(3,4)# 全填充xtorch.full((3,4),7)# 全为 7 的 (3, 4) 矩阵序列张量# 等差xtorch.arange(0,10,2)# tensor([0, 2, 4, 6, 8])xtorch.arange(5)# tensor([0, 1, 2, 3, 4])# 等分xtorch.linspace(0,1,5)# 0 到 1 均匀取 5 个点# tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])# 对数等分xtorch.logspace(-2,2,5)# 10^-2 到 10^2随机张量 ⭐# 均匀分布 [0, 1)xtorch.rand(3,4)# 标准正态分布 N(0, 1)xtorch.randn(3,4)# 整数随机 [low, high)xtorch.randint(0,10,(3,4))# 正态分布 N(mean, std)xtorch.normal(mean0,std1,size(3,4))# 随机排列xtorch.randperm(10)# 0-9 的随机排列# 固定随机种子可复现torch.manual_seed(42) 张量属性xtorch.randn(2,3,4)print(x.shape)# torch.Size([2, 3, 4])print(x.size())# 同上可以传入 dim: x.size(0) → 2print(x.ndim)# 维度数: 3print(x.dtype)# 数据类型: torch.float32print(x.device)# 所在设备: cpu / cuda:0print(x.numel())# 总元素数: 24print(x.requires_grad)# 是否需要梯度 数据类型dtype类型别名说明torch.float32torch.float32 位浮点默认torch.float64torch.double64 位双精度torch.float16torch.half16 位半精度torch.int64torch.long64 位整数torch.int32torch.int32 位整数torch.int8—8 位整数量化用torch.bool—布尔型torch.bfloat16—Brain 浮点训练用# 类型转换xtorch.tensor([1,2,3],dtypetorch.int64)xx.float()# → float32xx.double()# → float64xx.to(torch.float16)# → float16xx.type(torch.int32)# → int32# 创建时指定xtorch.tensor([1.0,2.0],dtypetorch.float64)⚙️ 基本运算算术运算atorch.tensor([1,2,3],dtypetorch.float32)btorch.tensor([4,5,6],dtypetorch.float32)# 逐元素运算支持广播print(ab)# tensor([5., 7., 9.])print(a-b)# tensor([-3., -3., -3.])print(a*b)# tensor([4., 10., 18.]) 逐元素乘法print(a/b)# tensor([0.2500, 0.4000, 0.5000])print(a**2)# tensor([1., 4., 9.])# 原地操作名称后带 _ 下划线a.add_(1)# a 1直接修改 aa.mul_(2)# a * 2矩阵运算Atorch.randn(3,4)Btorch.randn(4,5)# 矩阵乘法CA B# 推荐写法Ctorch.mm(A,B)# 只支持 2DCtorch.matmul(A,B)# 支持广播# 批矩阵乘法Atorch.randn(10,3,4)# batch10Btorch.randn(10,4,5)Ctorch.bmm(A,B)# (10, 3, 5)# 转置print(A.T)# 2D 转置print(A.transpose(0,1))# 交换两个维度print(A.permute(1,0,2))# 任意维度重排# 点积 / 外积v1,v2torch.randn(3),torch.randn(3)dottorch.dot(v1,v2)# 内积点积outertorch.outer(v1,v2)# 外积统计运算xtorch.randn(3,4)print(x.sum())# 所有元素求和print(x.sum(dim0))# 沿行求和压缩行→ (4,)print(x.sum(dim1))# 沿列求和压缩列→ (3,)print(x.mean())# 均值print(x.std())# 标准差print(x.var())# 方差print(x.max())# 最大值print(x.min())# 最小值print(x.argmax())# 最大值索引展平后print(x.argmax(dim1))# 每行最大值索引 → (3,)比较运算xtorch.tensor([1,2,3,4,5])print(x3)# tensor([False, False, False, True, True])print(x3)# tensor([False, False, True, False, False])print((x2)(x5))# tensor([False, False, True, True, False])print(torch.any(x3))# Trueprint(torch.all(x0))# True 索引与切片xtorch.randn(4,5)# 基本索引print(x[0])# 第 0 行 → (5,)print(x[0,1])# 第 0 行第 1 列 → 标量print(x[:,0])# 第 0 列 → (4,)# 切片print(x[:2])# 前 2 行print(x[1:3,2:4])# 行 1-2, 列 2-3print(x[::2])# 每隔一行# 高级索引indicestorch.tensor([0,2,3])print(x[indices])# 取第 0, 2, 3 行print(x[[0,2],[1,3]])# 取 (0,1) 和 (2,3) 两个元素# 布尔索引maskx0print(x[mask])# 所有 0 的元素展平为一维 形状操作xtorch.randn(2,3,4)# view / reshapeyx.view(-1,4)# 自动推导第一维 → (6, 4)yx.reshape(6,4)# 同上但 view 要求内存连续# 升维 / 降维yx.unsqueeze(0)# 在第 0 维前插入 → (1, 2, 3, 4)yx.unsqueeze(-1)# 在最后一维后插入 → (2, 3, 4, 1)yx.squeeze()# 删除所有长度为 1 的维度# 展平yx.flatten()# 完全展平 → (24,)yx.flatten(start_dim1)# 从第 1 维开始展平 → (2, 12)# 拼接与堆叠a,btorch.randn(2,3),torch.randn(2,3)ctorch.cat([a,b],dim0)# 沿 dim0 拼接 → (4, 3)ctorch.cat([a,b],dim1)# 沿 dim1 拼接 → (2, 6)ctorch.stack([a,b],dim0)# 新维度堆叠 → (2, 2, 3)# 分割chunkstorch.chunk(x,chunks3,dim1)# 均分为 3 块partstorch.split(x,split_size_or_sections2,dim0)# 每块 2 行↔️ NumPy 互转# Tensor → NumPyxtorch.randn(3,4)arrx.numpy()# CPU 上直接转换共享内存arrx.cpu().detach().numpy()# GPU 张量安全转换# NumPy → Tensorarrnp.array([1,2,3])xtorch.from_numpy(arr)# 共享内存xtorch.tensor(arr)# 复制一份新数据⚠️torch.from_numpy()和张量调用.numpy()是共享内存的改一个另一个也会变️ 设备管理# 查看可用设备print(torch.cuda.is_available())# 是否有 GPUprint(torch.cuda.device_count())# GPU 数量# 创建时指定设备xtorch.randn(3,4,devicecuda)# 直接在 GPU 上创建xtorch.randn(3,4,devicecuda:0)# 指定 GPU 编号# 移动张量xx.to(cuda)# 移到 GPUxx.cuda()# 同上xx.to(cpu)# 移回 CPUxx.cpu()# 同上# 设备无关代码devicetorch.device(cudaiftorch.cuda.is_available()elsecpu)xtorch.randn(3,4).to(device) 速查表需求代码创建列表张量torch.tensor([1, 2, 3])全零torch.zeros(3, 4)全一torch.ones(3, 4)标准正态随机torch.randn(3, 4)均匀随机torch.rand(3, 4)等差数列torch.arange(0, 10, 2)等分数列torch.linspace(0, 1, 10)矩阵乘法A B转置x.T/x.transpose(0, 1)改变形状x.view(-1, 4)/x.reshape(6, 4)插入维度x.unsqueeze(0)删除1维x.squeeze()展平x.flatten()拼接torch.cat([a, b], dim0)堆叠torch.stack([a, b], dim0)沿轴求和x.sum(dim0)NumPy→Tensortorch.from_numpy(arr)Tensor→NumPyx.numpy()移到GPUx.to(cuda)数据类型x.float()/x.long()[[pytorch-总览|← 返回总览]]
返回列表