pytorch常用语法

记录常用语法以备忘,记得不是很规范,主要方便自己遗忘时查阅…
本文从以下三个方面记录pytorch的常用语法,并会随着将来的使用不断更新:

  • 张量操作
  • 数据预处理
  • 网络构建
  • 可视化

1 张量操作

1.1 张量创建
  • x = torch.empty(5, 3 , dtype = torch.uint8)
  • x = torch.ones(5, 3 , dtype = torch.float64)
  • x = torch.rand(5, 3 , dtype = torch.float32, requires_grad=True)
  • x = torch.view(3,-1) # reshape x to (3,5)
  • x = torch.randn(5, 3 , dtype = torch.long)
  • x_copy = x.new_ones(5, 3 ,dtype = torch.double)
  • x_same_size = torch.randn_like(x, dtype = torch.float)
  • torch.arange(start, end, step=1, dtype=torch.int32)
  • torch.full(size, fill_value)
  • torch.normal(mean, std, out=None) #正态分布
  • x = x.unsqueeze(0) # 增加一维
1.2类型转换
  • b = a.long() # torch.int64
  • c = a.half() # torch.float16
  • d = a.int() # torch.int32
  • e = a.double() # torch.float64
  • f = a.float() # torch.float32
  • g = a.char() # torch.int8
  • h = a.byte() # torch.uint8
  • j = a.short() # torch.int16
  • c = a.type_as(c) # 转化 a 的数据格式与 c 相同
1.3 张量信息查询
  • print(x.size()) # print(x.shape)
  • print(x.dtype) #tensor.uint8 tensor.float64 ....
  • print(type(x))
  • print(x[0][2].item())
  • print(x[0][2])
1.4 张量操作
  • b = a.numpy() #numpy torch数据转换

  • a = torch.form_numpy(b)

  • ``

  • GPU设备中的运算

if torch.cuda.is_available():
	device = torch.device("cuda")
	y = torch.ones_like(x,device= device)   #直接从 GPU 创建张量
	x = x.to(device)                        #将 CPU 中变量移动到 GPU 中
	z = y + x
  • 求导相关
x = torch.rand(5, 5, requires_grad=True)
y = torch.rand(5, 5, requires_grad=True)
z=torch.sum(x+y)
z.backward(torch.ones_like(z))
print(z.grad_fn)
print(x.grad, y.grad)
with torch.no_grad():
	............
  • 反向传播
net.zero_grad()           # 反向传播前,将所有参数的梯度清零
out.backward(torch.ones(1,10))
import torch.optim
out = net(input)       		# 直接调用 forward 函数
criterion = nn.MSELoss()    # 损失函数 均方误差
loss = criterion(out, y)	# 计算 out 于 y 的均方误差
# 新建优化器
optimizer = torch.optim.SGD(net.parameters(),lr = 0.01, momentum=0.9) 
optimizer.zero_grad()     # equal to : net.zero_grad()
loss.backward()           # 反向传播
optimizer.step()		  # 更新参数

2 数据预处理

3 构建网络

3.1 优化器

常见的优化器:SGD, RMSProp,Adam,

  • import torch.optim # 优化器库
3.2 网络层
  • 卷积层
self.conv1 = torch.nn.Conv2d(in_channels, out_channels, kernel_size, 
			stride=1, padding=0, dilation=1, groups=1, bias=True)
x = self.conv1(x)
# parameters:
#		stride:(high,width)  
#       padding:(high,width)  high 上下各补0的行数,width 左右各补零的列数
#       groups: local convolution 局部卷积,然后拼起来,人脸识别常用到。  
#				eg. group=4 每个channel分成4份,各自卷积。默认为1
  • BatchNormal层
self.bn1 = torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, 
			affine=True, track_running_stats=True)
  • 池化层
  • ReLU层
  • 存储,加载网络
# 方法一,仅保持模型参数 (推荐)
torch.save(the_model.state_dict(), PATH) # PATH, .pt or .pth
# 加载
the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))
# 方法二,保存整个模型
torch.save(the_model,PATH)
# 加载
the_model = torch.load(PATH)

4 参考资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值