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

自己买空间让网络公司做网站好吗网络推广项目外包公司

自己买空间让网络公司做网站好吗,网络推广项目外包公司,wordpress 代码质量,视频格式转换网页版Pytorch_Sequential使用、损失函数、反向传播和优化器 文章目录 nn.Sequential搭建小实战损失函数与反向传播优化器 nn.Sequential nn.Sequential是一个有序的容器,用于搭建神经网络的模块被按照被传入构造器的顺序添加到nn.Sequential()容器中。 import torch.nn …

Pytorch_Sequential使用、损失函数、反向传播和优化器

文章目录

    • nn.Sequential
    • 搭建小实战
    • 损失函数与反向传播
    • 优化器

nn.Sequential

nn.Sequential是一个有序的容器,用于搭建神经网络的模块被按照被传入构造器的顺序添加到nn.Sequential()容器中。

在这里插入图片描述

在这里插入图片描述

import torch.nn  as nn
from collections import OrderedDict
# Using Sequential to create a small model. When `model` is run,
# input will first be passed to `Conv2d(1,20,5)`. The output of
# `Conv2d(1,20,5)` will be used as the input to the first
# `ReLU`; the output of the first `ReLU` will become the input
# for `Conv2d(20,64,5)`. Finally, the output of
# `Conv2d(20,64,5)` will be used as input to the second `ReLU`
model = nn.Sequential(nn.Conv2d(1,20,5),nn.ReLU(),nn.Conv2d(20,64,5),nn.ReLU())# Using Sequential with OrderedDict. This is functionally the
# same as the above code
model = nn.Sequential(OrderedDict([('conv1', nn.Conv2d(1,20,5)),('relu1', nn.ReLU()),('conv2', nn.Conv2d(20,64,5)),('relu2', nn.ReLU())]))
print(model)
Sequential((conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))(relu1): ReLU()(conv2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))(relu2): ReLU()
)

搭建小实战

还是以 C I F A R − 10 m o d e l CIFAR-10 model CIFAR10model为例

在这里插入图片描述

  1. 输入图像是3通道的32×32的
  2. 先后经过卷积层(5×5的卷积核)
  3. 最大池化层(2×2的池化核)
  4. 卷积层(5×5的卷积核)
  5. 最大池化层(2×2的池化核)
  6. 卷积层(5×5的卷积核)
  7. 最大池化层(2×2的池化核)
  8. 拉直(flatten)
  9. 全连接层的处理,
  10. 最后输出的大小为10

基于以上的介绍,后续将利用Pytorch构建模型,实现 C I F A R − 10 m o d e l s t r u c t u r e CIFAR-10 \quad model \quad structure CIFAR10modelstructure

参数说明:in_channels: int、out_channels: int,kernel_size: Union由input、特征图以及卷积核即可看出,而stride、padding需要通过公式计算得到。

特得到的具体的特征图尺寸的计算公式如下:
在这里插入图片描述

inputs : 3@32x32,3通道32x32的图片,5*5的kernel --> 特征图(Feature maps) : 32@32x32

即经过32个3@5x5的卷积层,输出尺寸没有变化(有x个卷积核即由x个卷积核,卷积核的通道数与输入的通道数相等)

由上述的计算公式来计算出 s t r i d e stride stride p a d d i n g padding padding

在这里插入图片描述

卷积层中的stride默认为1

池化层中的stride默认为kernel_size的大小

import torch
import torch.nn as nn
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
class BS(nn.Module):def __init__(self):super().__init__()self.conv1 = nn.Conv2d(in_channels=3,out_channels=32,kernel_size=5,stride=1,padding=2)  #stride和padding计算得到self.maxpool1 = nn.MaxPool2d(kernel_size=2)self.conv2 = nn.Conv2d(in_channels=32,out_channels=32,kernel_size=5,stride=1,padding=2)self.maxpool2 = nn.MaxPool2d(kernel_size=2)self.conv3 = nn.Conv2d(in_channels=32,out_channels=64,kernel_size=5,padding=2)self.maxpool3 = nn.MaxPool2d(kernel_size=2)self.flatten = nn.Flatten()  #变为63*4*4=1024self.linear1 = nn.Linear(in_features=1024, out_features=64)self.linear2 = nn.Linear(in_features=64, out_features=10)def forward(self,x):x = self.conv1(x)x = self.maxpool1(x)x = self.conv2(x)x = self.maxpool2(x)x = self.conv3(x)x = self.maxpool3(x)x = self.flatten(x)x = self.linear1(x)x = self.linear2(x)return xbs = BS()
bs
BS((conv1): Conv2d(3, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))(maxpool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(conv2): Conv2d(32, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))(maxpool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(conv3): Conv2d(32, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))(maxpool3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(flatten): Flatten(start_dim=1, end_dim=-1)(linear1): Linear(in_features=1024, out_features=64, bias=True)(linear2): Linear(in_features=64, out_features=10, bias=True)
)

