李沐深度学习-多层感知机从零开始

!!!梯度的产生是由于反向传播,在自定义从零开始编写代码时,第一次反向传播前应该对params参数的梯度进行判断

import torch
import numpy as np
import torch.utils.data as Data
import torchvision.datasets
import torchvision.transforms as transforms
import sys

sys.path.append("路径")
import d2lzh_pytorch as d2l

'''
--------------------------------------------------获取和读取数据
'''
batch_size = 256
train_mnist = torchvision.datasets.FashionMNIST(root='路径',
                                                download=True, train=True, transform=transforms.ToTensor())
test_mnist = torchvision.datasets.FashionMNIST(root='路径',
                                               download=True, train=False, transform=transforms.ToTensor())
train_iter = Data.DataLoader(train_mnist, batch_size=batch_size, shuffle=True)
test_iter = Data.DataLoader(test_mnist, batch_size=batch_size, shuffle=False)

'''
--------------------------------------------------定义模型参数
'''
num_inputs = 784
num_outputs = 10
num_hidden = 256
# 有几个隐藏层就要设置几个参数,简洁实现中,linear网络会自动配置初始参数,自己可以使用init.normal_()设置参数初始值
w1 = torch.tensor(np.random.normal(0, 0.01, (num_inputs, num_hidden)), dtype=torch.float)
b1 = torch.zeros(num_hidden, dtype=torch.float)
w2 = torch.tensor(np.random.normal(0, 0.1, (num_hidden, num_outputs)), dtype=torch.float)
b2 = torch.zeros(num_outputs, dtype=torch.float)
params = [w1, b1, w2, b2]
for param in params:
    param.requires_grad_(requires_grad=True)
'''
---------------------------------------------定义激活函数
'''


def relu(X):
    return torch.max(input=X, other=torch.tensor(0.0))


'''
---------------------------------------------------定义模型
'''


# 使用view函数将输入的样本转换成inputs特征数大小的图像
def net(X):
    X = X.view((-1, num_inputs))
    H = relu(torch.matmul(X, w1) + b1)  # torch.mm(X, w1) + b1得到隐藏层输出
    # 对隐藏层变量进行激活函数变换,然后作为下一个全连接层的输入
    # 第一层不是隐藏层,直接线性计算,隐藏层输出作为输出层输入的时候,对隐藏层进行非线性变换,然后传入输入层
    return torch.matmul(H, w2) + b2  # 隐藏层作为输出层的输入   n层layer有最多n-2个激活函数


'''
-----------------------------------------------------定义损失函数
'''
loss = torch.nn.CrossEntropyLoss()  # 包含了softmax运算和交叉熵运算

'''
------------------------------------------------------softmax操作,用于训练模型中训练集准确率调用
'''


def softmax(X):
    X_exp = X.exp()  # 幂指数化
    partition = X_exp.sum(dim=1, keepdim=True)  # 求和每行的元素值
    return X_exp / partition  # 做比值得预测概率


'''
----------------------------------------------------测试集准确率函数,训练模型中测试集准确率调用
'''


def evaluate_accuracy(test_data):
    acc_num, num = 0.0, 0
    for X, y in test_data:  # X,y分别是一个元组
        acc_num += (softmax(net(X)).argmax(dim=1) == y).float().sum().item()
        num += y.shape[0]
    return acc_num / num


'''
------------------------------------------------------训练模型
'''
num_epochs, lr = 5, 100


def train():
    for epoch in range(num_epochs):
        train_acc, train_l, test_acc, n, num = 0.0, 0.0, 0.0, 0, 0
        for X, y in train_iter:  #
            l = loss(net(X), y)  # CrossEntropyLoss 函数已经是对一个批次内所有样本的平均损失计算了
            if params[0].grad is not None:  # 第一次训练迭代前是没有梯度产生的,梯度是由于反向传播才产生的
                for param in params:  # 参数梯度清零
                    param.grad.data.zero_()
            l.backward()  # 反向传播
            d2l.sgd(params, lr, batch_size)  # 梯度下降操作
            train_l += l.item()
            # net(X)返回每个样本各个类别的预测值,有n个样本返回
            train_acc += (softmax(net(X)).argmax(dim=1) == y).float().sum().item()  # 累加预测正确个数
            n += y.shape[0]
            num += 1
        test_acc = evaluate_accuracy(test_iter)
        print(f'epoch %d, loss %.4f, train_acc %.3f, test_acc %.3f'
              % (epoch + 1, train_l / num, train_acc / n, test_acc))


train()

你可能感兴趣的:(李沐深度学习编码实现,深度学习,人工智能)