本章不太重要,python基础知识,随时 gpt 就够
1. 数据操作#
节省内存:
- 运行一些操作可能会导致为新结果分配内存:
before = id(a)
a = a + b
id(a) == before
pythonFalse
python- 正确操作:
Z = torch.zeros_like(Y)
before = id(Z)
Z[:] = X + Y
id(Z) == before
pythonTrue
pythonbefore = id(X)
X += Y
id(X) == before
pythonTrue
python转换为其他Python对象:
- 将NumPy张量(ndarray)转换为Tensor张量:
A = X.numpy()
B = torch.tensor(A)
type(A), type(B)
python(numpy.ndarray, torch.Tensor)
python- 将大小为1的张量转换为Python标量:
a = torch.tensor([3.5])
a, a.item(), float(a), int(a)
python(tensor([3.5]), 3.5, 3.5, 3)
python