您当前的位置: 首页 > 年代诗人

PyTorch都用代码段合集

2023-12-02 03:28:43

点击上图,核对考试细节

仅作学术研究社交,不都是本公众号主张,侵权联络删掉

转载于:比如说 | 极市平台

PyTorch最好的详细资料是官方HTML。本文是PyTorch特指编译支架段,在简要[1](张皓:PyTorch Cookbook)的基础上想到了一些修补,简便用于时翻查。

1

『整体配置』

新增包和发行版查询

import torch import torch.nn as nn import torchvision print(torch.曲在version曲在) print(torch.version.cuda) print(torch.backends.cudnn.version) print(torch.cuda.get_device_name(0))

可复现性

在硬件电源(CPU、GPU)不尽不尽相同时,完正因如此的可复现性能够意味着,即使随机叶子不尽相同。但是,在同一个电源上,应该意味着可复现性。具体想到法是,在处置程序开始的时候相同torch的随机叶子,同时也把numpy的随机叶子相同。

np.random.seed(0) torch.manual_seed(0) torch.cuda.manual_seed_all(0)

torch.backends.cudnn.deterministic = Truetorch.backends.cudnn.benchmark = False

DirectX另设

如果只只能一张DirectX

# Device configurationdevice = torch.device( 'cuda'iftorch.cuda.is_available else'cpu')

如果只能所选多张DirectX,比如0,1号DirectX。

import osos.environ['CUDA_VISIBLE_DEVICES'] = '0,1'

也可以在GUI开始运行编译支架时另设DirectX:

CUDA_VISIBLE_DEVICES=0,1 python train.py

扫除显存

torch.cuda.empty_cache

也可以用于在GUI重置GPU的解释器

nvidia-smi ;还有gpu-reset -i [gpu_id]

2

『Tensor处置』

标量的统计数据特性

PyTorch有9种CPU标量特性和9种GPU标量特性。

标量整体反馈

tensor = torch.randn(3,4,5)print(tensor.type) # 统计数据特性print(tensor.size) # 标量的shape,是个个位print(tensor.dim) # 等价的为数

定名标量

标量定名是一个更加精确的步骤,这样可以简便地用于等价的拼法来想到索引或其他操控,得益于了通用性、易用性,不必要出错。

# 在PyTorch 1.3此前,只能用于注解# Tensor[N, C, H, W]images = torch.randn(32, 3, 56, 56)images.sum(dim=1)images.select(dim=1, index=0)

# PyTorch 1.3之后NCHW = [‘N’, ‘C’, ‘H’, ‘W’]images = torch.randn(32, 3, 56, 56, names=NCHW)images.sum('C')images.select('C', index=0)# 也可以这么另设tensor = torch.rand(3,4,1,2,names=('C', 'N', 'H', 'W'))# 用于align_to可以对等价简便地排序tensor = tensor.align_to('N', 'C', 'H', 'W')

统计数据特性叠加

# 另设匹配特性,pytorch中会的FloatTensor远远很慢DoubleTensortorch.set_default_tensor_type(torch.FloatTensor)

# 特性叠加tensor = tensor.cudatensor = tensor.cputensor = tensor.floattensor = tensor.long

torch.Tensor与np.ndarray叠加

除了CharTensor,其他所有CPU上的标量都正因如此力支持叠加为numpy格式然后再叠加去找。

ndarray = tensor.cpu.numpytensor = torch.from_numpy(ndarray).floattensor = torch.from_numpy(ndarray.copy).float # If ndarray has negative stride.

Torch.tensor与PIL.Image叠加

# pytorch中会的标量匹配采用[N, C, H, W]的依序,并且统计数据适用范围在[0,1],只能透过转置和制度本土化# torch.Tensor -> PIL.Imageimage = PIL.Image.fromarray(torch.clamp(tensor*255, min=0, max=255).byte.permute(1,2,0).cpu.numpy)image = torchvision.transforms.functional.to_pil_image(tensor) # Equivalently way

