今天是本人学习Pytorch的第一天。简单介绍一下什么是Pytorch吧。
Pytorch
Pytorch是torch的python版本,是由Facebook开源的神经网络框架,专门针对 GPU 加速的深度神经网络(DNN)编程。与Tensorflow的静态计算图不同,pytorch的计算图是动态的,可以根据计算需要实时改变计算图。目前来说,pytorch有一个越来越热门的趋势,原因可能就是其学习成本相对较低,可以快速上手。
本文不介绍Pytorch如何安装了(毕竟本人刚刚入门),这篇博客的内容主要来自唐宇迪的课件,内容就不做过多的原创了。对我而言,目前能把迪哥讲的内容吃透就很满足了。
学习方法
- 1.边用边学,Torch只是一个工具,真正用,查的过程才是学的过程
- 2.直接上案例就行,先来跑,遇到问题再上网搜索
- 3.有一定面向对象的基础
Mnist分类任务:
-
网络基本构建与训练方法,常用函数解析
-
torch.nn.functional模块
-
nn.Module模块
读取Mnist数据集
- 会自动进行下载
import torch
print(torch.__version__)
2.4.1
%matplotlib inline
from pathlib import Path
DATA_PATH = Path("data")
PATH = DATA_PATH / "mnist"
FILENAME = "mnist.pkl.gz"
import pickle
import gzip
with gzip.open((PATH / FILENAME).as_posix(), "rb") as f:
((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding="latin-1")
其中,784是mnist数据集每个样本的像素点,50000行是样本个数,784是图像数据的特征点
print(x_train.shape,y_train.shape)
((50000, 784), (50000,))
from matplotlib import pyplot
import numpy as np
pyplot.figure(figsize=(1.5,2))
pyplot.imshow(x_train[0].reshape((28, 28)), cmap="gray")
pyplot.show()
整个框架的结构图
单个样本计算的过程图
其中输出的是各个类别的概率(亦可能是数值),选取最大值作为预测值
隐藏层的结构可以根据需求进行变化,但层数一般是 2 n 2^n 2n
注意数据需转换成tensor才能参与后续建模训练
数据类型转换
转换前的数据结构
#n是样本个数,c是特征个数(样本点)
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())#由此可以看出,这是一个十分类的任务
[[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.]][5, 0, 4, ..., 8, 4, 8]
(50000,784)
0 9
map映射------将array变成tensor
#此时y_train是数组格式
y_train[0:10]
array([5, 0, 4, 1, 9, 2, 1, 3, 1, 4], dtype=int64)
#做map映射,将数据类型转换成tensor
x_train