![](https://img-blog.csdnimg.cn/20201014180756925.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
pytorch
GeneralJing
这个作者很懒,什么都没留下…
展开
-
TypeError: __init__() got an unexpected keyword argument ‘is_valid_file‘
应该是torchvision的版本较低,换了一个高版本的虚拟环境,就可以了。原创 2021-06-15 10:34:05 · 381 阅读 · 0 评论 -
OSError: image file is truncated (71 bytes not processed)
在加载训练图像数据,准备训练模型的时候,报错如下:OSError: image file is truncated (71 bytes not processed)原创 2021-06-10 22:36:03 · 1209 阅读 · 0 评论 -
pytorch 获取参数量代码片段
# Find total parameters and trainable parameterstotal_params = sum(p.numel() for p in model.parameters())print(f'{total_params:,} total parameters.')total_trainable_params = sum( p.numel() for p in model.parameters() if p.requires_grad)print(f'{to.原创 2021-02-13 08:13:43 · 193 阅读 · 0 评论 -
pytorch 通过torchvision获取模型
最近在看一个开源的代码,在代码开头,获取模型的地方,使用了一个简洁的方式获取网络模型,看着非常好,记录一下。import torchfrom torchvision import modelsfrom .repvgg import func_dict as repvggdef build_model(net, num_classes=10): if net in ["resnet18", "resnet34", "resnet50"]: model = getattr原创 2021-02-10 08:21:02 · 569 阅读 · 1 评论 -
pytorch导出onnx格式模型时,不固定输入输出维度
Pytorch模型转换为onnx格式模型后,模型的输入、输出维度跟转换模型时,用的dummy_input的维度有关系,属于固定尺寸的输入与输出。可以采用以下代码修改onnx模型的输入输出维度:import onnx model = onnx.load('xxx.onnx')# 此处可以理解为获得了一个维度 “引用”,通过该 “引用“可以修改其对应的维度原创 2021-02-02 16:48:11 · 4727 阅读 · 0 评论 -
RuntimeError: Failed to export an ONNX attribute ‘onnx::Gather‘, since it‘s not constant, please try
最近在把pytorch模型转换onnx格式模型的时候,遇到了如下错误:RuntimeError: Failed to export an ONNX attribute 'onnx::Gather', since it's not constant, please try to make things (e.g., kernel size) static if possible在网上查了下,这个连接是跟我的问题相关的:https://github.com/onnx/tutorials/issue原创 2021-01-22 11:30:45 · 3035 阅读 · 0 评论 -
pytorch semantic segmentation using torchvision
一些有用的小的代码片段。# use the following function to convert this 2D image to an RGB image where each label is mapped to its # corresponding color.# Define the helper functiondef decode_segmap(image, nc=21): label_colors = np.array([(0, 0, 0), # 0=bac原创 2021-01-21 11:49:30 · 236 阅读 · 0 评论 -
pytorch squeeze and excitation模块
可以自适应的调整各通道的特征响应值,对通道间的内部依赖关系进行建模,主要为下面三个步骤: Squeeze: 沿着空间维度进行特征压缩,将每个二维的特征通道变成一个数,是具有全局的感受野。对进行global average pooling,得到大小的特征图,这个特征图可以理解为具有全局感受野。 Excitation: 每个特征通道生成一个权重,用来代表该特征通道的重要程度。使用一个全连接神经网络,对Sequeeze之后的结果做一个非线性变换。 Reweight:将Excitation原创 2021-01-15 11:20:41 · 957 阅读 · 0 评论 -
pytorch optimizer, scheduler使用
import torchdef get_optimizer(network, args): optimizer = torch.optim.SGD(network.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.w.原创 2021-01-14 11:35:53 · 842 阅读 · 0 评论 -
pytorch 交叉熵类定义
import torchclass Loss_Calculator(object): def __init__(self): self.criterion = torch.nn.CrossEntropyLoss() self.loss_seq = [] def calc_loss(self, output, target): loss = self.criterion(output, target) .原创 2021-01-14 11:06:35 · 675 阅读 · 0 评论 -
pytorch 下载数据集
def get_data_set(args, train_flag=True): if train_flag: data_set = torchvision.datasets.__dict__[args.data_set] (root=args.data_path, train=True, transform=get_transformer(args.data_set, args..原创 2021-01-14 10:56:52 · 747 阅读 · 0 评论 -
pytorch 利用vgg16_bn进行特征提取,然后进行分类
构建网络:import torchimport torchvision.models as modelsclass VGG(torch.nn.Module): def __init__(self, vgg='vgg16_bn', data_set='CIFAR10', pretrained=False): super(VGG, self).__init__() self.features = models.__dict__[vgg](pretrained=原创 2021-01-14 10:49:38 · 1451 阅读 · 0 评论 -
pytorch 对加载好的模型重新进行初始化
在验证小模型从头训练的效果时,需要把已有的权重重新进行初始化,发现了一个封装好的功能脚本,感谢大佬。#!/usr/bin/env python# -*- coding:UTF-8 -*-import torchimport torch.nn as nnimport torch.nn.init as initdef weight_init(m): ''' Usage: model = Model() model.apply(weight_i原创 2021-01-08 15:03:31 · 1602 阅读 · 0 评论 -
理解分组卷积和深度可分离卷积如何降低参数量
最近在计算conv的mask的时候,接触到Conv2D的group参数,对分组卷积有些不清楚,这篇博文介绍的通俗易懂,配图清晰。https://zhuanlan.zhihu.com/p/65377955原创 2021-01-08 10:39:08 · 766 阅读 · 0 评论 -
pytorch conv2d函数参数group的作用
这篇博客介绍的比较清楚,https://www.cnblogs.com/wanghui-garcia/p/10775851.html。原创 2021-01-07 19:18:32 · 814 阅读 · 0 评论 -
pytorch model.modules()疑问
最近在做剪枝相关的事情,在遍历模型模块的时候,使用的是如下方式:for k, m in enumerate(model.modules()): print("k:", k) print("m:", m)但是对于模型的模块输出发现有缺失,如下:k: 6m: Block( (conv1): Conv2d(16, 16, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(16, eps=1e原创 2021-01-07 10:46:45 · 513 阅读 · 3 评论 -
pytorch 模型加载
def load_model(model,model_path): if torch.cuda.is_available(): model_dict = torch.load(model_path) else: model_dict = torch.load(model_path,map_location='cpu') if('state_dict' in model_dict.keys()): model_dict.原创 2021-01-06 11:33:44 · 338 阅读 · 0 评论 -
pytorch 使用.contiguous().view()
view()使用的前提是variable是contiguous的,如果在view之前用了transpose, permute等,需要用contiguous()来返回一个contiguous copy。有些tensor并不是占用一整块内存,而是由不同的数据块组成,而tensor的view()操作依赖于内存是整块的,这时只需要执行contiguous()这个函数,把tensor变成在内存中连续分布的形式。在torch里面,view函数相当于numpy的reshape。X.view(-1, 5)这原创 2021-01-05 15:56:50 · 2010 阅读 · 0 评论 -
pytorch中正确使用损失函数nn.MSELoss
函数参数有reduce和size_average,类型为布尔类型。因为损失函数一般都是计算一个batch的数据,所以返回的结果都是维度为(batchsize, )的向量。1.如果reduce=false,size_average参数失效,直接返回向量形式的loss。2.如果reduce=true,那么loss返回的是标量size_average=true,返回的是loss.mean()size_average=false,返回的是loss.sum()注意:默认情况下, red...原创 2021-01-05 15:44:19 · 9305 阅读 · 2 评论 -
torch.argmax函数学习
torch.argmax()函数argmax函数:torch.argmax(input, dim=None, keepdim=False)返回指定维度最大值的序号,dim给定的定义是:the demention to reduce.也就是把dim这个维度的,变成这个维度的最大值的index。1)dim的不同值表示不同维度。特别的在dim=0表示二维中的列,dim=1在二维矩阵中表示行。广泛的来说,我们不管一个矩阵是几维的,比如一个矩阵维度如下:(d0,d1,...,dn−1) ,那么dim=0就表示对转载 2020-12-07 20:21:57 · 20339 阅读 · 3 评论 -
onnx.checker.check_model segmentation fault
今天对微调修改op的模型进行50个epoch训练后,将模型导出为onnx的过程中,遇到一个有意思的现象。转换后的模型,可以正常通过onnxruntime进行推理测试,但是在check_model的时候报错了,segmentation fault。百度查了下说是要在import torch之前,先进行import onnx。试了一下,check_model就通过了。另外一个现象是,为了推理加速,将后处理的操作移到了模型内,这种可以推理然后保存,但是训练就会报错,说是类型不匹配,具体的报错信息,因为目前在训原创 2020-12-02 16:26:27 · 1497 阅读 · 0 评论 -
RuntimeError: expected device cpu but got device cuda:0
在对模型进行微调训练的时候,代码报错如下:File "/home/xxxx/EdgeNets/utilities/train_eval_seg.py", line 48, in train_seg optimizer.step() File "/home/xxxx/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/optim/sgd.py", line 100, in step buf.mul_(momentum).a原创 2020-11-30 16:37:41 · 1626 阅读 · 0 评论 -
RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 1.
最近在修改模型不支持的算子后,由于对模型的效果产生了影响,所以需要进行微调训练,但是训练的时候报错了,如下:File "/home/xxxxxxx/EdgeNets/nn_layers/efficient_pyramid_pool.py", line 300, in forward out = torch.cat(hs, dim=1)RuntimeError: invalid argument 0: Sizes of tensors must match except in dimensio原创 2020-11-30 16:32:46 · 940 阅读 · 0 评论 -
onnxruntime CPU和GPU推理测试
最近在做移动端模型移植的工作,在转换为onnx中间模型格式的时候,利用onnxruntime加载onnx模型进行推理,为了对比CPU与GPU的推理时间,需要分别进行测试。onnxruntime的CPU和GPU测试的方式,百度了一下没有找到合适的解决方式,后来问了其他同事,大概知道了。如果要测试CPU的推理时间,Python环境需要安装onnxruntime,如果测试GPU的推理时间,Python环境就需要卸载CPU版本,安装onnxruntime-gpu,然后进行推理时间测试。 2.66s-ma原创 2020-11-19 17:05:13 · 12728 阅读 · 1 评论 -
错误-torch.nn.modules.module.ModuleAttributeError:: ‘xxx’ object has no attribute ‘copy’
使用torch.load_state_dict()出现的问题model.load_state_dict(torch.load(model_path))如下报错:torch.nn.modules.module.ModuleAttributeError: 'XXXNet' object has no attribute 'copy'发现问题出现在训练模型的代码中,在保存模型时,使用的是 torch.save(model, path)应该使用 torch.save(model原创 2020-11-13 20:43:51 · 4506 阅读 · 1 评论 -
torch.manual_seed()和torch.cuda.manual_seed()
torch.manual_seed(args.seed) #为CPU设置种子用于生成随机数,以使得结果是确定的if args.cuda: torch.cuda.manual_seed(args.seed) # 为当前GPU设置随机种子;如果使用多个GPU,应该使用 torch.cuda.manual_seed_all() # 为所有的GPU设置种子。...原创 2020-10-09 15:21:23 · 616 阅读 · 0 评论 -
pytorch训练中指定GPU
有两种方式:1.代码中指定GPU:import osos.environ['CUDA_VISIBLE_DEVICE'] = 12.训练的时候通过命令进行指定:CUDA_VISIBLE_DEVICES = 1原创 2020-09-26 11:21:39 · 1444 阅读 · 2 评论 -
pytorch模型结构可视化
最近在做跟hrnet相关的一些工作,需要查看网络的结构,对某些网络层需要进行特别的处理,所以需要对网络结构进行可视化。一开始想到的就是netron,但是由于hrnet网络中对层进行了封装处理,所以得到的是如下示意图:但是这种对封装的模块不能展开,不方便查看内部结构。后来尝试使用了TensorBoardX,代码大致如下:# build modelmodel = eval('models.'+config.MODEL.NAME + '.get_seg_mod原创 2020-09-16 11:07:07 · 922 阅读 · 1 评论