利用Sequential优化代码,并在tensorboard显示

.add_graph函数用于将PyTorch模型图添加到TensorBoard中。通过这个函数,您可以以可视化的方式展示模型的计算图,使其他人更容易理解您的模型结构和工作流程。

add_graph(model, input_to_model, strip_default_attributes=True)
  • model:要添加的PyTorch模型。
  • input_to_model:用于生成模型图的输入数据。
  • strip_default_attributes:是否删除模型中的默认属性,默认为True。
class BS(nn.Module):def __init__(self):super().__init__()self.model = nn.Sequential(nn.Conv2d(in_channels=3,out_channels=32,kernel_size=5,stride=1,padding=2),  #stride和padding计算得到nn.MaxPool2d(kernel_size=2),nn.Conv2d(in_channels=32,out_channels=32,kernel_size=5,stride=1,padding=2),nn.MaxPool2d(kernel_size=2),nn.Conv2d(in_channels=32,out_channels=64,kernel_size=5,padding=2),nn.MaxPool2d(kernel_size=2),nn.Flatten(),  #变为64*4*4=1024nn.Linear(in_features=1024, out_features=64),nn.Linear(in_features=64, out_features=10),)def forward(self,x):x = self.model(x)return xbs = BS()
print(bs)
BS((model): Sequential((0): Conv2d(3, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))(1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(2): Conv2d(32, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))(3): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(4): Conv2d(32, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))(5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)(6): Flatten(start_dim=1, end_dim=-1)(7): Linear(in_features=1024, out_features=64, bias=True)(8): Linear(in_features=64, out_features=10, bias=True))
)
# 在tensorboard中显示
input_ = torch.ones((64,3,32,32))
writer = SummaryWriter(".logs")
writer.add_graph(bs, input_)  # 定义的模型,数据
writer.close()

利用tensorboard可视化网络结构graph如下
在这里插入图片描述

损失函数与反向传播

计算模型目标输出和实际输出之间的误差。并通过反向传播算法更新模型的权重和参数,以减小预测输出和实际输出之间的误差。

  • 计算实际输出和目标输出之间的差距
  • 为更新输出提供一定依据(反向传播)

不同的模型用的损失函数一般也不一样。
在这里插入图片描述

平均绝对误差MAE Mean Absolute Error

torch.nn.L1Loss(size_average=None, reduce=None, reduction=‘mean’)

在这里插入图片描述

import torch
import torch.nn as nn
# 实例化
criterion1 = nn.L1Loss(reduction='mean')#mean
criterion2 = nn.L1Loss(reduction="sum")#sum
output = torch.tensor([1.0, 2.0, 3.0])#或dtype=torch.float32
target = torch.tensor([2.0, 2.0, 2.0])#或dtype=torch.float32
# 平均值损失值
loss = criterion1(output, target)
print(loss)  # 输出:tensor(0.6667)
# 误差和
loss1 = criterion2(output,target)
print(loss1) # tensor(2.)
tensor(0.6667)
tensor(2.)
loss = nn.L1Loss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward()
output
tensor(1.0721, grad_fn=<MeanBackward0>)

均方误差MSE Mean-Square Error
在这里插入图片描述

torch.nn.MSELoss(size_average=None, reduce=None, reduction=‘mean’)

在这里插入图片描述