# PIL.Image -> torch.Tensorpath = r'./figure.jpg'tensor = torch.from_numpy(np.asarray(PIL.Image.open(path))).permute(2,0,1).float / 255tensor = torchvision.transforms.functional.to_tensor(PIL.Image.open(path)) # Equivalently way

np.ndarray与PIL.Image的叠加

image = PIL.Image.fromarray(ndarray.astype(np.uint8))

ndarray = np.asarray(PIL.Image.open(path))

从只包含一个要素的标量中会提炼出值

value = torch.rand(1).item

标量拉伸

# 在将变换层叠加成正因如此连接层的情况下有时候只能对标量想到拉伸处置,# 相比torch.view,torch.reshape可以终端处置叠加成标量不连续的情况。tensor = torch.rand(2,3,4)shape = (6, 4)tensor = torch.reshape(tensor, shape)

打乱依序

tensor = tensor[torch.randperm(tensor.size(0))] # 打乱第一个等价

总体反转

# pytorch不正因如此力支持tensor[::-1]这样的负步长操控,总体反转可以通过标量索引解决问题# 假设标量的等价为[N, D, H, W].tensor = tensor[:,:,:,torch.arange(tensor.size(3) - 1, -1, -1).long]

br

粘贴标量

# Operation | New/Shared memory | Still in computation graph |tensor.clone # | New | Yes |tensor.detach # | Shared | No |tensor.detach.clone # | New | No |

br

标量拼接

'''请注意torch.cat和torch.stack的区别在于torch.cat沿着给定的等价拼接,而torch.stack才会新增给定。例如当值是3个10x5的标量,torch.cat的结果是30x5的标量,而torch.stack的结果是3x10x5的标量。'''tensor = torch.cat(list_of_tensors, dim=0)tensor = torch.stack(list_of_tensors, dim=0)

将整数附加转为one-hot编码

# pytorch的标示匹配从0开始tensor = torch.tensor([0, 2, 1, 3])N = tensor.size(0)num_classes = 4one_hot = torch.zeros(N, num_classes).longone_hot.scatter_(dim=1, index=torch.unsqueeze(tensor, dim=1), src=torch.ones(N, num_classes).long)

得不到非零要素

torch.nonzero(tensor) # index of non-zero elementstorch.nonzero(tensor==0) # index of zero elementstorch.nonzero(tensor).size(0) # number of non-zero elementstorch.nonzero(tensor == 0).size(0) # number of zero elements

判断两个标量相等

torch.allclose(tensor1, tensor2) # float tensortorch.equal(tensor1, tensor2) # int tensor

标量拓展

# Expand tensor of shape 64*512 to shape 64*512*7*7.tensor = torch.rand(64,512)torch.reshape(tensor, (64, 512, 1, 1)).expand(64, 512, 7, 7)

行列式自然数

# Matrix multiplcation: (m*n) * (n*p) * -> (m*p).result = torch.mm(tensor1, tensor2)

# Batch matrix multiplication: (b*m*n) * (b*n*p) -> (b*m*p)result = torch.bmm(tensor1, tensor2)

# Element-wise multiplication.result = tensor1 * tensor2

近似值三组统计数据错综复杂的两两欧式距离

来透过broadcast前提

dist = torch.sqrt(torch.sum((X1[:,None,:] - X2) ** 2, dim=2))

3

『框架定义和操控』

一个精确两层变换局域网的范例

# convolutional neural network (2 convolutional layers)class ConvNet(nn.Module):def 曲在init曲在(self, num_classes=10):super(ConvNet, self).曲在init曲在self.layer1 = nn.Sequential(nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),nn.BatchNorm2d(16),nn.ReLU,nn.MaxPool2d(kernel_size=2, stride=2))self.layer2 = nn.Sequential(nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),nn.BatchNorm2d(32),nn.ReLU,nn.MaxPool2d(kernel_size=2, stride=2))self.fc = nn.Linear(7*7*32, num_classes)

