基础详解-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) |
| 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]]) |
| torch.cat((x,y),dim=0),torch.cat((x,y),dim=1) |
| |
| |
| |
| 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 |
内存问题
| |
| 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) |
| |
| a=torch.tensor([3.5]) |
| a,a.item(),float(a),int(a) |
| |
本文作者:虾饺爱下棋
本文链接:https://www.cnblogs.com/lizhongzheng/p/18655378
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步