【深度学习】PyTorch命令笔记
- PyTorch文档
- from torchvision.transforms import transforms
- torch.backends.cudnn.benchmark
- torch.nn.Module
- torch.nn.BatchNorm2d
- torch.nn.Conv2d
- torch.nn.L1Loss
- torch.nn.LeakyReLU
- torch.nn.Linear
- torch.nn.MaxPool2d
- torch.nn.ModuleList
- torch.nn.MSELoss
- torch.nn.ReLU
- torch.nn.Sequential
- torch.nn.SmoothL1Loss
- torch.nn.Softmax
- torch.optim
- 结语
PyTorch文档
PyTorch中文文档
PyTorch documentation
from torchvision.transforms import transforms
PyTorch的图片变换方法
对PIL.Image进行变换
transforms.CenterCrop(size)
将给定的PIL.Image进行中心切割,得到给定的size大小的中心区域
transforms.CenterCrop(size)(image)
- size是tuple:(target_height, target_width)
- size是Integer:(size, size)
- image:PIL.Image
- 返回切割后的PIL.Image
类型转换
transforms.ToTensor
将PIL图片或者ndarray转换成Tensor
将PIL图片或者numpy.ndarray(h, w, c)(数值范围[0, 255])转换成(c, h, w)(数值范围[0.0, 1.0])的浮点型Tensor
// 用例
data = np.random.randint(0, 255, size=300)
img = data.reshape(10,10,3)
print(img.shape)
img_tensor = transforms.ToTensor()(img)
print(img_tensor)
Compose
将多个变换方式结合在一起
transforms.Compose([transforms.ToTensor(), transforms.CenterCrop(size), ...])(image)
torch.backends.cudnn.benchmark
如果网络的输入数据维度或类型固定,设置该标志可以增加运行效率
torch.backends.cudnn.benchmark = True
torch.nn.Module
自定义层或网络必须继承torch.nn.Module,并且在其构造函数中需调用torch.nn.Module的构造函数,即:
class MyNet(nn.Module):
def __init__(self, ...):
super(MyNet, self).__init__()
或:
class MyNet(nn.Module):
def __init__(self, ...):
nn.Module.__init__(self)
除此之外,还需要在自定义层或网络的类中实现forward方法
把网络中具有可学习参数的层放在构造函数__init__()中,不具有可学习参数的层(如ReLU)可放在构造函数中,或在forward中使用nn.functional来代替
只要在nn.Module的子类中定义了forward函数,backward函数就会被自动实现
torch.nn.Module.load_state_dict(torch.load(".pt file path", map_location=))
加载模型
- cpu -> cpu 或 gpu -> 同一个gpu
checkpoint = torch.load(".pt file path")
model.load_state_dict(checkpoint)
// model 是继承了nn.Module的子类
- gpu -> cpu
checkpoint = torch.load(".pt file path", map_location="cpu")
model.load_state_dict(checkpoint)
// model 是继承了nn.Module的子类
- cpu -> gpu编号0
checkpoint = torch.load(".pt file path", map_location=lambda storage, loc: storage.cuda(0))
model.load_state_dict(checkpoint)
// model 是继承了nn.Module的子类
- gpu编号0 -> gpu编号1
checkpoint = torch.load(".pt file path", map_location={"cuda:0":"cuda:1"})
model.load_state_dict(checkpoint)
// model 是继承了nn.Module的子类
- 另外
有时候会有如下情况:
checkpoint = torch.load(".pt file path", map_location="cpu")
model.load_state_dict(checkpoint["model"])
// model 是继承了nn.Module的子类
这是因为checkpoint是一个字典,保存的key可以自己定义。可以保存除参数信息之外的其它信息,如epoch等。
torch.nn.BatchNorm2d
torch.nn.Conv2d
torch.nn.L1Loss
torch.nn.LeakyReLU
torch.nn.Linear
torch.nn.MaxPool2d
torch.nn.ModuleList
torch.nn.MSELoss
torch.nn.ReLU
torch.nn.Sequential
torch.nn.SmoothL1Loss
torch.nn.Softmax
torch.optim
实现了各种优化算法
torch.optim.SGD
随机梯度下降算法,momentum可选
torch.optim.SGD(params, lr, momentum=0, dampening=0, weight_decay=0, nesterov=False)
- params :待优化参数的iterable或者是定义了参数组的dict
- lr:float类型,学习率
- momentum:float类型,动量因子,默认为0
- weight_decay :float类型,L2正则权重,默认为0
- dampening:float类型,动量的抑制因子,默认为0
- nesterov:bool类型,是否使用Nesterov动量,默认为False
torch.optim.lr_scheduler.MultiStepLR
按epoch时刻调整学习率
torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones, gamma=0.1)
- optimizer:优化器
- milestones:一个列表,里面是学习率要下降的epoch点
- gamma:学习率下降系数
结语
如果您有修改意见或问题,欢迎留言或者通过邮箱和我联系。
手打很辛苦,如果我的文章对您有帮助,转载请注明出处。