动手学深度学习(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
相关推荐
啵啵菜go15 分钟前
解决使用PPIO欧派云服务器时无法使用sftp的问题
运维·服务器·深度学习·云计算
尔呦1 小时前
Prompt-Free Diffusion: Taking “Text” out of Text-to-Image Diffusion Models
深度学习
好悬给我拽开线1 小时前
【】AI八股-神经网络相关
人工智能·深度学习·神经网络
江畔柳前堤6 小时前
CV01_相机成像原理与坐标系之间的转换
人工智能·深度学习·数码相机·机器学习·计算机视觉·lstm
qq_526099136 小时前
为什么要在成像应用中使用图像采集卡?
人工智能·数码相机·计算机视觉
码上飞扬6 小时前
深度解析:机器学习与深度学习的关系与区别
人工智能·深度学习·机器学习
super_Dev_OP7 小时前
Web3 ETF的主要功能
服务器·人工智能·信息可视化·web3
Sui_Network7 小时前
探索Sui的面向对象模型和Move编程语言
大数据·人工智能·学习·区块链·智能合约
别致的SmallSix7 小时前
集成学习(一)Bagging
人工智能·机器学习·集成学习
LNTON羚通7 小时前
视频共享融合赋能平台LnyonCVS国标视频监控平台包含哪些功能
大数据·网络·人工智能·算法·音视频