由浅入深,走进深度学习(5)

本期的内容是线性回归以及Softmax回归,损失函数,分类

个人感受:动手敲一遍,带着思考,会有不一样的感受!!!

代码是比较多的,有很多内容我也是都在代码上面注释了~

这次的内容比之前几次的会稍微复杂一点,说一下我自己的想法:动手敲一遍代码,体会一下,因为后期自己设计网络的时候,可以直接调用呢~~

正片开始!!!

# 自动求导
import torch
x = torch.arange(4.0)
print(x)

# 在外面计算y关于x的梯度之前 需要一个地方来存储梯度
x.requires_grad_(True) # 等价于 x = torch.arange(4.0,requires_grad=True)
print(x.grad)

xx = torch.arange(4.0, requires_grad = True) # xx.grad是存梯度的地方,默认为None,即还没有求导求出梯度出来
print(xx.grad)

# 现在计算y
y = 2 * torch.dot(x, x)
print(y) # grad_fn是隐式的构造了梯度函数

# 通过调用反向传播函数来自动计算y关于x每个分量的梯度
y.backward() # 反向传播后会有梯度计算出来
print(x.grad) # 访问导数 即访问梯度
print(x.grad == 4*x) # 4 * x 是 2 * x * x 的导数



# 在深度学习中,目的不是计算微分矩阵,而是批量中每个样本单独计算的偏导数之和
import torch
x = torch.arange(4.0, requires_grad = True)
y = 2 * torch.dot(x, x)
y.backward()
# 默认情况下,PyTorch会累积梯度,需要清除之前的值
# 对非标量调用 'backward' 需要传入一个 'gradient' 参数,该参数指定微分函数
x.grad.zero_()
y = x * x  # 这里的y不是一个标量,这是一个向量
print(y)
# 等价于y.backward(torch.ones(len(x)))
y.sum().backward() # y.sum()后就将向量转为标量了,对标量求导
x.grad
# 线性回归
# 将从零开始实现整个方法,包括数据流水线、模型、损失函数和小批量随即梯度下降优化器
# 生成数据集
import torch
import random
from d2l import torch as d2l

def synthetic_data(w, b, num_examples):
    """生成 y = Xw + b + 噪声"""
    X = torch.normal(0, 1, (num_examples, len(w)))
    print('X.shape:', X.shape)
    y = torch.matmul(X, w) + b
    print('y.shape:', y.shape)
    y += torch.normal(0, 0.01, y.shape)
    print('y.shape:', y.shape)
    return X, y.reshape((-1, 1))

true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)
print('features.shape:', features.shape)
print('labels.shape', labels.shape)

# 绘制数据集
# features中每一行都包含一个二维数据样本,labels中的每一行都包含一维标签值(一个标签)
print('features:', features[0], '\nlabels:', labels[0])
d2l.set_figsize()
d2l.plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1) # 只有detach后才能转到numpy里面去    

print('----------------------------------')
# 读取小批量
# data_iter函数接收批量大小、特征矩阵和标签向量作为输入,生成大小为batch_size的小批量
def data_iter(batch_size, features, labels):
    num_examples = len(features) # 样本个数
    print(num_examples)
    indices = list(range(num_examples)) # 样本索引
    # 这些样本是随即读取的,没有特定的顺序
    # print(indices)
    random.shuffle(indices)  # 把索引随即打乱
    for i in range(0, num_examples, batch_size):
        batch_indices = torch.tensor(indices[i:min(i+batch_size, num_examples)]) # 当i+batch_size超出时 取num_examples   
        yield features[batch_indices], labels[batch_indices] # 获得随即顺序的特征 及对应的标签

batch_size = 10
for X, y in data_iter(batch_size, features, labels):
    print(X, '\n', y) # 取一个批次后 就break跳出了
    break

# 定义初始化模型参数
w = torch.normal(0, 0.01, size = (2, 1), requires_grad = True)
b = torch.zeros(1, requires_grad = True)

# 定义模型
def linreg(X, w, b):
    """线性回归模型"""
    return torch.matmul(X, w) + b

# 定义损失函数
def squared_loss(y_hat, x):
    """军方误差"""
    return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2

# 定义优化算法
def sgd(params, lr, batch_size):
    """小批量随机梯度下降"""
    with torch.no_grad(): # 不要产生梯度计算 减少内存消耗
        for param in params:  # 每个参数进行遍历
            param -= lr * param.grad / batch_size
            # 每个参数进行更新 损失函数没有求均值 所以这里除以 batch_size 求了均值 由于乘法的线性关系 这里除以放在loss的除以是等价的。
            param.grad.zero_() # 每个参数的梯度清零

# 训练过程
lr = 0.03
num_epoch = 3
net = linreg # 这里用线性模型 这样写是很方便net赋予其他模型 只需要改一处 不需要下面所有网络模型名称都改
loss = squared_loss

