当前位置:网站首页>【简易笔记】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 refers to the offer 21. Adjust the order of the array so that the odd numbers are in front of the even numbers (simple)
Test of the opposite sex what you look like?
LeetCode 剑指offer 10-I.斐波那契数列(简单)
深度学习阶段性报告(一)
pytorch-06. Logistic regression
Pytorch配置与实战--Tips
Chain Reading Recommendation: From Tiles to Generative NFTs
Convolutional Neural Network (CNN) for Clothing Image Classification
先人一步,不再错过,链读APP即将上线!
LeetCode 1894.找到需要补充粉笔的学生编号
随机推荐
Common class BigDecimal
wiki confluence installation
win12 modify dns script
Notes for SVM
Mini Program Study Notes: Communication between Mini Program Components
pytorch-11.卷积神经网络(高级篇)
细说MySql索引原理
cesium listens to map zoom or zoom to control whether the content added on the map is displayed
pytorch-06. Logistic regression
Chain Reading Good Article: Jeff Garzik Launches Web3 Production Company
Common class String overview
pytorch-10.卷积神经网络(作业)
String常用方法
Smart contracts and DAPP decentralized applications
Reflection 【Notes】
Collection set interface
【笔记】集合框架体系 Collection
Database Notes Create Database, Table Backup
Knowledge Distillation Thesis Learning
堆的原理与实现以及排序