蓝色天空.知识 · 实践 · 创造
我的收藏
PyTorch 教程目录 39章
PyTorch / LEARN BY DOING

PyTorch 张量(Tensor)

逐项核对张量的构造、轴、归约、形状变换和 NumPy 共享存储条件。

学完这一章,你能够

  • 逐项核对张量的构造、轴、归约、形状变换和 NumPy 共享存储条件。

从秩和形状读懂张量

标量为 0 维,向量、矩阵分别为 1、2 维。先生成 4×5 矩阵,再用 stack 叠三个同形矩阵,得到 [3,4,5]。这里每层有 4 行 5 列。继续分别新增两个长度为 2 的轴,可到 [2,3,4,5] 和 [2,2,3,4,5]。dtype、所在设备及梯度属性也影响运行。

六列依次显示 0 到 5 维张量的实际形状。
本站按三个 stack 操作实测的形状绘制,原图状态另行登记。

选择正确的构造器

torch.tensor 用输入数据建立新张量。CPU 的可写 NumPy 数组在兼容布局下可通过 from_numpy 共享存储。ones 和 zeros 已初始化,empty 的数值需要先写入。rand 取 [0,1),randn 取标准正态样本。整数 arange 的终点排除,linspace 默认跨给定两端均匀取指定个数。

从属性和方法读出状态

shape 和 size() 表示轴长度,dim() 给出轴数,numel() 给出元素总数。直接读 dtype、device 和 requires_grad 确认条件。is_cuda 专门识别 CUDA。二维 .T 交换行列,连续矩阵转置后可能形成非连续视图。item() 只接受元素总数为 1 的张量,返回 Python 标量。

辨别逐项运算、矩阵积和归约轴

逐项运算先检查广播,矩阵乘法则要求内维相容。dot 用于两个同长向量。归约默认跨所有维度,也可指定轴。argmax 返回位置索引,多个元素并列时取首个。softmax 沿指定轴归一,在模型输入为原始分数时需要明确类别轴。行、列、布尔掩码和转平后读到的数据由下方程序对照。

核对视图和拼接条件

view 要求布局与新的步幅关系相容。reshape 在可行时用视图,否则生成副本。本站用转置矩阵实际观察 view 失败与 reshape 的读取顺序。unsqueeze 插入长度为 1 的轴,squeeze(dim) 仅移除长度为 1 的指定轴。cat 沿已有轴合并,其他轴长度要相容。

验证 NumPy 两个方向的存储关系

先检查 CUDA 是否可用,再选择 CPU 或适合的加速端。实例实测 CPU。支持布局的 CPU 张量可转为 NumPy 数组,默认接口要求张量无需梯度。先 detach 可让数据仍共享,clone 后再转可隔离原张量的写入。from_numpy 对某些步幅有限制,本例观察到倒序数组的负步幅被拒绝。

张量构造

构造器行为与条件可观察结果
torch.tensor(data)从列表或数组复制数据,可指定 dtype 和 device。改原列表或数组,结果保持原值。
torch.zeros(size)按给定形状填充 0,可指定 dtype。形状 2×3 的整型结果总和为 0。
torch.ones(size)按给定形状填充 1,可指定 dtype。形状 2×3 的浮点结果总和为 6。
torch.empty(size)分配空间,读取前应由调用者初始化。2×3 写满 2.5 后求和为 15。
torch.rand(size)生成 [0,1) 上的均匀样本。验证范围和形状。
torch.randn(size)生成标准正态样本,固定生成器可重放。同序 CPU 生成器得到相同第二次抽样。
torch.arange(start, end, step)从 start 开始按步长取值,终点 end 排除。1 到 8 步长 3 得 [1,4,7]。
torch.linspace(start, end, steps)按 steps 个样本等间隔覆盖两端。0 到 1 取 5 项,步距为 0.25。
torch.eye(n, m=None)默认建立 n×n 矩阵,主对角线为 1,其他为 0。n=3 生成 3×3 单位矩阵。
torch.from_numpy(ndarray)兼容数组与 CPU 张量共享存储。对两侧执行写入并读出。

