《动手学深度学习(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()
相关推荐
Blossom.1181 分钟前
联邦迁移学习实战:在数据孤岛中构建个性化推荐模型
开发语言·人工智能·python·深度学习·神经网络·机器学习·迁移学习
Blossom.1184 分钟前
大模型自动化压缩:基于权重共享的超网神经架构搜索实战
运维·人工智能·python·算法·chatgpt·架构·自动化
KAI智习10 分钟前
大模型榜单周报(2026/01/10)
人工智能·大模型
天天睡大觉13 分钟前
Python学习7
windows·python·学习
优选资源分享14 分钟前
MD5 哈希值校验工具 v1.5.3 实用文件校验工具
算法·哈希算法
AC赳赳老秦15 分钟前
医疗数据安全处理:DeepSeek实现敏感信息脱敏与结构化提取
大数据·服务器·数据库·人工智能·信息可视化·数据库架构·deepseek
木头程序员19 分钟前
机器学习模型成员推断攻击与防御:敏感数据保护实战指南
人工智能·机器学习
咋吃都不胖lyh19 分钟前
归因分析(Attribution Analysis)详解
大数据·人工智能
唐叔在学习20 分钟前
Pywebview进阶:基于Python直接操作前端元素
后端·python
AI科技星21 分钟前
能量绝对性与几何本源:统一场论能量方程的第一性原理推导、验证与范式革命
服务器·人工智能·科技·线性代数·算法·机器学习·生活