动手学深度学习(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
相关推荐
双向332 分钟前
实战测试:多模态AI在文档解析、图表分析中的准确率对比
人工智能
用户5191495848454 分钟前
1989年的模糊测试技术如何在2018年仍发现Linux漏洞
人工智能·aigc
人类发明了工具5 分钟前
【深度学习-基础知识】单机多卡和多机多卡训练
人工智能·深度学习
用户51914958484515 分钟前
检索增强生成(RAG)入门指南:构建知识库与LLM协同系统
人工智能·aigc
CoovallyAIHub16 分钟前
方案 | 动车底部零部件检测实时流水线检测算法改进
深度学习·算法·计算机视觉
CoovallyAIHub18 分钟前
方案 | 光伏清洁机器人系统详细技术实施方案
深度学习·算法·计算机视觉
星期天要睡觉20 分钟前
机器学习——CountVectorizer将文本集合转换为 基于词频的特征矩阵
人工智能·机器学习·矩阵
lxmyzzs22 分钟前
【图像算法 - 14】精准识别路面墙体裂缝:基于YOLO12与OpenCV的实例分割智能检测实战(附完整代码)
人工智能·opencv·算法·计算机视觉·裂缝检测·yolo12
什么都想学的阿超31 分钟前
【大语言模型 01】注意力机制数学推导:从零实现Self-Attention
人工智能·语言模型·自然语言处理