def forward(self, x):out = self.layer1(x)out = self.layer2(out)out = out.reshape(out.size(0), -1)out = self.fc(out)return out

model = ConvNet(num_classes).to(device)

双差分汇合(bilinear pooling)

X = torch.reshape(N, D, H * W) # Assume X has shape N*D*H*WX = torch.bmm(X, torch.transpose(X, 1, 2)) / (H * W) # Bilinear poolingassert X.size == (N, D, D)X = torch.reshape(X, (N, D * D))X = torch.sign(X) * torch.sqrt(torch.abs(X) + 1e-5) # Signed-sqrt normalizationX = torch.nn.functional.normalize(X) # L2 normalization

多卡不间断 BN(Batch normalization)

当用于 torch.nn.DataParallel 将编译支架开始运行在多张 GPU 卡上时,PyTorch 的 BN 层匹配操控是各卡上统计数据独立地近似值平方根和加权,不间断 BN 用于所有卡上的统计数据两兄弟近似值 BN 层的平方根和加权,缓解了当批量尺寸(batch size)比较同一时间对平方根和加权推估不准的情况,是在目的探测等任务中会一个有效的提升性能的高难度。

sync_bn = torch.nn.SyncBatchNorm(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)

将较早局域网的所有BN层改名不间断BN层

def convertBNtoSyncBN(module, process_group=None):'''Recursively replace all BN layers to SyncBN layer.

Args:module[torch.nn.Module]. Network'''if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):sync_bn = torch.nn.SyncBatchNorm(module.num_features, module.eps, module.momentum, module.affine, module.track_running_stats, process_group)sync_bn.running_mean = module.running_meansync_bn.running_var = module.running_varif module.affine:sync_bn.weight = module.weight.clone.detachsync_bn.bias = module.bias.clone.detachreturn sync_bnelse:for name, child_module in module.named_children:setattr(module, name) = convert_syncbn_model(child_module, process_group=process_group))return module

多种不同 BN 滑动平均

如果要解决问题多种不同 BN 滑动平均的操控,在 forward 表达式中会要用于原地(inplace)操控给滑动平均赋值。

class BN(torch.nn.Module)def 曲在init曲在(self):...self.register_buffer('running_mean', torch.zeros(num_features))

def forward(self, X):...self.running_mean += momentum * (current - self.running_mean)

近似值框架整体值量

num_parameters = sum(torch.numel(parameter) for parameter in model.parameters)

核对局域网中会的值

可以通过model.state_dict或者model.named_parameters表达式核对那时候的正因如此部可体能训练值(除此以外通过传给得不到的父类中会的值)

params = list(model.named_parameters)(name, param) = params[28]print(name)print(param.grad)print(';还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有-')(name2, param2) = params[29]print(name2)print(param2.grad)print(';还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有')(name1, param1) = params[30]print(name1)print(param1.grad)

框架统计数据处置(用于pytorchviz)

szagoruyko/pytorchvizgithub.com

多种不同 Keras 的 model.summary 反向框架反馈,用于pytorch-summary

sksq96/pytorch-summarygithub.com

框架二阶初始本土化

请注意 model.modules 和 model.children 的区别:model.modules 才会插值地二叉树框架的所有子层,而 model.children 只才会二叉树框架下的一层。

# Common practise for initialization.for layer in model.modules:if isinstance(layer, torch.nn.Conv2d):torch.nn.init.kaiming_normal_(layer.weight, mode='fan_out',nonlinearity='relu')if layer.bias is not None:torch.nn.init.constant_(layer.bias, val=0.0)elif isinstance(layer, torch.nn.BatchNorm2d):torch.nn.init.constant_(layer.weight, val=1.0)torch.nn.init.constant_(layer.bias, val=0.0)elif isinstance(layer, torch.nn.Linear):torch.nn.init.xavier_normal_(layer.weight)if layer.bias is not None:torch.nn.init.constant_(layer.bias, val=0.0)