import torch.nn as nn
# 实例化
criterion1 = nn.MSELoss(reduction='mean')
criterion2 = nn.MSELoss(reduction="sum")
output = torch.tensor([1, 2, 3],dtype=torch.float32)
target = torch.tensor([1, 2, 5],dtype=torch.float32)
# 平均值损失值
loss = criterion1(output, target)
print(loss)  # 输出:tensor(1.3333)
# 误差和
loss1 = criterion2(output,target)
print(loss1) # tensor(4.)
tensor(1.3333)
tensor(4.)

交叉熵损失 CrossEntropyLoss

torch.nn.CrossEntropyLoss(weight=None,size_average=None,ignore_index=-100,reduce=None,reduction='mean',label_smoothing=0.0)

当你有一个不平衡的训练集时,这是特别有用的
在这里插入图片描述

import torch
import torch.nn as nn# 设置三分类问题,假设是人的概率是0.1,狗的概率是0.2,猫的概率是0.3
x = torch.tensor([0.1, 0.2, 0.3])
print(x)
y = torch.tensor([1]) # 设目标标签为1,即0.2狗对应的标签,目标标签张量y
x = torch.reshape(x, (1, 3))  # tensor([[0.1000, 0.2000, 0.3000]]),批次大小为1,分类数3,即为3分类
print(x)
print(y)
# 实例化对象
loss_cross = nn.CrossEntropyLoss()
# 计算结果
result_cross = loss_cross(x, y)
print(result_cross)
tensor([0.1000, 0.2000, 0.3000])
tensor([[0.1000, 0.2000, 0.3000]])
tensor([1])
tensor(1.1019)
import torch
import torchvision
from torch.utils.data import DataLoader# 准备数据集
dataset = torchvision.datasets.CIFAR10(root="dataset",train=False,transform=torchvision.transforms.ToTensor(),download=True)
# 数据集加载器
dataloader = DataLoader(dataset, batch_size=1)
"""
输入图像是3通道的32×32的,
先后经过卷积层(5×5的卷积核)、
最大池化层(2×2的池化核)、
卷积层(5×5的卷积核)、
最大池化层(2×2的池化核)、
卷积层(5×5的卷积核)、
最大池化层(2×2的池化核)、
拉直、
全连接层的处理,
最后输出的大小为10
"""# 搭建神经网络
class BS(nn.Module):def __init__(self):super().__init__()self.model = nn.Sequential(nn.Conv2d(in_channels=3,out_channels=32,kernel_size=5,stride=1,padding=2),  #stride和padding计算得到nn.MaxPool2d(kernel_size=2),nn.Conv2d(in_channels=32,out_channels=32,kernel_size=5,stride=1,padding=2),nn.MaxPool2d(kernel_size=2),nn.Conv2d(in_channels=32,out_channels=64,kernel_size=5,padding=2),nn.MaxPool2d(kernel_size=2),nn.Flatten(),  #变为64*4*4=1024nn.Linear(in_features=1024, out_features=64),nn.Linear(in_features=64, out_features=10),)def forward(self, x):x = self.model(x)return x# 实例化
bs = BS()
loss = torch.nn.CrossEntropyLoss()
# 对每一张图片进行CrossEntropyLoss损失函数计算
# 使用损失函数loss计算预测结果和目标标签之间的交叉熵损失for inputs,labels in dataloader:outputs = bs(inputs)result = loss(outputs,labels)print(result)
tensor(2.3497, grad_fn=<NllLossBackward0>)
tensor(2.2470, grad_fn=<NllLossBackward0>)
tensor(2.2408, grad_fn=<NllLossBackward0>)
tensor(2.2437, grad_fn=<NllLossBackward0>)
tensor(2.3121, grad_fn=<NllLossBackward0>)
........

优化器

优化器(Optimizer)是用于更新神经网络参数的工具

它根据计算得到的损失函数的梯度来调整模型的参数,以最小化损失函数并改善模型的性能

在这里插入图片描述
常见的优化器包括:SGD、Adam

optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

model.parameters()用于获取模型的可学习参数

learning rate,lr表示学习率,即每次参数更新的步长

在每个训练批次中,需要执行以下操作:

  1. 输入训练数据到模型中,进行前向传播

  2. 根据损失函数计算损失

  3. 调用优化器的zero_grad()方法清零之前的梯度

  4. 调用backward()方法进行反向传播,计算梯度

  5. 调用优化器的step()方法更新模型参数

伪代码如下(运行不了的)

import torch
import torch.optim as optim# Step 1: 定义模型
model = ...
# Step 2: 定义优化器
optimizer = optim.SGD(model.parameters(), lr=0.01)
# Step 3: 定义损失函数
criterion = ...
# Step 4: 训练循环
for inputs, labels in dataloader:# 前向传播outputs = model(inputs)# 计算损失loss = criterion(outputs, labels)# 清零梯度optimizer.zero_grad()# 反向传播,得到梯度loss.backward()# 更新参数,根据梯度就行优化optimizer.step()

在上述模型代码中,SGD作为优化器,lr为0.01。同时根据具体任务选择适合的损失函数,例如torch.nn.CrossEntropyLoss、torch.nn.MSELoss等,以CIFRA10为例

import torch
import torch.optim as optim
import torchvision
from torch.utils.data import DataLoaderdataset = torchvision.datasets.CIFAR10(root="dataset", train=False, transform=torchvision.transforms.ToTensor(),download=True)
dataloader = DataLoader(dataset,batch_size=1)
class BS(nn.Module):def __init__(self):super().__init__()self.model = nn.Sequential(nn.Conv2d(in_channels=3,out_channels=32,kernel_size=5,stride=1,padding=2),  #stride和padding计算得到nn.MaxPool2d(kernel_size=2),nn.Conv2d(in_channels=32,out_channels=32,kernel_size=5,stride=1,padding=2),nn.MaxPool2d(kernel_size=2),nn.Conv2d(in_channels=32,out_channels=64,kernel_size=5,padding=2),nn.MaxPool2d(kernel_size=2),nn.Flatten(),  #变为64*4*4=1024nn.Linear(in_features=1024, out_features=64),nn.Linear(in_features=64, out_features=10),)def forward(self, x):x = self.model(x)return xmodel = BS()  #定义model
optimizer = optim.SGD(model.parameters(), lr=0.01)  #定义优化器SGD
criterion = nn.CrossEntropyLoss()  #定义损失函数,交叉熵损失函数'''循环一次,只对数据就行了一轮的学习'''
for inputs, labels in dataloader:# 前向传播outputs = model(inputs)# 计算损失loss = criterion(outputs, labels)# 清零梯度optimizer.zero_grad()# 反向传播loss.backward()# 更新参数optimizer.step()# 打印经过优化器后的结果print(loss)"""训练循环20次"""
# for epoch in range(20):
#     running_loss = 0.0
#     for inputs, labels in dataloader:
#         # 前向传播
#         outputs = model(inputs)
#         # 计算损失
#         loss = criterion(outputs,labels)
#         # 清零梯度
#         optimizer.zero_grad()
#         # 反向传播
#         loss.backward()
#         # 更新参数
#         optimizer.step()
#         # 打印经过优化器后的结果
#         running_loss = running_loss + loss
#     print(running_loss)
Files already downloaded and verified
tensor(2.3942, grad_fn=<NllLossBackward0>)
tensor(2.2891, grad_fn=<NllLossBackward0>)
tensor(2.2345, grad_fn=<NllLossBackward0>)
tensor(2.2888, grad_fn=<NllLossBackward0>)
tensor(2.2786, grad_fn=<NllLossBackward0>)
........

在这里插入图片描述


文章转载自:
http://kumpit.c7500.cn
http://television.c7500.cn
http://flatling.c7500.cn
http://bring.c7500.cn
http://corking.c7500.cn
http://dll.c7500.cn
http://lordotic.c7500.cn
http://unseeded.c7500.cn
http://fulfil.c7500.cn
http://spilikin.c7500.cn
http://sciaenoid.c7500.cn
http://bipartite.c7500.cn
http://dagger.c7500.cn
http://foxfire.c7500.cn
http://rudderless.c7500.cn
http://snotty.c7500.cn
http://transmogrification.c7500.cn
http://sverdrup.c7500.cn
http://glucogenic.c7500.cn
http://fianna.c7500.cn
http://centrality.c7500.cn
http://reconnoiter.c7500.cn
http://hydrophone.c7500.cn
http://parathyroid.c7500.cn
http://contradict.c7500.cn
http://geoelectricity.c7500.cn
http://catamite.c7500.cn
http://heelplate.c7500.cn
http://adjustment.c7500.cn
http://biramose.c7500.cn
http://cockchafer.c7500.cn
http://horoscopy.c7500.cn
http://incurrence.c7500.cn
http://dukedom.c7500.cn
http://teaboard.c7500.cn
http://microlitre.c7500.cn
http://pyronine.c7500.cn
http://rubbed.c7500.cn
http://sportfish.c7500.cn
http://delegate.c7500.cn
http://taking.c7500.cn
http://golan.c7500.cn
http://fixedness.c7500.cn
http://holoenzyme.c7500.cn
http://pantograph.c7500.cn
http://buster.c7500.cn
http://desired.c7500.cn
http://disarmament.c7500.cn
http://ineffectual.c7500.cn
http://emile.c7500.cn
http://symbology.c7500.cn
http://exorbitancy.c7500.cn
http://incurve.c7500.cn
http://uproariousness.c7500.cn
http://goalpost.c7500.cn
http://bellflower.c7500.cn
http://abraser.c7500.cn
http://unstick.c7500.cn
http://compress.c7500.cn
http://coagulant.c7500.cn
http://equinia.c7500.cn
http://straightedge.c7500.cn
http://precursor.c7500.cn
http://sclerodermia.c7500.cn
http://clotty.c7500.cn
http://jesuit.c7500.cn
http://beloid.c7500.cn
http://cymbiform.c7500.cn
http://stuggy.c7500.cn
http://fennelflower.c7500.cn
http://cubbyhouse.c7500.cn
http://heliotype.c7500.cn
http://subphylum.c7500.cn
http://castile.c7500.cn
http://mirthful.c7500.cn
http://holpen.c7500.cn
http://aton.c7500.cn
http://hurtfully.c7500.cn
http://exsection.c7500.cn
http://popout.c7500.cn
http://miskick.c7500.cn
http://micrometer.c7500.cn
http://accomplice.c7500.cn
http://meto.c7500.cn
http://sheep.c7500.cn
http://civilized.c7500.cn
http://filicide.c7500.cn
http://banal.c7500.cn
http://biserial.c7500.cn
http://beaten.c7500.cn
http://electrization.c7500.cn
http://patentee.c7500.cn
http://rootlike.c7500.cn
http://mastery.c7500.cn
http://between.c7500.cn
http://heterogamete.c7500.cn
http://extemporary.c7500.cn
http://hydronic.c7500.cn
http://carbonatation.c7500.cn
http://cholecalciferol.c7500.cn
http://www.zhongyajixie.com/news/97338.html

相关文章:

  • 怎么做外贸网站优化广州竞价托管
  • 建网站有哪些费用seo标签优化
  • 政府网站建设内容规划seo课程在哪培训好
  • 出入库管理系统软件网站推广优化的原因
  • 做网站如何分页百度经验官网入口
  • 佛山网站代运营搜索网站哪个好
  • 视频模板长沙整站优化
  • wordpress 删除作者惠州seo代理
  • 监控摄像头做直播网站怎么在网上推广产品
  • 网站备案费用多少有人看片吗免费观看视频
  • 温州外贸公司网站建设公司排名培训心得体会800字
  • 2019做什么类型网站公司网站怎么建立
  • 导航网站建设新乡网站seo
  • 泸州网站建设小红书seo优化
  • 专业建站公司建站系统百度的营销推广
  • 做学校后台网站企业网站设计论文
  • 在外国租服务器做那种网站seo外链怎么发
  • 小网站下载渠道有哪些手机上可以创建网站吗
  • 网站正建设中长沙网络推广
  • 有什么字体设计网站好外链平台
  • 网站服务器建设学电脑培训班多少一个月
  • 什么叫网站流量文案写作软件app
  • 浙江网站建设哪家好国外引流推广平台
  • 网站中查看熊掌号怎么做的友情链接收录
  • 怎么自己做网站表白销售
  • 邢台wap网站建设营销策划方案案例
  • app制作教程下载关键词优化
  • 做百度药材种苗网站东莞seo关键词排名优化排名
  • 兰州的互联网公司资源网站快速优化排名
  • 网站开发安全性分析黄页污水