当前位置:网站首页>【简易笔记】PyTorch官方教程简易笔记 EP2
【简易笔记】PyTorch官方教程简易笔记 EP2
2022-08-10 05:34:00 【Mioulo】
已完结…
记录PyTorch 官方入门教程中的大部分代码和对代码的解释注释
暂时内容包括:构建一个神经网络
参考网站:https://pytorch.org/tutorials/beginner/
/buildmodel_tutorial.html
构建神经网络
import os
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from zmq import device
if torch.cuda.is_available:
device = "cuda"
print("cuda加速已开启")
else:
device = "cpu"
这一段是设置对张量的加速设置,cuda对应着GPU加速,需要用到N卡的cuda
class NeuralNetwork(nn.Module):
def __init__(self):
super().__init__()
NeuralNetwork.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512,258),
nn.ReLU(),
nn.Linear(258, 10),
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork().to(device)
print(model)
这里是构建这个神经网络类,下面对每部分代码一一注释解释
super().__init__()
以nn.Module为父类创建他的子类,这个函数是用于设定继承父类的方法
self.flatten = nn.Flatten()
这是一个用于压平的函数,对应着之前理论的例子,在进行机器学习时,通常会把数据进行压平(如 28* 28 压为 1* 784)
我们这个子类继承于nn.flatten函数
函数参考:nn.flatten
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512,258),
nn.ReLU(),
nn.Linear(258, 10),
如其所示linear是线性分类器,ReLU是一最常见而经典的激活函数
这样设置相当于四层,输入维度为28* 28(1*784),最终输出10个特征值
函数参考:Sequential
Linear
ReLU
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
这里就开始定义,x即为压平后的张量,logits就是打包后的一个分类器
到此为止,这个类的定义完毕
model = NeuralNetwork().to(device)
print(model)
创建一个对象model,将实例化后的模型(NeuralNetwork)传递给设置好的设备(cuda or cpu)并赋值给这个对象model
之后进行输出这个对象model
X = torch.rand(1, 28, 28, device=device)
logits = model(X)
pred_probab = nn.Softmax(dim=1)(logits)
# softmax = nn.Softmax(dim=1)
# pred_probab = softmax(logits)
#归一化时也可以这样操作,一样的
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {
y_pred}")
那么我们用随机数将这个与分类器形式对应的张量初始化
由之前的知识(这个X就是我们想要优化的参数??)
之后用softmanx函数将输出的10个特征值进行归一化
之后的argmax函数是输出归一化后的pred_probab这个张量在这个维度最大的值的序号
函数参考:Softmax
argmax
input_image = torch.rand(3,28,28)
# print(input_image.size())
flatten = nn.Flatten()
# flat_image = flatten(input_image)
# print(flat_image.size())
layer1 = nn.Linear(in_features=28*28, out_features=20)
# hidden1 = layer1(flat_image)
# print(hidden1.size())
# print(f"Before ReLU: {hidden1}\n\n")
# hidden1 = nn.ReLU()(hidden1)
# print(f"After ReLU: {hidden1}")
seq_modules = nn.Sequential(
flatten,
layer1,
nn.ReLU(),
nn.Linear(20, 10)
)
logits = seq_modules(input_image)
这里我们就创建一个所谓的图像(这个张量为3通道2828大小的图像)
然后将这个图像压平(就像之前我们对那个参数X的操作一样,只不过之前是写在类里面的)
创建一个线性分类器并命名为layer1,与上面一样输入为2828,输出为20
(让这个图形输入后将输出部分命名为hidden1,即隐藏层)
然后用激活函数ReLU对这个图像的隐藏层进行处理(这个图像现在还是三通道的)
seq_modules写的是对这个图像进行处理的步骤进行打包,与之前写的那个类里类似
for name, param in model.named_parameters():
print(f"Layer: {
name} | Size: {
param.size()} | Values : {
param[:2]} \n")
param意为参数,用named_parameters这个迭代器循环遍历各层中的参数
函数参考:有关python中切片的介绍
边栏推荐
猜你喜欢
随机推荐
LeetCode 938.二叉搜索树的范围和(简单)
The submenu of the el-cascader cascade selector is double-clicked to display the selected content
Convolutional Neural Network (CNN) for mnist handwritten digit recognition
一个基于.Net Core 开源的物联网基础平台
IO流【】【】【】
sqlplus displays the previous command and the available backspace key
LeetCode 162.寻找峰值(中等)
Common class String overview
基于 .NET Core MVC 的权限管理系统
opencv
Linux数据库Oracle客户端安装,用于shell脚本用sqlplus连接数据库
LeetCode 94. Inorder Traversal of Binary Trees (Simple)
Smart contracts and DAPP decentralized applications
The way for programmers to make money from a sideline business and increase their monthly income by 20K
Chain Reading Recommendation: From Tiles to Generative NFTs
符号表
Copy large files with crontab
Notes for RNN
集合 Map
Chain Reading|The latest and most complete digital collection sales calendar-07.29









