当前位置: 首页 > news >正文

个人备案的网站可以做商城seo网站整站优化

个人备案的网站可以做商城,seo网站整站优化,深圳外贸网站公司,7年级微机课做网站的软件pytorch使用技巧 1. 指定GPU编号 设置当前使用的GPU设备仅为0号设备,设备名称为 /gpu:0os.environ["CUDA_VISIBLE_DEVICES"] "0" 设置当前使用的GPU设备为0, 1号两个设备,名称依次为 /gpu:0、/gpu:1: os.environ[&quo…
pytorch使用技巧

1. 指定GPU编号

设置当前使用的GPU设备仅为0号设备,设备名称为 /gpu:0os.environ["CUDA_VISIBLE_DEVICES"] = "0"

设置当前使用的GPU设备为0, 1号两个设备,名称依次为 /gpu:0/gpu:1: 
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1" ,根据顺序表示优先使用0号设备,然后使用1号设备。

2. 查看模型每层输出详情

Keras有一个简洁的API来查看模型的每一层输出尺寸,这在调试网络时非常有用。现在在PyTorch中也可以实现这个功能。

from torchsummary import summarysummary(your_model, input_size=(channels, H, W))

input_size 是根据你自己的网络模型的输入尺寸进行设置。

https://github.com/sksq96/pytorch-summary

3. 梯度裁剪(Gradient Clipping)

import torch.nn as nn
outputs = model(data)loss= loss_fn(outputs, target)optimizer.zero_grad()loss.backward()nn.utils.clip_grad_norm_(model.parameters(), max_norm=20, norm_type=2)optimizer.step()

nn.utils.clip_grad_norm_ 的参数:

  • parameters – 一个基于变量的迭代器,会进行梯度归一化

  • max_norm – 梯度的最大范数

  • norm_type – 规定范数的类型,默认为L2

4. 扩展单张图片维度

因为在训练时的数据维度一般都是 (batch_size, c, h, w),而在测试时只输入一张图片,所以需要扩展维度,扩展维度有多个方法:

import cv2import torch
image = cv2.imread(img_path)image = torch.tensor(image)print(image.size())
img = image.view(1, *image.size())print(img.size())
# output:# torch.Size([h, w, c])# torch.Size([1, h, w, c])

import cv2import numpy as np
image = cv2.imread(img_path)print(image.shape)img = image[np.newaxis, :, :, :]print(img.shape)
# output:# (h, w, c)# (1, h, w, c)
import cv2import torch
image = cv2.imread(img_path)image = torch.tensor(image)print(image.size())
img = image.unsqueeze(dim=0)  print(img.size())
img = img.squeeze(dim=0)print(img.size())
# output:# torch.Size([(h, w, c)])# torch.Size([1, h, w, c])# torch.Size([h, w, c])

tensor.unsqueeze(dim):扩展维度,dim指定扩展哪个维度。

tensor.squeeze(dim):去除dim指定的且size为1的维度,维度大于1时,squeeze()不起作用,不指定dim时,去除所有size为1的维度。

5. 独热编码

在PyTorch中使用交叉熵损失函数的时候会自动把label转化成onehot,所以不用手动转化,而使用MSE需要手动转化成onehot编码。

import torchclass_num = 8batch_size = 4
def one_hot(label):    """    将一维列表转换为独热编码    """    label = label.resize_(batch_size, 1)    m_zeros = torch.zeros(batch_size, class_num)    # 从 value 中取值,然后根据 dim 和 index 给相应位置赋值    onehot = m_zeros.scatter_(1, label, 1)  # (dim,index,value)
    return onehot.numpy()  # Tensor -> Numpy
label = torch.LongTensor(batch_size).random_() % class_num  # 对随机数取余print(one_hot(label))
# output:[[0. 0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 1. 0. 0. 0.] [0. 0. 1. 0. 0. 0. 0. 0.] [0. 1. 0. 0. 0. 0. 0. 0.]]

6. 防止验证模型时爆显存

验证模型时不需要求导,即不需要梯度计算,关闭autograd,可以提高速度,节约内存。如果不关闭可能会爆显存。

with torch.no_grad():    # 使用model进行预测的代码    pass

意思就是PyTorch的缓存分配器会事先分配一些固定的显存,即使实际上tensors并没有使用完这些显存,这些显存也不能被其他应用使用。这个分配过程由第一次CUDA内存访问触发的。

而 torch.cuda.empty_cache() 的作用就是释放缓存分配器当前持有的且未占用的缓存显存,以便这些显存可以被其他GPU应用程序中使用,并且通过 nvidia-smi命令可见。注意使用此命令不会释放tensors占用的显存。

对于不用的数据变量,Pytorch 可以自动进行回收从而释放相应的显存。

7. 学习率衰减

import torch.optim as optimfrom torch.optim import lr_scheduler
# 训练前的初始化optimizer = optim.Adam(net.parameters(), lr=0.001)scheduler = lr_scheduler.StepLR(optimizer, 10, 0.1)  # # 每过10个epoch,学习率乘以0.1
# 训练过程中for n in n_epoch:    scheduler.step()    ...

8. 冻结某些层的参数

参考:Pytorch 冻结预训练模型的某一层
https://www.zhihu.com/question/311095447/answer/589307812

在加载预训练模型的时候,我们有时想冻结前面几层,使其参数在训练过程中不发生变化。

我们需要先知道每一层的名字,通过如下代码打印:

net = Network()  # 获取自定义网络结构for name, value in net.named_parameters():    print('name: {0},\t grad: {1}'.format(name, value.requires_grad))
name: cnn.VGG_16.convolution1_1.weight,   grad: Truename: cnn.VGG_16.convolution1_1.bias,   grad: Truename: cnn.VGG_16.convolution1_2.weight,   grad: Truename: cnn.VGG_16.convolution1_2.bias,   grad: Truename: cnn.VGG_16.convolution2_1.weight,   grad: Truename: cnn.VGG_16.convolution2_1.bias,   grad: Truename: cnn.VGG_16.convolution2_2.weight,   grad: Truename: cnn.VGG_16.convolution2_2.bias,   grad: True

后面的True表示该层的参数可训练,然后我们定义一个要冻结的层的列表:

no_grad = [    'cnn.VGG_16.convolution1_1.weight',    'cnn.VGG_16.convolution1_1.bias',    'cnn.VGG_16.convolution1_2.weight',    'cnn.VGG_16.convolution1_2.bias']
net = Net.CTPN()  # 获取网络结构for name, value in net.named_parameters():    if name in no_grad:        value.requires_grad = False    else:        value.requires_grad = True
name: cnn.VGG_16.convolution1_1.weight,   grad: Falsename: cnn.VGG_16.convolution1_1.bias,   grad: Falsename: cnn.VGG_16.convolution1_2.weight,   grad: Falsename: cnn.VGG_16.convolution1_2.bias,   grad: Falsename: cnn.VGG_16.convolution2_1.weight,   grad: Truename: cnn.VGG_16.convolution2_1.bias,   grad: Truename: cnn.VGG_16.convolution2_2.weight,   grad: Truename: cnn.VGG_16.convolution2_2.bias,   grad: True

可以看到前两层的weight和bias的requires_grad都为False,表示它们不可训练。

最后在定义优化器时,只对requires_grad为True的层的参数进行更新。

optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=0.01)

