动手学深度学习(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
相关推荐
Fuly102414 小时前
LangGraph基础教程(4)---LangGraph的核心能力
人工智能·langchain
一如年少模样丶14 小时前
AI 智能体的终极记忆方案?来认识一下 Graphiti
人工智能
机器学习之心15 小时前
NRBO-XGBoost+SHAP分析+新数据预测!机器学习可解释分析不在发愁!提供9种混沌映射方法(tent、chebyshev、singer等)
人工智能·机器学习·nrbo-xgboost
天天讯通15 小时前
医院慢病电话随访:AI 问血压→异常转医生,0 人工
人工智能
为你写首诗ge15 小时前
【python】python安装使用pytorch库环境配置
pytorch·python
张较瘦_15 小时前
[论文阅读] 生成式人工智能嵌入对公众职业安全感冲击的影响机理及防范对策
论文阅读·人工智能
这张生成的图像能检测吗15 小时前
(论文速读)Regor - 渐进式对应点再生实现鲁棒3D配准
人工智能·算法·计算机视觉·配准·3d点云
shayudiandian15 小时前
AI学习路线图2025:从入门到进阶的完整指南
人工智能
聚梦小课堂15 小时前
2025年11月10日 AI快讯
人工智能·新闻资讯·ai大事件
Danceful_YJ15 小时前
30.注意力汇聚:Nadaraya-Watson 核回归
pytorch·python·深度学习