张量元数据

表达式返回值或行为条件
tensor.shape返回 torch.Size。维度长度按轴呈现。
tensor.size()无参数时给出完整形状。可用 dim 指定某个轴。
tensor.dtype返回 torch.dtype。数值范围和精度随类型变化。
tensor.device返回实际设备标识。可比较 type 或具体设备编号。
tensor.dim()返回轴数。例如矩阵有 2 个轴。
tensor.requires_grad记录张量是否需要梯度。图记录还取决于操作和梯度模式。
tensor.numel()给出元素总数。2×3 有 6 个元素。
tensor.is_cuda布尔值,指明是否在 CUDA 设备。CPU 样本返回 False。
tensor.T二维张量交换行列。其他秩优先用 transpose 或按目标维度操作。
tensor.item()提取 Python 标量。仅允许单元素输入,多元素实测报错。
tensor.is_contiguous()报告张量是否符合所选内存格式的连续布局。普通稠密转置会改变步幅。

运算与归约

操作行为可观察结果
+、−、×、÷逐元素运算,可广播相容的轴。2×3 矩阵加长度 3 的行向量。
torch.matmul(x, y)按秩选择矩阵或批矩阵积,矩阵内维应相容。2×3 乘 3×2 得到 2×2。
torch.dot(x, y)计算两个同长一维张量的点积。样本得 37,矩阵输入报错。
torch.sum(x)可按给定轴或对所有元素求和。实测总和 15。
torch.mean(x)对浮点或复数输入求均值,可按轴。实测各行 3 和 2,整数输入需浮点 dtype。
torch.max(x)无轴时返回全局最大值,指定 dim 时同时返回位置。样本全局最大值为 8。
torch.min(x)无轴时返回全局最小值,指定 dim 时同时返回位置。样本全局最小值为 −3。
torch.argmax(x, dim)沿轴返回最大值的索引。并列最大值取第一个。
torch.softmax(x, dim)沿轴把分数归一化。极端分数的结果有限,每行和近似 1。

形状与内存

操作行为边界
x.view(shape)按新形状解释同一份存储。元素数相同且步幅相容。
x.reshape(shape)尝试返回视图,需要时复制。本例转置后转成一维得到独立存储。
x.t()二维交换行列,零维或一维返回同形。高于二维需显式选择要换的轴。
x.unsqueeze(dim)在给定位置插入长度 1 的轴。[2,3] 在第 0 轴扩为 [1,2,3]。
x.squeeze(dim)移除长度为 1 的指定轴。长于 1 的轴保持原样。
torch.cat((x, y), dim)沿已有轴拼接。两组 [2,3] 沿第 1 轴得到 [2,6]。

NumPy 转换

操作共享条件观测
torch.from_numpy(ndarray)共享受支持的 dtype 与布局。写入同步,负步幅输入报错。
x.numpy()默认要求 CPU 张量且无需梯度,类型及布局也需支持。共享时双向写入可见。独立数据可先 clone。

从单个数扩展到五维,再核对运算与存储

含完整源码 · 134 行
展开查看收起
python
"""Verify tensor constructors, operations, views and NumPy ownership on CPU."""
import json
import platform

import numpy as np
import torch


def record(cases, name, data, condition, action, expected, actual):
    assert actual == expected, (name, expected, actual)
    cases.append(dict(name=name, inputs=data, prerequisites=condition, action=action,
                      expected=expected, actual=actual, passed=True))


def rejects(operation, exception):
    try:
        operation()
    except exception:
        return True
    return False