for epoch in range(num_epoch):
    for X, y in data_iter(batch_size, features, labels):
        l = loss(net(X, w, b), y) # x和y的小批量损失
        # 因为l是形状是(batch_size,1) 而不是一个标量 l中所有元素被加到一起
        # 并以此计算关于[w,b]的梯度
        l.sum().backward()
        sgd([w, b], lr, batch_size)  #使用参数的梯度更新参数
    with torch.no_grad():
        train_l = loss(net(X, w, b), labels)
        print(f'epoch{epoch + 1}, loss{float(train_l.mean()): f}')

# 比较真实参数和通过训练学到的参数来评估训练的成功程度
print(f'w 的估计误差:{true_w - w.reshape(true_w.shape)}')
print(f'b 的估计误差:{true_b - b}')
# 线性回归 使用框架
import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l
from torch import nn


true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)  # 库函数生成人工数据集    

def load_array(data_arrays, batch_size, is_train = True):
    """构造一个Pytorch数据迭代器"""
    dataset = data.TensorDataset(*data_arrays) # dataset相当于Pytorch的Dataset 一个星号* 表示对list解开入参
    return data.DataLoader(dataset, batch_size, shuffle = is_train)  # 返回的是从dataset中随机挑选出batch_size个样本出来

batch_size = 10
data_iter = load_array((features, labels), batch_size) # 返回的数据的迭代器
print(next(iter(data_iter))) # iter(data_iter) 是一个迭代器对象 next是取迭代器里面的元素 

# 使用框架的预定义好的层
# nn是神经网络的缩写
net = nn.Sequential(nn.Linear(2, 1))

# 初始化模型参数
net[0].weight.data.normal_(0, 0.01)  # 使用正态分布替换掉weight变量里面的数据值
net[0].bias.data.fill_(0) # 偏差bias变量里面的值设置为0
print(net[0])

# 计算均方误差使用的是MSELoss类  也称为平方L2范数
loss = nn.MSELoss() #L1是算术差,L2是平方差

# 实例化SGD
trainer = torch.optim.SGD(net.parameters(), lr = 0.03)

# 训练过程代码从零开始时非常相似
num_epoch = 3
for epoch in range(num_epoch):
    for X, y in data_iter: # 从DataLoader里面一次一次把所有数据拿出来
        # print('X:', X)
        # print('y:', y)
        l = loss(net(X), y) # net(X) 为计算出来的线性回归的预测值
        trainer.zero_grad()  # 梯度清零
        l.backward()
        trainer.step() # SGD优化器优化模型
    l = loss(net(features), labels)
    print(f'epoch{epoch + 1},loss{l:f}')

使用Softmax完整的训练测试

import torch
import torchvision
from torch.utils import data
from torchvision import transforms
from d2l import torch as d2l
from IPython import display

def get_dataloader_workers():
    """使用4个进程来读取的数据"""
    return 0

def load_data_fashion_mnist(batch_size, resize=None):
    """下载Fashion-MNIST数据集,然后将其加载到内存中"""
    trans = [transforms.ToTensor()]
    if resize:
        trans.insert(0,transforms.Resize(resize)) # 如果有Resize参数传进来,就进行resize操作
    trans = transforms.Compose(trans)
    mnist_train = torchvision.datasets.FashionMNIST(root="mnist_data",train=True,transform=trans,download=True)
    mnist_test = torchvision.datasets.FashionMNIST(root="mnist_data",train=False,transform=trans,download=True)            
    return (data.DataLoader(mnist_train, batch_size, shuffle=True, num_workers=get_dataloader_workers()),
           data.DataLoader(mnist_train, batch_size, shuffle=True, num_workers=get_dataloader_workers()))               


batch_size = 256
train_iter, test_iter = load_data_fashion_mnist(batch_size) # 返回训练集、测试集的迭代器     

num_inputs = 784
num_outputs = 10
w = torch.normal(0,0.01,size=(num_inputs,num_outputs),requires_grad=True)
b = torch.zeros(num_outputs,requires_grad=True)

def softmax(X):
    X_exp = torch.exp(X) # 每个都进行指数运算
    partition = X_exp.sum(1,keepdim=True) 
    return X_exp / partition # 这里应用了广播机制

# 实现softmax回归模型
def net(X):
    return softmax(torch.matmul(X.reshape((-1,w.shape[0])),w)+b) # -1为默认的批量大小,表示有多少个图片,每个图片用一维的784列个元素表示      

def cross_entropy(y_hat, y):
    return -torch.log(y_hat[range(len(y_hat)),y]) # y_hat[range(len(y_hat)),y]为把y的标号列表对应的值拿出来。传入的y要是最大概率的标号      

def accuracy(y_hat,y):
    """计算预测正确的数量"""
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1: # y_hat.shape[1]>1表示不止一个类别,每个类别有各自的概率   
        y_hat = y_hat.argmax(axis=1) # y_hat.argmax(axis=1)为求行最大值的索引
    cmp = y_hat.type(y.dtype) == y # 先判断逻辑运算符==,再赋值给cmp,cmp为布尔类型的数据
    return float(cmp.type(y.dtype).sum()) # 获得y.dtype的类型作为传入参数,将cmp的类型转为y的类型(int型),然后再求和       

