动手学深度学习(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
相关推荐
a1111111111ss2 分钟前
添加最新的LSKNet遥感目标检测网络主干
人工智能·目标检测·计算机视觉
relis15 分钟前
llama.cpp Flash Attention 论文与实现深度对比分析
人工智能·深度学习
盼小辉丶19 分钟前
Transformer实战(21)——文本表示(Text Representation)
人工智能·深度学习·自然语言处理·transformer
艾醒(AiXing-w)23 分钟前
大模型面试题剖析:模型微调中冷启动与热启动的概念、阶段与实例解析
人工智能·深度学习·算法·语言模型·自然语言处理
科技小E27 分钟前
流媒体视频技术在明厨亮灶场景中的深度应用
人工智能
geneculture36 分钟前
融智学院十大学部知识架构示范样板
人工智能·数据挖掘·信息科学·哲学与科学统一性·信息融智学
无风听海37 分钟前
神经网络之交叉熵与 Softmax 的梯度计算
人工智能·深度学习·神经网络
算家计算38 分钟前
AI树洞现象:是社交降级,还是我们都在失去温度?
人工智能
java1234_小锋40 分钟前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 神经网络基础原理
python·深度学习·tensorflow·tensorflow2
JJJJ_iii42 分钟前
【深度学习03】神经网络基本骨架、卷积、池化、非线性激活、线性层、搭建网络
网络·人工智能·pytorch·笔记·python·深度学习·神经网络