"""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()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
入口文件:projects/pytorch-tutorial-lab/check-tensor-operations.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
check-tensor-operations.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a446.zip