如何通过动手学深度学习掌握Python基础知识?

摘要:基础详解-part1 import torch x=torch.arange(12) x x.shape x.numel() #数组中元素的总数 # 修改形状 x.reshape(3,4) torch.zeros((2,3,4)) # 两层
基础详解-part1 import torch x=torch.arange(12) x x.shape x.numel() #数组中元素的总数 # 修改形状 x.reshape(3,4) torch.zeros((2,3,4)) # 两层,三行,四列 print(torch.tensor([[2,1,4,3],[1,2,3,4],[4,3,2,1]]).shape)#二维 # 两个框表示二维,三个表示三维 print(torch.tensor([[[2,1,4,3],[1,2,3,4],[4,3,2,1]]]).shape)#三维 标准算术运算 x=torch.tensor([1.0,2,4,8]) y=torch.tensor([2,2,2,2]) print(x+y) print(x-y) print(x*y) print(x/y) print(x**y) #x的y阶 print(torch.exp(x)) #计算输入张量x中每个元素的指数值;通俗讲是e的x次方(e大约等于2.71828) # 多个张量连接 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]]) torch.cat((x,y),dim=0),torch.cat((x,y),dim=1) #torch.cat((x, y), dim=0):在第0维(行)上拼接 x 和 y。这将创建一个6行4列的张量,其中前3行是 x,后3行是 y。 # torch.cat((x, y), dim=1):在第1维(列)上拼接 x 和 y。这将创建一个3行8列的张量,其中前4列是 x,后4列是 y。 x.sum() 广播机制:广播允许在某些情况下,即使数组或张量的形状不完全相同,也可以进行元素级的运算 a=torch.arange(3).reshape((3,1)) b=torch.arange(2).reshape((1,2)) print(a,b) print(a+b) x[-1],x[1:3] x[1,2]=9 x x[0:2,:]=12 x 内存问题 #id()类似于指针 before=id(y) y=y+x id(y)==before z=torch.zeros_like(y) print('id(z):',id(z)) z[:]=x+y print('id(z):',id(z)) before=id(x) x+=y id(x)==before numpy a=x.numpy() b=torch.tensor(a) type(a),type(b) # 将大小为1的张量转换为python标量 a=torch.tensor([3.5]) a,a.item(),float(a),int(a) # a.item():将张量中的单个元素转换为Python的标量值