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

PyTorch 教程

从两份 CPU 随机张量开始,实际验证数据类型、形状、乘积、索引和归约。

学完这一章,你能够

  • 从两份 CPU 随机张量开始,实际验证数据类型、形状、乘积、索引和归约。

用 PyTorch 做什么

PyTorch 是开源机器学习工具,涵盖张量运算、梯度计算与模型构建。早期由 Facebook 的研究团队发起,已有计算机视觉、自然语言处理与语音等应用。先用 CPU 观察最小运算,再选择训练任务和设备。

开始前准备哪些知识

初学者可从 Python 的列表、函数和类开始。矩阵、概率和导数有助于理解张量、采样与训练,但运行本章例子只需要会在终端启动 Python。

进入应用后再区分监督、无监督和强化学习,按分类任务理解准确率、召回率及 F1。前馈网络、CNN、RNN 及 LSTM 对应不同输入结构。视觉、文本、命令行与查英文文档的经验可按需要补齐。

生成两个同形的张量

调用 torch.randn((2,3), device='cpu', dtype=torch.float32) 会从标准正态分布采样。示例用 CPU Generator 固定种子,再重建生成器验证两次采样次序。连续取得的两个张量不同,但相同环境重新设种子可复验本例。跨版本或设备的具体数值应单独比较。

从同一块数据读出多个结果

同形张量的 * 对相同坐标逐项相乘,结果形状保持 2×3。sum() 和 max() 默认跨所有维度,得到零维张量。零起点下 [1,2] 指第二行第三项。用固定矩阵核对时,总和、此索引下的值和最大值分别是 3、−5、4。

矩阵含 2、−1、3、4、0、−5,显示和 3、索引结果 −5、最大值 4。
本站根据同一个固定矩阵的三项运行结果绘制。

查阅运行版本对应的项目资料

安装说明给出平台和包版本条件。API 手册用来核对参数和返回类型,源码仓库可查看实现及版本记录。在本章程序中,以打印出的版本辨识实际使用的构建。

核对 CPU 张量的五个可观察结果

含完整源码 · 52 行
展开查看收起
python
"""Run reproducible introductory tensor operations and check independent expectations."""
import json
import math
import platform

import torch


def record(cases, name, data, action, expected, actual):
    assert expected == actual, (name, expected, actual)
    cases.append(dict(name=name, inputs=data, prerequisites="CPU PyTorch; explicitly shaped float32 input",
                      action=action, expected=expected, actual=actual, passed=True))


def main():
    cases = []
    generator = torch.Generator(device="cpu").manual_seed(31)
    a = torch.randn((2, 3), generator=generator, device="cpu", dtype=torch.float32)
    b = torch.randn((2, 3), generator=generator, device="cpu", dtype=torch.float32)
    repeat = torch.Generator(device="cpu").manual_seed(31)
    first_again = torch.randn((2, 3), generator=repeat, device="cpu", dtype=torch.float32)
    second_again = torch.randn((2, 3), generator=repeat, device="cpu", dtype=torch.float32)
    actual = [list(a.shape), a.dtype == torch.float32, a.device.type,
              bool(torch.equal(a, first_again)), bool(torch.equal(b, second_again)), not torch.equal(a, b)]
    record(cases, "seeded_normal", {"shape":[2, 3], "seed":31},
           "Draw two standard-normal arrays, then replay the generator from the same seed",
           [[2, 3], True, "cpu", True, True, True], actual)
    random_values = [a.tolist(), b.tolist()]
    actual = (a * b).tolist()
    expected = [[left * right for left, right in zip(lrow, rrow, strict=True)]
                for lrow, rrow in zip(*random_values, strict=True)]
    matches = all(math.isclose(left, right, rel_tol=1e-6)
                  for lrow, rrow in zip(expected, actual, strict=True)
                  for left, right in zip(lrow, rrow, strict=True))
    record(cases, "elementwise_product", random_values,
           "Compare every result with independent Python multiplication of the flattened inputs",
           [[2, 3], True], [list((a * b).shape), matches])
    fixed = torch.tensor([[2.0, -1.0, 3.0], [4.0, 0.0, -5.0]])
    record(cases, "tensor_sum", fixed.tolist(), "Reduce all dimensions with sum()",
           [[], 3.0], [list(fixed.sum().shape), fixed.sum().item()])
    record(cases, "zero_based_index", {"array":fixed.tolist(), "index":[1, 2]},
           "Read the second row and third column and convert the scalar using item()",
           [[], -5.0], [list(fixed[1, 2].shape), fixed[1, 2].item()])
    record(cases, "global_maximum", fixed.tolist(), "Find the maximum data value across all positions",
           4.0, fixed.max().item())
    print(json.dumps(dict(version=platform.python_version(), torch=torch.__version__,
                          system=platform.system(), cases=cases)))


if __name__ == "__main__":
    main()
重放种子能复现两份随机张量,固定矩阵的总和为 3、第二行第三列为 −5、全局最大值为 4。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:PyTorch

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

下载课程关联工程包:PyTorch

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

从 0 数起的行和列,因此是第 2 行第 3 列。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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