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

08多层感知机简洁版

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

net = nn.Sequential(
    nn.Flatten(),
    nn.Linear(784,256),
    nn.ReLU(),
    nn.Linear(256,10)  
)

#函数接受一个参数 m,通常是一个神经网络模块(例如,线性层,卷积层等)
def init_weights(m):
#这行代码检查传入的模块 m 是否是 nn.Linear 类型,即线性层(全连接层)
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight,std=0.01)
#m.weight 是线性层的权重矩阵。
#std=0.01 指定了初始化权重的标准差为 0.01,表示权重将从均值为0,标准差为0.01的正态分布中随机采样。

#model.apply(init_weights) 会遍历模型的所有模块,并对每个模块调用 init_weights 函数。
#如果模块是 nn.Linear 类型,则初始化它的权重。
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)

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

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

运行结果:

python 复制代码
<Figure size 350x250 with 1 Axes>
epoch: 1,train_loss: 1.0443685918807983,train_acc: 0.64345,test_acc: 0.7608
<Figure size 350x250 with 1 Axes>
epoch: 2,train_loss: 0.5980708345413208,train_acc: 0.7904166666666667,test_acc: 0.7707
<Figure size 350x250 with 1 Axes>
epoch: 3,train_loss: 0.5194601311365763,train_acc: 0.8209166666666666,test_acc: 0.8143
<Figure size 350x250 with 1 Axes>
epoch: 4,train_loss: 0.4801325536727905,train_acc: 0.8319666666666666,test_acc: 0.827
<Figure size 350x250 with 1 Axes>
epoch: 5,train_loss: 0.4518238489786784,train_acc: 0.8414833333333334,test_acc: 0.8358
相关推荐
SailingCoder2 分钟前
AI 流式对话该怎么做?SSE、fetch、axios 一次讲清楚
前端·javascript·人工智能·ai·node.js
腾视科技4 分钟前
超低功耗 性能卓越|腾视科技重磅推出TS-SG-SM9系列AI算力模组,引领边缘智能计算新篇章
人工智能·科技
视界先声4 分钟前
洁诚新能源:践行双碳战略的绿色行动派
大数据·人工智能·物联网
gorgeous(๑>؂<๑)5 分钟前
【南京大学-李文斌-arXiv25】超高分辨率遥感多模态大语言模型基准测试
人工智能·语言模型·自然语言处理
低调小一5 分钟前
Google A2UI 协议深度解析:AI 生成 UI 的机遇与实践(客户端视角,Android/iOS 都能落地)
android·人工智能·ui
AI白艿6 分钟前
男装市场稳健增长?AI助力精准把握消费新趋势
人工智能·aigc
5G全域通6 分钟前
工信部2026年短信业务合规申请全流程官方指南(1月1日强制生效)
大数据·网络·人工智能·信息与通信·时序数据库
木卫四科技6 分钟前
【CES 2026】木卫四科技携“合规全生命周期”汽车网络安全方案亮相 CES 2026
人工智能·木卫四科技·ces2026·智能汽车安全
爱思德学术8 分钟前
中国计算机学会(CCF)推荐学术会议-B(交叉/综合/新兴):CogSci 2026
人工智能·神经网络·认知科学
好奇龙猫9 分钟前
【人工智能学习-AI-MIT公开课第 16 讲:支持向量机(SVM)】
人工智能·学习·支持向量机