电子商务网站开发教程论文6,网站建设横幅,黄酒的电商网页设计网站,互联网定制产品网站文章目录 在MINST-FASHION上实现神经网络的学习流程1. 导库2. 导入数据#xff0c;分割小批量3. 定义神经网络4.定义训练函数5.进行训练与评估 在MINST-FASHION上实现神经网络的学习流程
现在我们要整合本节课中所有的代码实现一个完整的训练流程。 首先要梳理一下整个流程分割小批量3. 定义神经网络4.定义训练函数5.进行训练与评估 在MINST-FASHION上实现神经网络的学习流程
现在我们要整合本节课中所有的代码实现一个完整的训练流程。 首先要梳理一下整个流程 1)设置步长lr,动量值 g a m m a gamma gamma ,迭代次数 e p o c h s epochs epochs , b a t c h _ s i z e batch\_size batch_size等信息如果需要设置初始权重 w 0 w_0 w0 2)导入数据将数据切分成 b a t c h _ s i z e batch\_size batch_size 3)定义神经网络架构 4)定义损失函数 L ( w ) L(w) L(w),如果需要的话将损失函数调整成凸函数以便求解最小值 5)定义所使用的优化算法 6)开始在 e p o c h e s epoches epoches 和 b a t c h batch batch上循环执行优化算法 6.1)调整数据结构确定数据能够在神经网络、损失函数和优化算法中顺利运行;6.2)完成向前传播计算初始损失6.3)利用反向传播在损失函数 L ( w ) L(w) L(w)上对每一个 w w w求偏导数6.4)迭代当前权重6.5)清空本轮梯度6.6)完成模型进度与效果监控 7)输出结果
1. 导库
这次我们要使用PyTorch中自带的数据MINST-FATION。
import torch
from torch import nn
from torch import optim
from torch.nn import functional as F
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader
#确定数据、确定优先需要设置的值
lr 0.15
gamma 0
epochs 10
bs 1282. 导入数据分割小批量 import torchvision
import torchvision.transforms as transforms#初次运行时会下载需要等待较长时间
mnist torchvision.datasets.FashionMNIST(rootC:\Pythonwork\DEEP LEARNING\Datasets\FashionMNIST,trainTrue, downloadTrue, transformtransforms.ToTensor())len(mnist)#查看特征张量mnist.data#这个张量结构看起来非常常规可惜的是它与我们要输入到模型的数据结构有差异#查看标签
mnist.targets#查看标签的类别
mnist.classes
#查看图像的模样
import matplotlib.pyplot as plt
plt.imshow(mnist[0][0].view((28, 28)).numpy());plt.imshow(mnist[1][0].view((28, 28)).numpy());#分割batch
batchdata DataLoader(mnist,batch_sizebs, shuffle True)
#总共多少个batch?
len(batchdata)
#查看会放入进行迭代的数据结构
for x,y in batchdata:print(x.shape)print(y.shape)breakinput_ mnist.data[0].numel() #特征的数目一般是第一维之外的所有维度相乘的数
output_ len(mnist.targets.unique()) #分类的数目#最好确认一下没有错误input_output_#
import torchvision
import torchvision.transforms as transforms
mnist torchvision.datasets.FashionMNIST(root~/Datasets/FashionMNIST, trainTrue, downloadFalse, transformtransforms.ToTensor())
batchdata DataLoader(mnist,batch_sizebs, shuffle True)
input_ mnist.data[0].numel()
output_ len(mnist.targets.unique()
3. 定义神经网络
class Model(nn.Module):def __init__(self,in_features10,out_features2):super().__init__()#self.normalize nn.BatchNorm2d(num_features1)self.linear1 nn.Linear(in_features,128,biasFalse)self.output nn.Linear(128,out_features,biasFalse)def forward(self, x):#x self.normalize(x)x x.view(-1, 28*28)#需要对数据的结构进行一个改变这里的“-1”代表我不想算请pytorch帮我计算sigma1 torch.relu(self.linear1(x))z2 self.output(sigma1)sigma2 F.log_softmax(z2,dim1)return sigma24.定义训练函数
def fit(net,batchdata,lr0.01,epochs5,gamma0):criterion nn.NLLLoss() #定义损失函数opt optim.SGD(net.parameters(), lrlr,momentumgamma) #定义优化算法correct 0samples 0for epoch in range(epochs):for batch_idx, (x,y) in enumerate(batchdata):y y.view(x.shape[0])sigma net.forward(x)loss criterion(sigma,y)loss.backward()opt.step()opt.zero_grad()#求解准确率yhat torch.max(sigma,1)[1]correct torch. sum Cyhat y)samples x. shape [ o]if (batch_ idx 1) % 125 o or batch_ idx len (batchdata)-1:print( Epocht: [ / (:of] % ) ] tLoss : 6ft Accuracy::.3f].format(epoch1 , samples ,len( batchdata. dataset) * epochs,100* samples/ ( len (batchdata. dataset)epochs),loss.data.item(),float(correct*100)/samples))
5.进行训练与评估
#实例化神经网络调用优化算法需要的参数
torch. manualseed(420)
net Mode ( in_ features input_ out_featuresoutput_)
fit( net, batchdata, lr lr, epochs epochs, gammagamma)我们现在已经完成了一个最基本的、神经网络训练并查看训练结果的代码。