# Initialization with given tensor.layer.weight = torch.nn.Parameter(tensor)

提炼出框架中会的某一层

modules才会离开框架中会所有接口的插值支架,它能够访问到最包覆,比如self.layer1.conv1这个接口,还有一个与它们相对应的是name_children一般来说以及named_modules,这两个不仅才会离开接口的插值支架,还才会离开局域网层的拼法。

# 取框架中会的前两层new_model = nn.Sequential(*list(model.children)[:2] # 如果希望提炼出出框架中会的所有变换层,可以像后面这样操控:for layer in model.named_modules:if isinstance(layer[1],nn.Conv2d):conv_model.add_module(layer[0],layer[1])

之外层用于实体能训练框架

请注意如果留存的框架是 torch.nn.DataParallel,则也就是说的框架也只能是

model.load_state_dict(torch.load('model.pth'), strict=False)

将在 GPU 留存的框架加载到 CPU

model.load_state_dict(torch.load('model.pth', map_location='cpu'))

新增另一个框架的不尽相同之外到属于自己框架

框架新增值时,如果两个框架结构不赞同,则直接新增值才会报错。用后面步骤可以把另一个框架的不尽相同的之外新增到属于自己框架中会。

# model_new都是属于自己框架# model_saved都是其他框架,比如用torch.load新增的已留存的框架model_new_dict = model_new.state_dictmodel_common_dict = {k:v for k, v in model_saved.items if k in model_new_dict.keys}model_new_dict.update(model_common_dict)model_new.load_state_dict(model_new_dict)

4

『统计数据处置』

近似值统计数据集的平方根和加权

import osimport cv2import numpy as npfrom torch.utils.data import Datasetfrom PIL import Image

def compute_mean_and_std(dataset):# 叠加成PyTorch的dataset,反向平方根和加权mean_r = 0mean_g = 0mean_b = 0

for img, _ in dataset:img = np.asarray(img) # change PIL Image to numpy arraymean_b += np.mean(img[:, :, 0])mean_g += np.mean(img[:, :, 1])mean_r += np.mean(img[:, :, 2])

mean_b /= len(dataset)mean_g /= len(dataset)mean_r /= len(dataset)

diff_r = 0diff_g = 0diff_b = 0

N = 0

for img, _ in dataset:img = np.asarray(img)

diff_b += np.sum(np.power(img[:, :, 0] - mean_b, 2))diff_g += np.sum(np.power(img[:, :, 1] - mean_g, 2))diff_r += np.sum(np.power(img[:, :, 2] - mean_r, 2))

N += np.prod(img[:, :, 0].shape)

std_b = np.sqrt(diff_b / N)std_g = np.sqrt(diff_g / N)std_r = np.sqrt(diff_r / N)

mean = (mean_b.item / 255.0, mean_g.item / 255.0, mean_r.item / 255.0)std = (std_b.item / 255.0, std_g.item / 255.0, std_r.item / 255.0)return mean, std

得不到视频统计数据整体反馈

import cv2video = cv2.VideoCapture(mp4_path)height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))num_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))fps = int(video.get(cv2.CAP_PROP_FPS))video.release

TSN 每段(segment)滤波一帧视频

K = self._num_segmentsif is_train:if num_frames> K:# Random index for each segment.frame_indices = torch.randint(high=num_frames // K, size=(K,), dtype=torch.long)frame_indices += num_frames // K * torch.arange(K)else:frame_indices = torch.randint(high=num_frames, size=(K - num_frames,), dtype=torch.long)frame_indices = torch.sort(torch.cat((torch.arange(num_frames), frame_indices)))[0]else:if num_frames> K:# Middle index for each segment.frame_indices = num_frames / K // 2frame_indices += num_frames // K * torch.arange(K)else:frame_indices = torch.sort(torch.cat(( torch.arange(num_frames), torch.arange(K - num_frames))))[0]assert frame_indices.size == (K,)return [frame_indices[i] for i in range(K)]

