pytorch模型保存方式-时间测试-inference--torch.squeeze() 和torch.unsqueeze()的相关用法

本文详细解析了PyTorch中cp27m与cp27mu的区别,探讨了模型保存与加载的不同方式,包括整个模型与仅参数的保存,并介绍了torch.squeeze()与torch.unsqueeze()的用法,以及在PyTorch中进行时间测试的正确方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pytorch中cp27m与cp27mu的区别

https://blog.youkuaiyun.com/dlhlSC/article/details/88533376

我们在下载pytorch安装包时,会发现CUDA9.0有py27_gpu版有两个whl下载文件,分别是:

cu90/torch-0.3.0.post4-cp27-cp27mu-linux_x86_64.whl
cu90/torch-0.3.0.post4-cp27-cp27m-linux_x86_64.whl

cp27m是ucs2,cp27mu是ucs4。
UCS2规定每个字符占用2个字节,UCS4规定每个字节占用4个字符,都是UNICODE的编码形式。
一般选UCS2的版本即可。
 

 

Pytorch中的模型保存

torch.save()实现对网络结构和模型参数的保存。有两种保存方式:一是保存年整个神经网络的的结构信息和模型参数信息,save的对象是网络net;二是只保存神经网络的训练模型参数,save的对象是net.state_dict()。

 

保存和加载整个模型

torch.save(model_object, ‘model.pkl’)
model = torch.load(‘model.pkl’)

仅保存和加载模型参数(推荐使用)

torch.save(model_object.state_dict(), ‘params.pkl’)
model_object.load_state_dict(torch.load(‘params.pkl’))

 

有时候是.pth

有时候是.pkl

其实模型内部还是一样,主要是怎么保存的

 

对应上面两种保存方式,重载方式也有两种。

对应第一种完整网络结构信息,重载的时候通过

torch.load(‘.pth’)

直接初始化新的神经网络对象即可。

 

对应第二种只保存模型参数信息,需要首先导入对应的网络,

通过

