李沐动手学深度学习1——数据操作
李沐动手学深度学习,有视频、有中文电子书(含配套代码),推荐!
代码如下,pytorch的数据操作和numpy很接近,理解起来难度不大:
import torch # 创建行向量 x = torch.arange(12) # numel:返回元素总数 print(x.shape, x, x.numel()) print(x.reshape(3, 4)) # 全0、全1张量 print(torch.zeros(2, 3, 4)) print(torch.ones(2, 3, 4)) # 列表初始化张量 print(torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])) # 算术运算 x = torch.tensor([1.0, 2, 4, 8]) y = torch.tensor([2, 2, 2, 2]) print(x+y, x-y, x*y, x/y, x**y) # 指数运算 print(torch.exp(x)) # 连结张量 X = torch.arange(12, dtype=torch.float32).reshape((3, 4)) Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) print(torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1), sep="\n") # 逻辑符构建张量 print(X == Y) # 对张量求和会返回一个只有一个元素的张量 print(X.sum()) # 张量切片,冒号左右两个下标为左开右闭区间 print(X[-1], X[1:3], X[1:3, 1:3], sep="\n") # 张量元素赋值 X[2, 2] = 100 X[0:2, ] = 99 print(X) # 对已赋值的tensor变量重新赋值会导致其内存变化 # 对已赋值的tensor变量切片赋值或+=之类的原地操作(+为非原地操作)不会分配新内存 before = id(Y) Y = Y+1 print(id(Y) == before) before = id(Y) Y -= 1 print(id(Y) == before) before = id(Y) Y[:] = Y+1 print(id(Y) == before) # tensor/ndarray转换 A = X.numpy() B = torch.tensor(A) print(type(A), type(B)) # tensor转标量 a = torch.tensor([3.5]) # item函数只适用于提取单元素张量的元素 print(type(a), type(a.item()), type(float(a)))
浙公网安备 33010602011771号