特指体能训练和有效性统计数据实处置

其中会 ToTensor 操控才会将 PIL.Image 或形状为 H×W×D,参数适用范围为 [0, 255] 的 np.ndarray 叠加为形状为 D×H×W,参数适用范围为 [0.0, 1.0] 的 torch.Tensor。

train_transform = torchvision.transforms.Compose([torchvision.transforms.RandomResizedCrop(size= 224, scale=( 0.08, 1.0)), torchvision.transforms.RandomHorizontalFlip,torchvision.transforms.ToTensor,torchvision.transforms.Normalize(mean=( 0.485, 0.456, 0.406), std=( 0.229, 0.224, 0.225)), ])val_transform = torchvision.transforms.Compose([torchvision.transforms.Resize( 256), torchvision.transforms.CenterCrop( 224), torchvision.transforms.ToTensor,torchvision.transforms.Normalize(mean=( 0.485, 0.456, 0.406), std=( 0.229, 0.224, 0.225)), ])

5

『框架体能训练和测试』

分类框架体能训练编译支架

# Loss and optimizercriterion = nn.CrossEntropyLossoptimizer = torch.optim.Adam(model.parameters, lr=learning_rate)

# Train the modeltotal_step = len(train_loader)for epoch in range(num_epochs):for i ,(images, labels) in enumerate(train_loader):images = images.to(device)labels = labels.to(device)

# Forward passoutputs = model(images)loss = criterion(outputs, labels)

# Backward and optimizeroptimizer.zero_gradloss.backwardoptimizer.step

if (i+1) % 100 == 0:print('Epoch: [{}/{}], Step: [{}/{}], Loss: {}'.format(epoch+1, num_epochs, i+1, total_step, loss.item))

分类框架测试编译支架

# Test the modelmodel.eval # eval mode(batch norm uses moving mean/variance #instead of mini-batch mean/variance)with torch.no_grad:correct = 0total = 0for images, labels in test_loader:images = images.to(device)labels = labels.to(device)outputs = model(images)_, predicted = torch.max(outputs.data, 1)total += labels.size(0)correct += (predicted == labels).sum.item

