《动手学深度学习(PyTorch版)》笔记4.2 4.3

注:书中对代码的讲解并不详细,本文对很多细节做了详细注释。另外,书上的源代码是在Jupyter Notebook上运行的,较为分散,本文将代码集中起来,并加以完善,全部用vscode在python 3.9.18下测试通过。

Chapter4 Multilayer Perceptron

4.2 Implementations of Multilayer-perceptron from Scratch

复制代码
import matplotlib.pyplot as plt
from torch import nn
import torch
from d2l import torch as d2l

#我们将实现一个具有单隐藏层的多层感知机,它包含256个隐藏单元,我们可以将层数和隐藏单元数都视为超参数
#我们通常选择2的若干次幂作为层的宽度,因为内存在硬件中的分配和寻址方式,这么做往往可以在计算上更高效
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
num_inputs, num_outputs, num_hiddens = 784, 10, 256

#我们用几个张量来表示我们的参数。注意,对于每一层我们都要记录一个权重矩阵和一个偏置向量。
W1 = nn.Parameter(torch.randn(
    num_inputs, num_hiddens, requires_grad=True) * 0.01)
b1 = nn.Parameter(torch.zeros(num_hiddens, requires_grad=True))
W2 = nn.Parameter(torch.randn(
    num_hiddens, num_outputs, requires_grad=True) * 0.01)
b2 = nn.Parameter(torch.zeros(num_outputs, requires_grad=True))

params = [W1, b1, W2, b2]

#定义激活函数
def relu(X):
    a = torch.zeros_like(X)
    return torch.max(X, a)

#实现模型
def net(X):
    X = X.reshape((-1, num_inputs))
    H = relu(X@W1 + b1)  # '@'代表矩阵乘法
    return (H@W2 + b2)

#损失函数
loss = nn.CrossEntropyLoss(reduction='none')

#训练
num_epochs, lr = 10, 0.1
updater = torch.optim.SGD(params, lr=lr)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)

#评估
d2l.predict_ch3(net, test_iter)

plt.show()

4.3 Concise Implementations of Multilayer-perceptron

复制代码
import matplotlib.pyplot as plt
import torch
from d2l import torch as d2l
from torch import nn

#模型
net=nn.Sequential(nn.Flatten(),nn.Linear(784,256),nn.ReLU(),nn.Linear(256,10))
def init_weights(m):
    if type(m)==nn.Linear:
        nn.init.normal_(m.weight,std=0.01)

net.apply(init_weights)

batch_size, lr, num_epochs = 256, 0.1, 10
loss = nn.CrossEntropyLoss(reduction='none')
trainer = torch.optim.SGD(net.parameters(), lr=lr)

#训练
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)

plt.show()
相关推荐
qinyia1 分钟前
Wisdom SSH:探索AI助手在复杂运维任务中的卓越表现
运维·人工智能·ssh
TY-20252 分钟前
二、深度学习——损失函数
人工智能·深度学习
Python×CATIA工业智造3 分钟前
列表页与详情页的智能识别:多维度判定方法与工业级实现
爬虫·深度学习·pycharm
遇见你很高兴10 分钟前
Pycharm中体验通义灵码来AI辅助编程
python
京东零售技术10 分钟前
让大模型更懂你,京东零售的算法工程师做了这些事
人工智能·求职
PyAIExplorer10 分钟前
图像梯度处理与边缘检测:OpenCV 实战指南
人工智能·opencv·计算机视觉
CoovallyAIHub12 分钟前
单目深度估计重大突破:无需标签,精度超越 SOTA!西湖大学团队提出多教师蒸馏新方案
深度学习·算法·计算机视觉
biubiubiu070613 分钟前
微软云语音识别ASR示例Demo
人工智能·语音识别
大虫小呓14 分钟前
50个Python处理Excel示例代码,覆盖95%日常使用场景-全网最全
python·excel
CoovallyAIHub15 分钟前
从FCOS3D到PGD:看深度估计如何快速搭建你的3D检测项目
深度学习·算法·计算机视觉