动手学深度学习(Pytorch版)代码实践 -深度学习基础-07多层感知机基础版

07多层感知机基础版

python 复制代码
import torch
from torch import nn
from d2l import torch as d2l
import liliPytorch as lp

batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

#实现一个具有单隐藏层的多层感知机
#输入层的神经元数量784,输出层的神经元数量10, 隐藏层的神经元数量256
num_inputs, num_outputs, num_hiddens = 784, 10, 256

#第一层
"""
torch.randn初始化权重使用的是正态分布,可以有效打破对称性,
让每个神经元学习不同的特征,从而提高网络的表达能力和训练效果。
而使用全零或全一初始化会导致对称性问题,使得网络无法有效训练
"""

W1 = nn.Parameter(#权重矩阵,形状为(784, 256),使用正态分布随机初始化
    torch.randn(num_inputs, num_hiddens, requires_grad=True) * 0.01
)
b1 = nn.Parameter(#偏置向量,初始化为全零,形状为(256)
    torch.zeros(num_hiddens,requires_grad=True) * 0.01
)

#第二层
W2 = nn.Parameter(#权重矩阵,形状为(256, 10),使用正态分布随机初始化
    torch.randn(num_hiddens, num_outputs,requires_grad=True) * 0.01
)
b2 = nn.Parameter(#偏置向量,初始化为全零,形状为(10)
    torch.zeros(num_outputs, requires_grad=True) * 0.01
)

#包含所有网络参数的列表
params = [W1, b1, W2, b2]

#实现RelU激活函数
def relu(X):
    a = torch.zeros_like(X)
    return torch.max(X,a)

#实现我们的模型
def net(X):
    #-1 表示自动推断批量大小。
    #X.reshape((-1, num_inputs)) 将输入 X 重塑为形状 (batch_size, num_inputs)
    X = X.reshape((-1, num_inputs))
    # @运算符进行矩阵乘法
    H = relu(X @ W1 + b1) # 隐藏层
    return (H @ W2 + b2)  # 输出层

loss = nn.CrossEntropyLoss(reduction='none')

num_epochs = 10
updater = torch.optim.SGD(params, lr = 0.1)

#训练
lp.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)

#验证
lp.predict_ch3(net, test_iter)
d2l.plt.show() 

运行结果:

python 复制代码
<Figure size 350x250 with 1 Axes>
epoch: 1,train_loss: 1.049810703786214,train_acc: 0.6473166666666667,test_acc: 0.7147
<Figure size 350x250 with 1 Axes>
epoch: 2,train_loss: 0.5967115777969361,train_acc: 0.7906333333333333,test_acc: 0.8078
<Figure size 350x250 with 1 Axes>
epoch: 3,train_loss: 0.5182829195022584,train_acc: 0.8189833333333333,test_acc: 0.8115
<Figure size 350x250 with 1 Axes>
epoch: 4,train_loss: 0.48012483253479005,train_acc: 0.8311833333333334,test_acc: 0.8145
<Figure size 350x250 with 1 Axes>
epoch: 5,train_loss: 0.45687386004130043,train_acc: 0.8388166666666667,test_acc: 0.8265
相关推荐
jieshenai1 分钟前
BERT_Experiment_Template 多种模型与数据集加载,训练、参数保存与评估,适合论文实验的代码模板项目
人工智能·深度学习·bert
蝎蟹居13 分钟前
GBT 4706.1-2024逐句解读系列(25) 第7.5条款:不同电压功率需清晰明确
人工智能·单片机·嵌入式硬件·物联网·安全
Mintopia14 分钟前
😎 HTTP/2 中的 HPACK 压缩原理全揭秘
前端·人工智能·aigc
阿里云大数据AI技术20 分钟前
EMR AI 助手再升级:支持 Serverless StarRocks
人工智能
bing.shao21 分钟前
golang 做AI任务链的优势和场景
开发语言·人工智能·golang
知乎的哥廷根数学学派22 分钟前
基于多物理约束融合与故障特征频率建模的滚动轴承智能退化趋势分析(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习
deephub37 分钟前
Agentic Memory 实践:用 agents.md 实现 LLM 持续学习
人工智能·大语言模型·agent
chen_jared43 分钟前
反对称矩阵的性质和几何意义
人工智能·算法·机器学习
NocoBase1 小时前
NocoBase 本周更新汇总:支持 Gemini-3 模型
人工智能·开源·零代码·无代码·版本更新
汇智信科1 小时前
智慧矿山和工业大数据解决方案“安全生产数据综合分析系统
大数据·人工智能·安全·智能算法·智慧矿山·工业大数据·汇智信科