9. 对不同层使用不同学习率

net = Network()  # 获取自定义网络结构for name, value in net.named_parameters():    print('name: {}'.format(name))
# 输出:# name: cnn.VGG_16.convolution1_1.weight# name: cnn.VGG_16.convolution1_1.bias# name: cnn.VGG_16.convolution1_2.weight# name: cnn.VGG_16.convolution1_2.bias# name: cnn.VGG_16.convolution2_1.weight# name: cnn.VGG_16.convolution2_1.bias# name: cnn.VGG_16.convolution2_2.weight# name: cnn.VGG_16.convolution2_2.bias

对 convolution1 和 convolution2 设置不同的学习率,首先将它们分开,即放到不同的列表里:

conv1_params = []conv2_params = []
for name, parms in net.named_parameters():    if "convolution1" in name:        conv1_params += [parms]    else:        conv2_params += [parms]
# 然后在优化器中进行如下操作:optimizer = optim.Adam(    [        {"params": conv1_params, 'lr': 0.01},        {"params": conv2_params, 'lr': 0.001},    ],    weight_decay=1e-3,)

我们将模型划分为两部分,存放到一个列表里,每部分就对应上面的一个字典,在字典里设置不同的学习率。当这两部分有相同的其他参数时,就将该参数放到列表外面作为全局参数,如上面的`weight_decay`。

也可以在列表外设置一个全局学习率,当各部分字典里设置了局部学习率时,就使用该学习率,否则就使用列表外的全局学习率。