print('Test accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))

定制loss

传给torch.nn.Module类写自己的loss。

class MyLoss(torch.nn.Moudle):def 曲在init曲在(self):super(MyLoss, self).曲在init曲在

def forward(self, x, y):loss = torch.mean((x - y) ** 2)return loss

附加纹理(label smoothing)

写一个label_smoothing.py的文件,然后在体能训练编译支架之中引用,用LSR代替交叉熵损失均可。label_smoothing.py细节如下:

import torchimport torch.nn as nn

class LSR(nn.Module):

def 曲在init曲在(self, e=0.1, reduction='mean'):super.曲在init曲在

self.log_softmax = nn.LogSoftmax(dim=1)self.e = eself.reduction = reduction

def _one_hot(self, labels, classes, value=1):"""Convert labels to one hot vectors

Args:labels: torch tensor in format [label1, label2, label3, ...]classes: int, number of classesvalue: label value in one hot vector, default to 1

Returns:return one hot format labels in shape [batchsize, classes]"""

one_hot = torch.zeros(labels.size(0), classes)

#labels and value_added size must matchlabels = labels.view(labels.size(0), -1)value_added = torch.Tensor(labels.size(0), 1).fill_(value)

value_added = value_added.to(labels.device)one_hot = one_hot.to(labels.device)

one_hot.scatter_add_(1, labels, value_added)

return one_hot

def _smooth_label(self, target, length, smooth_factor):"""convert targets to one-hot format, and smooththem.Args:target: target in form with [label1, label2, label_batchsize]length: length of one-hot format(number of classes)smooth_factor: smooth factor for label smooth

Returns:smoothed labels in one hot format"""one_hot = self._one_hot(target, length, value=1 - smooth_factor)one_hot += smooth_factor / (length - 1)

return one_hot.to(target.device)

def forward(self, x, target):

if x.size(0) != target.size(0):raise ValueError('Expected input batchsize ({}) to match target batch_size({})'.format(x.size(0), target.size(0)))

if x.dim < 2:raise ValueError('Expected input tensor to have least 2 dimensions(got {})'.format(x.size(0)))

if x.dim != 2:raise ValueError('Only 2 dimension tensor are implemented, (got {})'.format(x.size))

smoothed_target = self._smooth_label(target, x.size(1), self.e)x = self.log_softmax(x)loss = torch.sum(- x * smoothed_target, dim=1)

if self.reduction == 'none':return loss

elif self.reduction == 'sum':return torch.sum(loss)

elif self.reduction == 'mean':return torch.mean(loss)

else:raise ValueError('unrecognized option, expect reduction to be one of none, mean, sum')

或者直接在体能训练文件之中想到label smoothing

for images, labels in train_loader:images, labels = images.cuda, labels.cudaN = labels.size(0)# C is the number of classes.smoothed_labels = torch.full(size=(N, C), fill_value=0.1 / (C - 1)).cudasmoothed_labels.scatter_(dim=1, index=torch.unsqueeze(labels, dim=1), value=0.9)

score = model(images)log_prob = torch.nn.functional.log_softmax(score, dim=1)loss = -torch.sum(log_prob * smoothed_labels) / Noptimizer.zero_gradloss.backwardoptimizer.step

Mixup体能训练

beta_distribution = torch.distributions.beta.Beta(alpha, alpha)for images, labels in train_loader:images, labels = images.cuda, labels.cuda

# Mixup images and labels.lambda_ = beta_distribution.sample([]).itemindex = torch.randperm(images.size(0)).cudamixed_images = lambda_ * images + (1 - lambda_) * images[index, :]label_a, label_b = labels, labels[index]

# Mixup loss.scores = model(mixed_images)loss = (lambda_ * loss_function(scores, label_a)+ (1 - lambda_) * loss_function(scores, label_b))optimizer.zero_gradloss.backwardoptimizer.step

L1 下述本土化

l1_regularization = torch.nn.L1Loss(reduction='sum')loss = ... # Standard cross-entropy lossfor param in model.parameters:loss += torch.sum(torch.abs(param))loss.backward

不对回授项透过二阶震荡(weight decay)

pytorch之中的weight decay相当于l2下述

bias_list = (param for name, param in model.named_parameters if name[-4:] == 'bias')others_list = (param for name, param in model.named_parameters if name[-4:] != 'bias')parameters = [{'parameters': bias_list, 'weight_decay': 0}, {'parameters': others_list}]optimizer = torch.optim.SGD(parameters, lr=1e-2, momentum=0.9, weight_decay=1e-4)

温度梯度拼接(gradient clipping)

torch.nn.utils.clip_grad_norm_(model.parameters, max_norm=20)

得不到也就是说努力学习所部

# If there is one global learning rate (which is the common case).lr = next(iter(optimizer.param_groups))['lr']

# If there are multiple learning rates for different layers.all_lr = []for param_group in optimizer.param_groups:all_lr.append(param_group['lr'])

另一种步骤,在一个batch体能训练编译支架之中,也就是说的lr是optimizer.param_groups[0]['lr']

努力学习所部震荡

# Reduce learning rate when validation accuarcy plateau.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', patience=5, verbose=True)for t in range(0, 80):train(...)val(...)scheduler.step(val_acc)

# Cosine annealing learning rate.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=80)# Reduce learning rate by 10 at given epochs.scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[50, 70], gamma=0.1)for t in range(0, 80):scheduler.step train(...)val(...)

# Learning rate warmup by 10 epochs.scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda t: t / 10)for t in range(0, 10):scheduler.steptrain(...)val(...)

最优本土化支架链式更加新

从1.4发行版开始,torch.optim.lr_scheduler 正因如此力支持链式更加新(chaining),即Gmail可以定义两个 schedulers,并交替在体能训练中会用于。

import torchfrom torch.optim import SGDfrom torch.optim.lr_scheduler import ExponentialLR, StepLRmodel = [torch.nn.Parameter(torch.randn(2, 2, requires_grad=True))]optimizer = SGD(model, 0.1)scheduler1 = ExponentialLR(optimizer, gamma=0.9)scheduler2 = StepLR(optimizer, step_size=3, gamma=0.1)for epoch in range(4):print(epoch, scheduler2.get_last_lr[0])optimizer.stepscheduler1.stepscheduler2.step

框架体能训练统计数据处置

PyTorch可以用于tensorboard来统计数据处置体能训练过程。

安装和开始运行TensorBoard。

pip install tensorboardtensorboard ;还有logdir=runs

用于SummaryWriter类来采集和统计数据处置反之亦然的统计数据,放了简便核对,可以用于不尽不尽相同的页面,比如'Loss/train'和'Loss/test'。

from torch.utils.tensorboard import SummaryWriterimport numpy as np

writer = SummaryWriter

for n_iter in range(100):writer.add_scalar('Loss/train', np.random.random, n_iter)writer.add_scalar('Loss/test', np.random.random, n_iter)writer.add_scalar('Accuracy/train', np.random.random, n_iter)writer.add_scalar('Accuracy/test', np.random.random, n_iter)

留存与加载断点

请注意为了能够恢复体能训练,我们只能同时留存框架和最优本土化支架的稳定状态,以及也就是说的体能训练轮数。

提炼出 ImageNet 实体能训练框架某层的变换形态

# VGG-16 relu5-3 feature.model = torchvision.models.vgg16(pretrained=True).features[:-1]# VGG-16 pool5 feature.model = torchvision.models.vgg16(pretrained=True).features# VGG-16 fc7 feature.model = torchvision.models.vgg16(pretrained=True)model.classifier = torch.nn.Sequential(*list(model.classifier.children)[:-3])# ResNet GAP feature.model = torchvision.models.resnet18(pretrained=True)model = torch.nn.Sequential(collections.OrderedDict(list(model.named_children)[:-1]))

with torch.no_grad:model.evalconv_representation = model(image)

提炼出 ImageNet 实体能训练框架多层的变换形态

class FeatureExtractor(torch.nn.Module):"""Helper class to extract several convolution features from the givenpre-trained model.

Attributes:_model, torch.nn.Module._layers_to_extract, list or set

Example:>>> model = torchvision.models.resnet152(pretrained=True)>>> model = torch.nn.Sequential(collections.OrderedDict(list(model.named_children)[:-1]))>>> conv_representation = FeatureExtractor(pretrained_model=model,layers_to_extract={'layer1', 'layer2', 'layer3', 'layer4'})(image)"""def 曲在init曲在(self, pretrained_model, layers_to_extract):torch.nn.Module.曲在init曲在(self)self._model = pretrained_modelself._model.evalself._layers_to_extract = set(layers_to_extract)

def forward(self, x):with torch.no_grad:conv_representation = []for name, layer in self._model.named_children:x = layer(x)if name in self._layers_to_extract:conv_representation.append(x)return conv_representation

这两项正因如此连接层

model = torchvision.models.resnet18(pretrained=True)for param in model.parameters:param.requires_grad = Falsemodel.fc = nn.Linear(512, 100) # Replace the last fc layeroptimizer = torch.optim.SGD(model.fc.parameters, lr=1e-2, momentum=0.9, weight_decay=1e-4)

以较小努力学习所部这两项正因如此连接层,较小努力学习所部这两项变换层

model = torchvision.models.resnet18(pretrained= True) finetuned_parameters = list(map(id, model.fc.parameters))conv_parameters = (p forp inmodel.parameters ifid(p) notinfinetuned_parameters) parameters = [{ 'params': conv_parameters, 'lr': 1e-3}, { 'params': model.fc.parameters}] optimizer = torch.optim.SGD(parameters, lr= 1e-2, momentum= 0.9, weight_decay= 1e-4)

6

『其他请注意事项』

绝须要于太大的差分层。因为nn.Linear(m,n)用于的是O(mn)的内存,差分层太大很不易大于现有显存。

绝不在过长的序列上用于RNN。因为RNN反向传播用于的是BPTT算法,其只能的内存和叠加成序列的长度方形差分关系。

model(x) 前用 model.train 和 model.eval 切换局域网稳定状态。

不只能近似值温度梯度的编译支架块用 with torch.no_grad 包含出去。

model.eval 和 torch.no_grad 的区别在于,model.eval 是将局域网切换为测试稳定状态,例如 BN 和dropout在体能训练和测试版用于不尽不尽相同的近似值步骤。torch.no_grad 是关闭 PyTorch 标量的终端切线前提,以减缓加载用于和加速近似值,得不到的结果能够透过 loss.backward。

model.zero_grad才会把整个框架的值的温度梯度都归零, 而optimizer.zero_grad只才会把传入其中会的值的温度梯度归零.

torch.nn.CrossEntropyLoss 的叠加成不只能经过 Softmax。torch.nn.CrossEntropyLoss 等价于 torch.nn.functional.log_softmax + torch.nn.NLLLoss。

loss.backward 前用 optimizer.zero_grad 扫除再加温度梯度。

torch.utils.data.DataLoader 中会尽量另设 pin_memory=True,对特别小的统计数据集如 MNIST 另设 pin_memory=False 反而更加快一些。num_workers 的另设只能在实验中会看到极快的取值。

用 del 及时删掉须要的中会间表达式,减省 GPU 加载。

用于 inplace 操控可减省 GPU 加载,如

x = torch.nn.functional.relu(x, inplace=True)

减缓 CPU 和 GPU 错综复杂的统计数据数据传输。例如如果你想知道一个 epoch 中会每个 mini-batch 的 loss 和准确所部,必先将它们再加在 GPU 中会等一个 epoch 落幕之后两兄弟数据传输回 CPU 才会比每个 mini-batch 都透过一次 GPU 到 CPU 的数据传输更加快。

用于半精确度二进制 half 才会有一定的低速提升,具体效所部意味着 GPU 标准型。只能小心参数精确度过低带来的稳定性原因。

时特指于 assert tensor.size == (N, D, H, W) 作为复用手段,确保标量等价和你设想中会赞同。

除了标示 y 外,尽量少用于给定标量,用于 n*1 的二维标量代替,可以不必要一些意想不到的给定标量近似值结果。

汇总编译支架各之外用时

with torch.autograd.profiler.profile(enabled=True, use_cuda=False) as profile: ...print(profile)# 或者在GUI开始运行python -m torch.utils.bottleneck main.py

用于TorchSnooper来复用PyTorch编译支架,处置程序在指派的时候,就才会终端 print 出来每一行的指派结果的 tensor 的形状、统计数据特性、电源、是否只能温度梯度的反馈。

# pip install torchsnooperimport torchsnooper# 对于表达式,用于修饰支架@torchsnooper.snoop# 如果不是表达式,用于 with 语句来激活 TorchSnooper,把体能训练的那个循环装进 with 语句中会去。with torchsnooper.snoop: 原本的代

框架可解释性,用于captum奎:

简要

张皓:PyTorch Cookbook(特指编译支架段采集合集),

PyTorch官方HTML和范例

其他

;还有;还有;还有;还有;还有;还有;还有;还有;还有-

END

;还有;还有;还有;还有;还有;还有;还有;还有;还有;还有

心肺复苏急救培训
艾拉莫德片是治疗类风湿的吗
艾得辛和甲氨蝶呤可以一起吃吗
推荐阅读
图文聚焦