当前位置:网站首页>pytorch基本操作:使用神经网络进行分类任务
pytorch基本操作:使用神经网络进行分类任务
2022-08-02 05:11:00 【樱花的浪漫】
1.读取Mnist数据
首先,读取Mnist数据,在深度学习框架中,数据的基本结构是tensor,据需转换成tensor才能参与后续建模训练,可用map函数将数据转换为tensor格式
import torch
x_train, y_train, x_valid, y_valid = map(
torch.tensor, (x_train, y_train, x_valid, y_valid)
)
n, c = x_train.shape
x_train, x_train.shape, y_train.min(), y_train.max()
print(x_train, y_train)
print(x_train.shape)
print(y_train.min(), y_train.max())
2.torch.nn.functional
torch.nn.functional中有很多功能, 比如,常见的激活函数、损失函数,一般情况下,如果模型有可学习的参数,最好用nn.Module,其他情况nn.functional相对更简单一些

3.创建一个model
- 必须继承nn.Module且在其构造函数中需调用nn.Module的构造函数
- 无需写反向传播函数,nn.Module能够利用autograd自动实现反向传播
- Module中的可学习参数可以通过named_parameters()或者parameters()返回迭代器
from torch import nn
class Mnist_NN(nn.Module):
def __init__(self):
super().__init__()
self.hidden1 = nn.Linear(784, 128)
self.hidden2 = nn.Linear(128, 256)
self.out = nn.Linear(256, 10)
def forward(self, x):
x = F.relu(self.hidden1(x))
x = F.relu(self.hidden2(x))
x = self.out(x)
return x
打印出来:
通过named_parameters()或者parameters()返回迭代器

4.使用TensorDataset和DataLoader加载数据
TensorDataset:将训练数据的特征和标签组合
DataLoader:随机读取小批量
5.训练模块
梯度下降方法和损失函数

torch默认会叠加梯度,所以结束后需要将梯度置零
- 一般在训练模型时加上model.train(),这样会正常使用Batch Normalization和 Dropout
- 测试的时候一般选择model.eval(),这样就不会使用Batch Normalization和 Dropout
import numpy as np
def fit(steps, model, loss_func, opt, train_dl, valid_dl):
for step in range(steps):
model.train()
for xb, yb in train_dl:
loss_batch(model, loss_func, xb, yb, opt)
model.eval()
with torch.no_grad(): # 验证时不进行梯度下降
losses, nums = zip(
*[loss_batch(model, loss_func, xb, yb) for xb, yb in valid_dl]
)
val_loss = np.sum(np.multiply(losses, nums)) / np.sum(nums) # 平均损失
print('当前step:'+str(step), '验证集损失:'+str(val_loss))
边栏推荐
- [C language] LeetCode26. Delete duplicates in an ordered array && LeetCode88. Merge two ordered arrays
- 构造方法、成员变量、局部变量
- MySql将一张表的数据copy到另一张表中
- 分布式文件存储服务器之Minio对象存储技术参考指南
- C language: Check for omissions and fill in vacancies (3)
- 利用浏览器本地存储 实现记住用户名的功能
- C语言基础知识梳理总结:零基础入门请看这一篇
- Cyber Security Learning - Intranet Penetration 4
- Navicat报错:1045 -拒绝访问用户[email protected](使用passwordYES)
- navicat无法连接mysql超详细处理方法
猜你喜欢
随机推荐
The company does not pay attention to software testing, and the new Ali P8 has written a test case writing specification for us
说好的女程序员做测试有优势?面试十几家,被面试官虐哭~~
21天学习挑战赛安排
ATM系统
关于鸿蒙系统 JS UI 框架源码的分析
Navicat报错:1045 -拒绝访问用户[email protected](使用passwordYES)
[PSQL] window function, GROUPING operator
构造方法、成员变量、局部变量
浏览器的onload事件
Cyber Security Learning - Intranet Penetration 4
navicat无法连接mysql超详细处理方法
165.比较版本号
There are more and more talents in software testing. Why are people still reluctant to take the road of software testing?
关于web应用的目录结构
golang环境详细安装、配置
classSR论文阅读笔记
eggjs controller层调用controller层解决方案
C竞赛训练
5年在职经验之谈:2年功能测试、3年自动化测试,从入门到不可自拔...
51 MCU peripherals: DS18B20







![[PSQL] window function, GROUPING operator](/img/95/5c9dc06539330db907d22f84544370.png)