net.load_state_dict(torch.load(‘.pth’)

完成模型参数的重载。在网络比较大的时候,第一种方法会花费较多的时间。

 

Pytorch中 torch.squeeze() 和torch.unsqueeze()的相关用法

https://blog.youkuaiyun.com/qian2213762498/article/details/86097912

 

Pytorch中时间测试

start = time.time()
result = model(input)
end = time.time()
torch.cuda.synchronize()
start = time.time()
result = model(input)
torch.cuda.synchronize()
end = time.time()

一共上述两种测试时间的方式,正确的方式是第二种,为什么是这样呢?在pytorch里面,程序的执行都是异步的。如果采用第一种方式,测试的时间会很短,因为执行完end=time.time()程序就退出了,后台的cu也因为python的退出退出了,如果采用第二种方式,代码会同步cu的操作,等待gpu上的操作都完成了再继续成形end = time.time()

 

DeblurGAN-v2 是一种图像去模糊的深度学习模型,可用于将模糊图像转换为清晰图像。在该模型中,使用了超像素技术来提高去模糊的效果。下面是利用超像素优化DeblurGAN-v2的PyTorch代码: 首先,需要安装以下依赖库: ``` pip install opencv-python pip install scikit-image pip install numpy pip install torch pip install torchvision pip install pydensecrf ``` 然后,加载DeblurGAN-v2模型测试图像,并生成超像素: ```python import cv2 import torch import numpy as np from skimage.segmentation import slic from skimage.segmentation import mark_boundaries from skimage.color import rgb2gray from models.networks import define_G from options.test_options import TestOptions from util import util from pydensecrf.densecrf import DenseCRF2D # 加载模型 opt = TestOptions().parse() opt.nThreads = 1 opt.batchSize = 1 opt.serial_batches = True opt.no_flip = True model = define_G(opt) util.load_checkpoint(model, opt.pretrained) # 加载测试图像 img_path = 'path/to/test/image' img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) h, w, c = img.shape # 生成超像素 segments = slic(img, n_segments=100, sigma=5, compactness=10) ``` 接下来,将每个超像素作为输入,运行DeblurGAN-v2模型进行去模糊: ```python # 对每个超像素进行去模糊 result = np.zeros((h, w, c), dtype=np.float32) for i in np.unique(segments): mask = (segments == i).astype(np.uint8) masked_img = cv2.bitwise_and(img, img, mask=mask) if np.sum(mask) > 0: masked_img = masked_img[np.newaxis, :, :, :] masked_img = torch.from_numpy(masked_img.transpose((0, 3, 1, 2))).float() with torch.no_grad(): output = model(masked_img) output = output.cpu().numpy() output = output.transpose((0, 2, 3, 1)) output = np.squeeze(output) result += output * mask[:, :, np.newaxis] # 对结果进行后处理 result /= 255.0 result = np.clip(result, 0, 1) result = (result * 255).astype(np.uint8) ``` 最后,使用密集条件随机场(DenseCRF)算法对结果进行后处理,以进一步提高去模糊的效果: ```python # 使用DenseCRF算法进行后处理 d = DenseCRF2D(w, h, 2) result_softmax = np.stack([result, 255 - result], axis=0) result_softmax = result_softmax.astype(np.float32) / 255.0 unary = -np.log(result_softmax) unary = unary.reshape((2, -1)) d.setUnaryEnergy(unary) d.addPairwiseGaussian(sxy=5, compat=3) d.addPairwiseBilateral(sxy=20, srgb=3, rgbim=img, compat=10) q = d.inference(5) q = np.argmax(np.array(q), axis=0).reshape((h, w)) result = q * 255 ``` 完整代码如下: ```python import cv2 import torch import numpy as np from skimage.segmentation import slic from skimage.segmentation import mark_boundaries from skimage.color import rgb2gray from models.networks import define_G from options.test_options import TestOptions from util import util from pydensecrf.densecrf import DenseCRF2D # 加载模型 opt = TestOptions().parse() opt.nThreads = 1 opt.batchSize = 1 opt.serial_batches = True opt.no_flip = True model = define_G(opt) util.load_checkpoint(model, opt.pretrained) # 加载测试图像 img_path = 'path/to/test/image' img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) h, w, c = img.shape # 生成超像素 segments = slic(img, n_segments=100, sigma=5, compactness=10) # 对每个超像素进行去模糊 result = np.zeros((h, w, c), dtype=np.float32) for i in np.unique(segments): mask = (segments == i).astype(np.uint8) masked_img = cv2.bitwise_and(img, img, mask=mask) if np.sum(mask) > 0: masked_img = masked_img[np.newaxis, :, :, :] masked_img = torch.from_numpy(masked_img.transpose((0, 3, 1, 2))).float() with torch.no_grad(): output = model(masked_img) output = output.cpu().numpy() output = output.transpose((0, 2, 3, 1)) output = np.squeeze(output) result += output * mask[:, :, np.newaxis] # 对结果进行后处理 result /= 255.0 result = np.clip(result, 0, 1) result = (result * 255).astype(np.uint8) # 使用DenseCRF算法进行后处理 d = DenseCRF2D(w, h, 2) result_softmax = np.stack([result, 255 - result], axis=0) result_softmax = result_softmax.astype(np.float32) / 255.0 unary = -np.log(result_softmax) unary = unary.reshape((2, -1)) d.setUnaryEnergy(unary) d.addPairwiseGaussian(sxy=5, compat=3) d.addPairwiseBilateral(sxy=20, srgb=3, rgbim=img, compat=10) q = d.inference(5) q = np.argmax(np.array(q), axis=0).reshape((h, w)) result = q * 255 # 显示结果 result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR) cv2.imshow('result', result) cv2.waitKey(0) cv2.destroyAllWindows() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值