def observe():
    cases = []
    device = torch.device("cpu")
    raw = [4, -1, 9]
    from_list = torch.tensor(raw, device=device, dtype=torch.int64)
    raw[0] = 22
    arr = np.array([3, 8], dtype=np.int64)
    copy = torch.tensor(arr)
    arr[0] = 5
    zero = torch.zeros((2, 3), dtype=torch.int32)
    ones = torch.ones((2, 3), dtype=torch.float32)
    scratch = torch.empty((2, 3), dtype=torch.float32)
    scratch.fill_(2.5)
    record(cases, "creation_initialized", {"list":[4,-1,9],"array":[3,8],"shape":[2,3]},
        "Read empty only after writing every element",
        "Compare list and array copy constructors with zeros, ones and initialized scratch space",
        [[4,-1,9],[3,8],0,6.0,[2,3],15.0],
        [from_list.tolist(),copy.tolist(),zero.sum().item(),ones.sum().item(),list(scratch.shape),scratch.sum().item()])
    rng = torch.Generator(device="cpu").manual_seed(147)
    uniform = torch.rand((2, 3), generator=rng)
    normal = torch.randn((2, 3), generator=rng)
    replay = torch.Generator(device="cpu").manual_seed(147)
    torch.rand((2, 3), generator=replay)
    again = torch.randn((2, 3), generator=replay)
    record(cases,"random_factories",{"seed":147,"size":[2,3]},"Same installed CPU generator",
        "Check the uniform interval and reproduce the second draw from the normal factory",
        [[2,3],True,[2,3],True],
        [list(uniform.shape),bool(((uniform>=0)&(uniform<1)).all()),list(normal.shape),bool(torch.equal(normal,again))])
    record(cases,"ranges_and_eye",[1,8,3],"Integral arange; explicit floating spacing for linspace",
        "Compare excluded end, included linspace ends, and square identity",
        [[1,4,7],[0.0,0.25,0.5,0.75,1.0],[[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]]],
        [torch.arange(1,8,3).tolist(),torch.linspace(0,1,5).tolist(),torch.eye(3).tolist()])

    scalar = torch.tensor(-2)
    vector = torch.arange(10)
    plane = torch.arange(20).reshape(4,5)
    cube = torch.stack((plane,plane+20,plane+40))
    fourth = torch.stack((cube,cube+60))
    fifth = torch.stack((fourth,fourth+120))
    record(cases,"ranks_zero_to_five","An arange matrix and nested stacks", "Stack adds one axis per operation",
        "Inspect size and rank for the scalar, vector, matrix and three stacks",
        [[],[10],[4,5],[3,4,5],[2,3,4,5],[2,2,3,4,5],239],
        [*[list(t.shape) for t in (scalar,vector,plane,cube,fourth,fifth)],fifth[-1,-1,-1,-1,-1].item()])

    a = torch.tensor([[2.,5.,7.],[3.,11.,13.]],requires_grad=True)
    b = torch.tensor([[2.,1.,4.],[1.,3.,2.]])
    at = a.T
    record(cases,"tensor_metadata",[[2,5,7],[3,11,13]],"Contiguous float32 CPU input with grad enabled",
        "Inspect properties, transposed layout and scalar extraction boundary",
        [[2,3],[2,3],"torch.float32","cpu",2,True,6,False,True,[[2.,3.],[5.,11.],[7.,13.]],False,11.0,True],
        [list(a.shape),list(a.size()),str(a.dtype),a.device.type,a.dim(),a.requires_grad,
         a.numel(),a.is_cuda,a.is_contiguous(),at.tolist(),at.is_contiguous(),a[1,1].item(),rejects(a.item,RuntimeError)])
    row = torch.tensor([1.,2.,4.])
    record(cases,"arithmetic_and_index",row.tolist(),"Last-axis broadcast, no zero divisors",
        "Run four operators and read row, scalar, column, flatten and boolean filter",
        [[[3.,7.,11.],[4.,13.,17.]],[[1.,3.,3.],[2.,9.,9.]],[[2.,10.,28.],[3.,22.,52.]],
         [[2.,2.5,1.75],[3.,5.5,3.25]],[2.,5.,7.],2.,[5.,11.],[2.,5.,7.,3.,11.,13.],[7.,11.,13.]],
        [(a+row).tolist(),(a-row).tolist(),(a*row).tolist(),(a/row).tolist(),
         a[0].tolist(),a[0,0].item(),a[:,1].tolist(),a.flatten().tolist(),a[a>5].tolist()])
    record(cases,"matrix_and_vector_products",b.tolist(),"Match matrix inner dimensions and one-dimensional dot inputs",
        "Compare two shapes and check that dot rejects matrices",
        [[[37.,31.],[69.,62.]],37.0,True],
        [torch.matmul(a,b.T).tolist(),torch.dot(a[0],b[0]).item(),rejects(lambda:torch.dot(a,b),RuntimeError)])
    extrema = torch.tensor([[4.,4.,1.],[-3.,8.,1.]])
    logits = torch.tensor([[1000.,1000.,1000.],[-1000.,-1001.,-1001.]])
    distribution = torch.softmax(logits,dim=1)
    record(cases,"reduce_select_and_softmax",extrema.tolist(),"Float32 data; reduce along declared dimension",
        "Check global and axis reductions, argmax tie order and stable class distribution",
        [15.,[3.,2.],8.,-3.,[0,1],[0,0],True,True,True],
        [extrema.sum().item(),extrema.mean(dim=1).tolist(),
         extrema.max().item(),extrema.min().item(),extrema.argmax(dim=1).tolist(),distribution.argmax(dim=1).tolist(),
         bool(torch.allclose(distribution.sum(dim=1),torch.ones(2))),bool(torch.isfinite(distribution).all()),
         rejects(lambda:torch.arange(3).mean(),RuntimeError)])
    direct = a.view(3,2)
    reshaped = at.reshape(-1)
    expanded = a.unsqueeze(0)
    combined = torch.cat((a,b),dim=1)
    record(cases,"shape_view_reshape_concat",list(a.shape),"Contiguous input and a deliberately incompatible transposed view",
        "Observe sharing, reshape order, failed view, squeeze/unsqueeze and concatenation",
        [[[2.,5.],[7.,3.],[11.,13.]],True,[2.,3.,5.,11.,7.,13.],True,True,True,[1,2,3],[2,3],[2,3],
         [[2.,5.,7.,2.,1.,4.],[3.,11.,13.,1.,3.,2.]]],
        [direct.tolist(),direct.data_ptr()==a.data_ptr(),reshaped.tolist(),
         reshaped.data_ptr()!=a.data_ptr(),rejects(lambda:at.view(-1),RuntimeError),bool(torch.equal(a.t(),at)),
         list(expanded.shape),list(expanded.squeeze(0).shape),list(a.squeeze(0).shape),combined.tolist()])

    parent = np.array([4.,6.,8.],dtype=np.float32)
    aliases = torch.from_numpy(parent)
    parent[1] = 22
    aliases[2] = 29
    back = aliases.numpy()
    back[0] = 17
    independent = aliases.clone().numpy()
    aliases[0] = 19
    allowed = a.detach().numpy()
    record(cases,"numpy_in_both_directions",{"array":[4,6,8],"changes":[22,29,17,19]},
        "Writable compatible NumPy storage and CPU strided tensor",
        "Observe writes in both directions, independently copy via clone and reject default gradient export",
        [[19.,22.,29.],[19.,22.,29.],[17.,22.,29.],True,[2,3],True],
        [parent.tolist(),back.tolist(),independent.tolist(),rejects(a.numpy,RuntimeError),
         list(allowed.shape),rejects(lambda:torch.from_numpy(parent[::-1]),ValueError)])
    selected = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    value = a.to(selected)
    record(cases,"device_check",str(selected),"This run uses the CPU wheel", "Check CUDA availability and the actual output device",
        [False,"cpu",True],[torch.cuda.is_available(),value.device.type,value is a])
    return cases


if __name__ == "__main__":
    print(json.dumps(dict(version=platform.python_version(),torch=torch.__version__,system=platform.system(),
                          numpy=np.__version__,cases=observe())))

叠出形状 [2,2,3,4,5],观察转置的步幅及共享写入,核对逐项、矩阵积与归约结果。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 选择对应构建并运行脚本。

下载本章实验包 (mbskycom202612a409.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a434.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

view 要用既有步幅解释同一份存储。转置改变轴顺序,原步幅可能无法按所需的一维顺序表示。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习