「他山之石,可以攻玉」,站在巨人的肩膀才能看得更高,走得更遠。在科研的道路上,更需藉助東風才能更快前行。為此,我們特別搜集整理了一些實用的代碼鏈接,數據集,軟件,編程技巧等,開闢「他山之石」專欄,助你乘風破浪,一路奮勇向前,敬請關注。
地址:https://zhuanlan.zhihu.com/p/59205847編輯:人工智能前沿講習
本文代碼基於PyTorch 1.0版本,需要用到以下包import collectionsimport osimport shutilimport tqdmimport numpy as npimport PIL.Imageimport torchimporttorchvision01
torch.__version__ # PyTorch versiontorch.version.cuda # Corresponding CUDA versiontorch.backends.cudnn.version() # Corresponding cuDNN versiontorch.cuda.get_device_name(0)#GPUtypePyTorch將被安裝在anaconda3/lib/python3.7/site-packages/torch/目錄下。conda update pytorch torchvision -c pytorchtorch.manual_seed(0)torch.cuda.manual_seed_all(0)CUDA_VISIBLE_DEVICES=0,1 python train.pyos.environ['CUDA_VISIBLE_DEVICES'] = '0,1'torch.cuda.is_available()Benchmark模式會提升計算速度,但是由於計算中有隨機性,每次網絡前饋結果略有差異。torch.backends.cudnn.benchmark = Truetorch.backends.cudnn.deterministic = True有時Control-C中止運行後GPU存儲沒有及時釋放,需要手動清空。在PyTorch內部可以或在命令行可以先使用ps找到程序的PID,再使用kill結束該進程ps aux | grep pythonkill -9 [pid]nvidia-smi --gpu-reset -i [gpu_id]02
tensor.type() # Data typetensor.size() # Shape of the tensor. It is a subclass of Python tupletensor.dim()#Numberofdimensions.# Set default tensor type. Float in PyTorch is much faster than double.torch.set_default_tensor_type(torch.FloatTensor)# Type convertions.tensor = tensor.cuda()tensor = tensor.cpu()tensor = tensor.float()tensor = tensor.long()torch.Tensor與np.ndarray轉換# torch.Tensor -> np.ndarray.ndarray = tensor.cpu().numpy()# np.ndarray -> torch.Tensor.tensor = torch.from_numpy(ndarray).float()tensor = torch.from_numpy(ndarray.copy()).float() # If ndarray has negative stridePyTorch中的張量默認採用N×D×H×W的順序,並且數據範圍在[0, 1],需要進行轉置和規範化。# torch.Tensor -> PIL.Image.image = 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.Tensor.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.astypde(np.uint8))# PIL.Image -> np.ndarray.ndarray = np.asarray(PIL.Image.open(path))這在訓練時統計loss的變化過程中特別有用。否則這將累積計算圖,使GPU存儲占用量越來越大。張量形變常常需要用於將卷積層特徵輸入全連接層的情形。相比torch.view,torch.reshape可以自動處理輸入張量不連續的情況。tensor = torch.reshape(tensor, shape)tensor=tensor[torch.randperm(tensor.size(0))]#ShufflethefirstdimensionPyTorch不支持tensor[::-1]這樣的負步長操作,水平翻轉可以用張量索引實現。# Assume tensor has shape N*D*H*W.tensor = tensor[:, :, :, torch.arange(tensor.size(3) - 1, -1, -1).long()]# Operation | New/Shared memory | Still in computation graph |tensor.clone() # | New | Yes |tensor.detach() # | Shared | No |tensor.detach.clone()() # | New | No |注意torch.cat和torch.stack的區別在於torch.cat沿着給定的維度拼接,而torch.stack會新增一維。例如當參數是3個10×5的張量,torch.cat的結果是30×5的張量,而torch.stack的結果是3×10×5的張量。tensor = torch.cat(list_of_tensors, dim=0)tensor = torch.stack(list_of_tensors, dim=0)N = tensor.size(0)one_hot = torch.zeros(N, num_classes).long()one_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 elementstorch.allclose(tensor1, tensor2) # float tensortorch.equal(tensor1, tensor2) # int tensor# Expand tensor of shape 64*512 to shape 64*512*7*7.torch.reshape(tensor,(64,512,1,1)).expand(64,512,7,7)# Matrix multiplication: (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# X1 is of shape m*d, X2 is of shape n*d.dist = torch.sqrt(torch.sum((X1[:,None,:] - X2) ** 2, dim=2))03
conv = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=True)conv = torch.nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=True)如果卷積層配置比較複雜,不方便計算輸出大小時,可以利用如下可視化工具輔助https://ezyang.github.io/convolution-visualizer/index.htmlGAP(Global average pooling)層gap = torch.nn.AdaptiveAvgPool2d(output_size=1)雙線性匯合(bilinear pooling)[1]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)#L2normalization多卡同步BN(Batch normalization)當使用torch.nn.DataParallel將代碼運行在多張GPU卡上時,PyTorch的BN層默認操作是各卡上數據獨立地計算均值和標準差,同步BN使用所有卡上的數據一起計算BN層的均值和標準差,緩解了當批量大小(batch size)比較小時對均值和標準差估計不準的情況,是在目標檢測等任務中一個有效的提升性能的技巧。https://github.com/vacancy/Synchronized-BatchNorm-PyTorchsync_bn = torch.nn.SyncBatchNorm(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)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_mean sync_bn.running_var = module.running_var if module.affine: sync_bn.weight = module.weight.clone().detach() sync_bn.bias = module.bias.clone().detach() return sync_bn else: for name, child_module in module.named_children(): setattr(module, name) = convert_syncbn_model(child_module, process_group=process_group)) return module如果要實現類似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)forparameterinmodel.parameters())類似Keras的model.summary()輸出模型信息https://github.com/sksq96/pytorch-summary注意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)注意如果保存的模型是torch.nn.DataParallel,則當前的模型也需要是torch.nn.DataParallel。torch.nn.DataParallel(model).module == model。model.load_state_dict(torch.load('model,pth'), strict=False)model.load_state_dict(torch.load('model,pth', map_location='cpu'))04
圖像分塊打散(image shuffle)/區域混淆機制(region confusion mechanism,RCM)[2]# X is torch.Tensor of size N*D*H*W.# Shuffle rowsQ = (torch.unsqueeze(torch.arange(num_blocks), dim=1) * torch.ones(1, num_blocks).long() + torch.randint(low=-neighbour, high=neighbour, size=(num_blocks, num_blocks)))Q = torch.argsort(Q, dim=0)assert Q.size() == (num_blocks, num_blocks)X = [torch.chunk(row, chunks=num_blocks, dim=2) for row in torch.chunk(X, chunks=num_blocks, dim=1)]X = [[X[Q[i, j].item()][j] for j in range(num_blocks)] for i in range(num_blocks)]# Shulle columns.Q = (torch.ones(num_blocks, 1).long() * torch.unsqueeze(torch.arange(num_blocks), dim=0) + torch.randint(low=-neighbour, high=neighbour, size=(num_blocks, num_blocks)))Q = torch.argsort(Q, dim=1)assert Q.size() == (num_blocks, num_blocks)X = [[X[i][Q[i, j].item()] for j in range(num_blocks)] for i in range(num_blocks)]Y=torch.cat([torch.cat(row,dim=2)forrowinX],dim=1)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()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 // 2 frame_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]foriinrange(K)]# 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.eval() conv_representation = model(image)class FeatureExtractor(torch.nn.Module): """Helper class to extract several convolution features from the given pre-trained model. Attributes: _model, torch.nn.Module. _layers_to_extract, list<str> or set<str> 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_model self._model.eval() self._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_representationhttps://github.com/Cadene/pretrained-models.pytorchmodel = 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 for p in model.parameters() if id(p) not in finetuned_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)05
其中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)),])for t in epoch(80): for images, labels in tqdm.tqdm(train_loader, desc='Epoch %3d' % (t + 1)): images, labels = images.cuda(), labels.cuda() scores = model(images) loss = loss_function(scores, labels) optimizer.zero_grad() loss.backward() optimizer.step()for images, labels in train_loader: images, labels = images.cuda(), labels.cuda() N = labels.size(0) # C is the number of classes. smoothed_labels = torch.full(size=(N, C), fill_value=0.1 / (C - 1)).cuda() smoothed_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) / N optimizer.zero_grad() loss.backward() optimizer.step()beta_distribution = torch.distributions.beta.Beta(alpha, alpha)for images, labels in train_loader: images, labels = images.cuda(), labels.cuda() # Mixup images. lambda_ = beta_distribution.sample([]).item() index = torch.randperm(images.size(0)).cuda() mixed_images = lambda_ * images + (1 - lambda_) * images[index, :] # Mixup loss. scores = model(mixed_images) loss = (lambda_ * loss_function(scores, labels) + (1 - lambda_) * loss_function(scores, labels[index])) optimizer.zero_grad() loss.backward() optimizer.step()l1_regularization = torch.nn.L1Loss(reduction='sum')loss = ... # Standard cross-entropy lossfor param in model.parameters(): loss += lambda_ * torch.sum(torch.abs(param))loss.backward()不對偏置項進行L2正則化/權值衰減(weight decay)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)torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=20)score = model(images)prediction = torch.argmax(score, dim=1)num_correct = torch.sum(prediction == labels).item()accuruacy = num_correct / labels.size(0)https://github.com/szagoruyko/pytorchviz有Facebook自己開發的Visdom和Tensorboard(仍處於實驗階段)兩個選擇。https://github.com/fossasia/visdomhttps://pytorch.org/docs/stable/tensorboard.html# Example using Visdom.vis = visdom.Visdom(env='Learning curve', use_incoming_socket=False)assert self._visdom.check_connection()self._visdom.close()options = collections.namedtuple('Options', ['loss', 'acc', 'lr'])( loss={'xlabel': 'Epoch', 'ylabel': 'Loss', 'showlegend': True}, acc={'xlabel': 'Epoch', 'ylabel': 'Accuracy', 'showlegend': True}, lr={'xlabel': 'Epoch', 'ylabel': 'Learning rate', 'showlegend': True})for t in epoch(80): tran(...) val(...) vis.line(X=torch.Tensor([t + 1]), Y=torch.Tensor([train_loss]), name='train', win='Loss', update='append', opts=options.loss) vis.line(X=torch.Tensor([t + 1]), Y=torch.Tensor([val_loss]), name='val', win='Loss', update='append', opts=options.loss) vis.line(X=torch.Tensor([t + 1]), Y=torch.Tensor([train_acc]), name='train', win='Accuracy', update='append', opts=options.acc) vis.line(X=torch.Tensor([t + 1]), Y=torch.Tensor([val_acc]), name='val', win='Accuracy', update='append', opts=options.acc) vis.line(X=torch.Tensor([t + 1]), Y=torch.Tensor([lr]), win='Learning rate', update='append', opts=options.lr)# 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'])# 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.step() train(...); val(...)注意為了能夠恢復訓練,我們需要同時保存模型和優化器的狀態,以及當前的訓練輪數。# Save checkpoint.is_best = current_acc > best_accbest_acc = max(best_acc, current_acc)checkpoint = { 'best_acc': best_acc, 'epoch': t + 1, 'model': model.state_dict(), 'optimizer': optimizer.state_dict(),}model_path = os.path.join('model', 'checkpoint.pth.tar')torch.save(checkpoint, model_path)if is_best: shutil.copy('checkpoint.pth.tar', model_path)# Load checkpoint.if resume: model_path = os.path.join('model', 'checkpoint.pth.tar') assert os.path.isfile(model_path) checkpoint = torch.load(model_path) best_acc = checkpoint['best_acc'] start_epoch = checkpoint['epoch'] model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) print('Load checkpoint at epoch %d.' % start_epoch)計算準確率、查准率(precision)、查全率(recall)
# data['label'] and data['prediction'] are groundtruth label and prediction # for each image, respectively.accuracy = np.mean(data['label'] == data['prediction']) * 100# Compute recision and recall for each class.for c in range(len(num_classes)): tp = np.dot((data['label'] == c).astype(int), (data['prediction'] == c).astype(int)) tp_fp = np.sum(data['prediction'] == c) tp_fn = np.sum(data['label'] == c) precision = tp / tp_fp * 100 recall = tp / tp_fn * 10006
計算每個類別的查准率(precision)、查全率(recall)、F1和總體指標import sklearn.metricsall_label = []all_prediction = []for images, labels in tqdm.tqdm(data_loader): # Data. images, labels = images.cuda(), labels.cuda() # Forward pass. score = model(images) # Save label and predictions. prediction = torch.argmax(score, dim=1) all_label.append(labels.cpu().numpy()) all_prediction.append(prediction.cpu().numpy())# Compute RP and confusion matrix.all_label = np.concatenate(all_label)assert len(all_label.shape) == 1all_prediction = np.concatenate(all_prediction)assert all_label.shape == all_prediction.shapemicro_p, micro_r, micro_f1, _ = sklearn.metrics.precision_recall_fscore_support( all_label, all_prediction, average='micro', labels=range(num_classes))class_p, class_r, class_f1, class_occurence = sklearn.metrics.precision_recall_fscore_support( all_label, all_prediction, average=None, labels=range(num_classes))# Ci,j = #{y=i and hat_y=j}confusion_mat = sklearn.metrics.confusion_matrix( all_label, all_prediction, labels=range(num_classes))assert confusion_mat.shape == (num_classes, num_classes)import csv# Write results onto disk.with open(os.path.join(path, filename), 'wt', encoding='utf-8') as f: f = csv.writer(f) f.writerow(['Class', 'Label', '# occurence', 'Precision', 'Recall', 'F1', 'Confused class 1', 'Confused class 2', 'Confused class 3', 'Confused 4', 'Confused class 5']) for c in range(num_classes): index = np.argsort(confusion_mat[:, c])[::-1][:5] f.writerow([ label2class[c], c, class_occurence[c], '%4.3f' % class_p[c], '%4.3f' % class_r[c], '%4.3f' % class_f1[c], '%s:%d' % (label2class[index[0]], confusion_mat[index[0], c]), '%s:%d' % (label2class[index[1]], confusion_mat[index[1], c]), '%s:%d' % (label2class[index[2]], confusion_mat[index[2], c]), '%s:%d' % (label2class[index[3]], confusion_mat[index[3], c]), '%s:%d' % (label2class[index[4]], confusion_mat[index[4], c])]) f.writerow(['All', '', np.sum(class_occurence), micro_p, micro_r, micro_f1, '','','','',''])07
建議有參數的層和匯合(pooling)層使用torch.nn模塊定義,激活函數直接使用torch.nn.functional。torch.nn模塊和torch.nn.functional的區別在於,torch.nn模塊在計算時底層調用了torch.nn.functional,但torch.nn模塊包括該層參數,還可以應對訓練和測試兩種網絡狀態。使用torch.nn.functional時要注意網絡狀態,如def forward(self, x): ... x = torch.nn.functional.dropout(x, p=0.5, training=self.training)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()。torch.nn.CrossEntropyLoss的輸入不需要經過Softmax。torch.nn.CrossEntropyLoss等價於torch.nn.functional.log_softmax + torch.nn.NLLLoss。loss.backward()前用optimizer.zero_grad()清除累積梯度。optimizer.zero_grad()和model.zero_grad()效果一樣。torch.utils.data.DataLoader中儘量設置pin_memory=True,對特別小的數據集如MNIST設置pin_memory=False反而更快一些。num_workers的設置需要在實驗中找到最快的取值。x=torch.nn.functional.relu(x,inplace=True)此外,還可以通過torch.utils.checkpoint前向傳播時只保留一部分中間結果來節約GPU存儲使用,在反向傳播時需要的內容從最近中間結果中計算得到。減少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)python -m torch.utils.bottleneck main.py感謝@些許流年、@El tnoto、@FlyCharles的勘誤,感謝@oatmeal提供的更簡潔的方法。由於作者才疏學淺,更兼時間和精力所限,代碼中錯誤之處在所難免,敬請讀者批評指正。參考資料
https://github.com/pytorch/examplesPyTorch論壇:
https://discuss.pytorch.org/latest?order=views
PyTorch文檔:
http://pytorch.org/docs/stable/index.html
其他基於PyTorch的公開實現代碼,無法一一列舉
參考
1.T.-Y. Lin, A. RoyChowdhury, and S. Maji. Bilinear CNN models for fine-grained visual recognition. In ICCV, 2015.
2.Y. Chen, Y. Bai, W. Zhang, and T. Mei. Destruction and construction learning for fine-grained image recognition. In CVPR, 2019.
3.L. Wang, Y. Xiong, Z. Wang, Y. Qiao, D. Lin, X. Tang, and L. V. Gool. Temporal segment networks: Towards good practices for deep action recognition. In ECCV, 2016.
4.C. Szegedy, V. Vanhoucke, S. Ioffe, J. Shlens, and Z. Wojna: Rethinking the Inception architecture for computer vision. In CVPR, 2016.
5.H. Zhang, M. Cissé, Y. N. Dauphin, and D. Lopez-Paz. mixup: Beyond empirical risk minimization. In ICLR, 2018.



本文目的在於學術交流,並不代表本公眾號贊同其觀點或對其內容真實性負責,版權歸原作者所有,如有侵權請告知刪除。
神經網絡調參技巧:warmup策略語義分割的三點奇技淫巧機器學習中的相似性度量總結基於pytorch時間序列預測的數據shape處理10種聚類算法完整Python實現!使用scikit-learn構建模型的通用模板人臉3D重建論文方案分析2022(附代碼詳解)機器學習博士在獲得學位之前需要掌握的九種工具!100行代碼使用torch.fx極簡量化教程K-means和譜聚類的比較TensorFlow和Pytorch中的音頻增強關於SNN用BP訓練對話系統與四大天王整理了100個必備的 Python 函數如何在一個代碼里使用兩次 BERT更多他山之石專欄文章,請點擊文章底部「閱讀原文」查看