动手学深度学习(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
相关推荐
朱大喜14 小时前
数据可视化工具选型:matplotlib、Plotly 与 ECharts
人工智能
动物园猫14 小时前
直升机停机坪目标检测数据集分享(适用于YOLO系列深度学习分类检测任务)
深度学习·yolo·目标检测
染指111020 小时前
26.RAG进阶(Advanced RAG)-假设性问题索引
人工智能·windows·agent·rag·advanced rag
闵孚龙20 小时前
动态图机制:为什么 PyTorch 调试起来更舒服
人工智能·pytorch·python
甲维斯21 小时前
还要啥Codex!DeepSeek接入Zcode远程连接!
人工智能
Kobebryant-Manba21 小时前
RNN从0实现
pytorch·rnn·深度学习
百胜软件@百胜软件21 小时前
百胜软件亮相“AI消费新生活”主题日活动,AI智能运营平台入选市级案例征集
人工智能·生活·零售数字化·数智中台·珠宝行业
专注搞钱1 天前
GPT-4o写设备Recipe:从3小时到10分钟
数据库·人工智能·gpt·半导体
闻道参看1 天前
贝芯宠AI灵兽 ELFVET 大模型聚焦临床应用,强化宠物诊疗综合能力
人工智能·宠物
MartinYeung51 天前
[论文学习]重新思考大型语言模型忘却目标:梯度视角与超越
人工智能·学习·语言模型