# 可以评估在任意模型net的准确率
def evaluate_accuracy(net,data_iter):
    """计算在指定数据集上模型的精度"""
    if isinstance(net,torch.nn.Module): # 如果net模型是torch.nn.Module实现的神经网络的话,将它变成评估模式     
        net.eval()  # 将模型设置为评估模式
    metric = Accumulator(2) # 正确预测数、预测总数,metric为累加器的实例化对象,里面存了两个数
    for X, y in data_iter:
        metric.add(accuracy(net(X),y),y.numel()) # net(X)将X输入模型,获得预测值。y.numel()为样本总数
    return metric[0] / metric[1] # 分类正确的样本数 / 总样本数

# Accumulator实例中创建了2个变量,用于分别存储正确预测的数量和预测的总数量
class Accumulator:
    """在n个变量上累加"""
    def __init__(self,n):
        self.data = [0,0] * n
        
    def add(self, *args):
        self.data = [a+float(b) for a,b in zip(self.data,args)] # zip函数把两个列表第一个位置元素打包、第二个位置元素打包....
        
    def reset(self):
        self.data = [0.0] * len(self.data)
        
    def __getitem__(self,idx):
        return self.data[idx]

# 训练函数
def train_epoch_ch3(net, train_iter, loss, updater):
    if isinstance(net, torch.nn.Module):
        net.train() # 开启训练模式
    metric = Accumulator(3)
    for X, y in train_iter:
        y_hat = net(X)
        l = loss(y_hat,y) # 计算损失
        if isinstance(updater, torch.optim.Optimizer): # 如果updater是pytorch的优化器的话
            updater.zero_grad()
            l.mean().backward()  # 这里对loss取了平均值出来
            updater.step()
            metric.add(float(l)*len(y),accuracy(y_hat,y),y.size().numel()) # 总的训练损失、样本正确数、样本总数   
        else:
            l.sum().backward()
            updater(X.shape[0])
            metric.add(float(l.sum()),accuracy(y_hat,y),y.numel()) 
    return metric[0] / metric[2], metric[1] / metric[2] # 所有loss累加除以样本总数,总的正确个数除以样本总数  


    
class Animator:
    def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
                ylim=None, xscale='linear',yscale='linear',
                fmts=('-','m--','g-.','r:'),nrows=1,ncols=1,
                figsize=(3.5,2.5)): 
        if legend is None:
            legend = []
        d2l.use_svg_display()
        self.fig, self.axes = d2l.plt.subplots(nrows,ncols,figsize=figsize)
        if nrows * ncols == 1:
            self.axes = [self.axes,]
        self.config_axes = lambda: d2l.set_axes(self.axes[0],xlabel,ylabel,xlim,ylim,xscale,yscale,legend)         
        self.X, self.Y, self.fmts = None, None, fmts
        
    def add(self, x, y):
        if not hasattr(y, "__len__"):
            y = [y]
        n = len(y)
        if not hasattr(x, "__len__"):
            x = [x] * n
        if not self.X:
            self.X = [[] for _ in range(n)] 
        if not self.Y:
            self.Y = [[] for _ in range(n)]
        for i, (a,b) in enumerate(zip(x,y)):
            if a is not None and b is not None:
                self.X[i].append(a)
                self.Y[i].append(b)
        self.axes[0].cla()
        for x, y, fmt in zip(self.X, self.Y, self.fmts):
            self.axes[0].plot(x, y, fmt)
        self.config_axes()
        display.display(self.fig)
        display.clear_output(wait=True)

# 总训练函数        
def train_ch3(net,train_iter,test_iter,loss,num_epochs,updater):
    animator = Animator(xlabel='epoch',xlim=[1,num_epochs],ylim=[0.3,0.9],       
                       legend=['train loss','train acc','test acc'])
    for epoch in range(num_epochs):  # 变量num_epochs遍数据
        train_metrics = train_epoch_ch3(net,train_iter,loss,updater) # 返回两个值,一个总损失、一个总正确率
        test_acc = evaluate_accuracy(net, test_iter) # 测试数据集上评估精度,仅返回一个值,总正确率  
        animator.add(epoch+1,train_metrics+(test_acc,)) # train_metrics+(test_acc,) 仅将两个值的正确率相加,
    train_loss, train_acc = train_metrics
    
# 小批量随即梯度下降来优化模型的损失函数
lr = 0.1
def updater(batch_size):
    return d2l.sgd([w,b],lr,batch_size)

num_epochs = 10
train_ch3(net,train_iter,test_iter,cross_entropy,num_epochs,updater)

# 预测数据
def predict_ch3(net,test_iter,n=6):
    for X, y in test_iter: 
        break # 仅拿出一批六个数据
    trues = d2l.get_fashion_mnist_labels(y)
    preds = d2l.get_fashion_mnist_labels(net(X).argmax(axis=1))
    titles = [true + '\n' + pred for true, pred in zip(trues,preds)]
    d2l.show_images(X[0:n].reshape((n,28,28)),1,n,titles=titles[0:n])
    
predict_ch3(net,test_iter)

注:上述内容参考b站up主“我是土堆”的视频,参考吴恩达深度学习,机器学习内容,参考李沐动手学深度学习!!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今天不想Debug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值