动手学深度学习(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
相关推荐
浊酒南街3 分钟前
吴恩达深度学习笔记:卷积神经网络(Foundations of Convolutional Neural Networks)2.7-2.8
人工智能·深度学习·神经网络
DuoRuaiMiFa37 分钟前
ChatGPT全新功能Canvas上线:开启智能编程与写作新篇章
人工智能·chatgpt
DisonTangor40 分钟前
Windows 11将新增基于AI的搜索、生成式填充和其它AI功能
人工智能
soso196842 分钟前
【AI自然语言处理应用】通过API调用通义晓蜜CCAI-对话分析AIO应用
人工智能·自然语言·ccai
网安-搬运工1 小时前
RAG再总结之如何使大模型更好使用外部数据:四个不同层级及查询-文档对齐策略
人工智能·自然语言处理·大模型·llm·大语言模型·ai大模型·rag
大模型八哥1 小时前
大模型扫盲系列——大模型实用技术介绍(上)
人工智能·程序人生·ai·大模型·llm·llama·ai大模型
被制作时长两年半的个人练习生1 小时前
【pytorch】权重为0的情况
人工智能·pytorch·深度学习
Elastic 中国社区官方博客1 小时前
使用 Vertex AI Gemini 模型和 Elasticsearch Playground 快速创建 RAG 应用程序
大数据·人工智能·elasticsearch·搜索引擎·全文检索
说私域2 小时前
地理定位营销与开源AI智能名片O2O商城小程序的融合与发展
人工智能·小程序