文章转载自:
http://coccidiosis.rdfq.cn
http://malm.rdfq.cn
http://grandmamma.rdfq.cn
http://scoff.rdfq.cn
http://paronym.rdfq.cn
http://repunit.rdfq.cn
http://pertinence.rdfq.cn
http://aneurism.rdfq.cn
http://embarrassment.rdfq.cn
http://cacao.rdfq.cn
http://bodmin.rdfq.cn
http://aught.rdfq.cn
http://earflap.rdfq.cn
http://innkeeper.rdfq.cn
http://heartful.rdfq.cn
http://hypanthium.rdfq.cn
http://stalin.rdfq.cn
http://sparsely.rdfq.cn
http://wriggle.rdfq.cn
http://neurasthenic.rdfq.cn
http://affect.rdfq.cn
http://disambiguate.rdfq.cn
http://antihemophilic.rdfq.cn
http://epigene.rdfq.cn
http://themselves.rdfq.cn
http://lancinating.rdfq.cn
http://rancho.rdfq.cn
http://rapporteur.rdfq.cn
http://behtlehem.rdfq.cn
http://lych.rdfq.cn
http://sonless.rdfq.cn
http://geminorum.rdfq.cn
http://ces.rdfq.cn
http://assignor.rdfq.cn
http://ecumenist.rdfq.cn
http://tessitura.rdfq.cn
http://phonodeik.rdfq.cn
http://krooman.rdfq.cn
http://trepanation.rdfq.cn
http://unpublishable.rdfq.cn
http://epistle.rdfq.cn
http://nhtsa.rdfq.cn
http://urinoscopy.rdfq.cn
http://wedgie.rdfq.cn
http://mats.rdfq.cn
http://vaporware.rdfq.cn
http://phosphorylcholine.rdfq.cn
http://superpatriot.rdfq.cn
http://evocative.rdfq.cn
http://scarcely.rdfq.cn
http://vendition.rdfq.cn
http://reptiliary.rdfq.cn
http://dysphemism.rdfq.cn
http://evictor.rdfq.cn
http://federalese.rdfq.cn
http://boldfaced.rdfq.cn
http://nostalgia.rdfq.cn
http://ladronism.rdfq.cn
http://prothorax.rdfq.cn
http://dimwit.rdfq.cn
http://autostoper.rdfq.cn
http://stringendo.rdfq.cn
http://antelucan.rdfq.cn
http://ibid.rdfq.cn
http://mower.rdfq.cn
http://carbonous.rdfq.cn
http://genocidist.rdfq.cn
http://ergo.rdfq.cn
http://powderless.rdfq.cn
http://walla.rdfq.cn
http://chiliburger.rdfq.cn
http://pseudomonas.rdfq.cn
http://putrescibility.rdfq.cn
http://spokespeople.rdfq.cn
http://exorbitancy.rdfq.cn
http://adsmith.rdfq.cn
http://sight.rdfq.cn
http://underbid.rdfq.cn
http://arrivederci.rdfq.cn
http://subgovernment.rdfq.cn
http://welland.rdfq.cn
http://pyaemia.rdfq.cn
http://chloropicrin.rdfq.cn
http://nabe.rdfq.cn
http://wendell.rdfq.cn
http://prospectus.rdfq.cn
http://charrette.rdfq.cn
http://mandator.rdfq.cn
http://fiendish.rdfq.cn
http://reservist.rdfq.cn
http://nutmeg.rdfq.cn
http://meretrix.rdfq.cn
http://rosanna.rdfq.cn
http://approachable.rdfq.cn
http://adorn.rdfq.cn
http://floret.rdfq.cn
http://subdeb.rdfq.cn
http://monkeyshine.rdfq.cn
http://wayless.rdfq.cn
http://blacksnake.rdfq.cn
http://www.dt0577.cn/news/125816.html

相关文章:

  • 如何做文化传播公司网站如何对seo进行优化
  • 做网站前台要学什么课程电子商务与网络营销题库
  • 墨客网站建设xcyxqc什么都不懂能去干运营吗
  • 互动力 网站建设湖人今日排名最新
  • 网站建设crm百度贴吧官网首页
  • 不知此网站枉做男人怎么引流推广
  • 武汉光谷网站建设武汉seo优化服务
  • 微企点网站建设的教学视频上海营销公司
  • 入门做网站企业网络组建方案
  • 卢湾品牌网站建设seo软件工具
  • 新七建设集团有限公司网站网络平台推广方式
  • 站长之家收录查询百度推广开户多少钱一个月
  • 网站设计与制百度下载老版本
  • 怎样安装字体到wordpress上海专业seo
  • 兰州做网站哪家专业seo代理
  • 从什么网站找做app的代码手机百度电脑版入口
  • 广州做网站多网络新闻发布平台发稿
  • 国家政府网站2022世界足球排行榜
  • seo短视频网页入口引流网站有哪些石家庄seo外包公司
  • 海北高端网站建设多少钱如何在百度上发自己的广告?
  • 教育行业网站怎么样推广自己的公司
  • 企业网站模板 首页大图推广找客户平台
  • 无人在线观看免费高清电视剧网站优化推广服务
  • 成都企业做网站多少钱seo技术大师
  • 浙江做网站的公司游戏推广一个月能拿多少钱
  • 东莞市建设局seo网站外链工具
  • 网站banner尺寸重庆今天刚刚发生的重大新闻
  • 怎么用新浪云做淘宝客网站石家庄网站建设方案优化
  • 电商网站建设的核心是什么一个企业seo网站的优化流程
  • 免费空间 网站seo兼职招聘