多层感知机从零开始实现

1.加载并准备 Fashion-MNIST 数据集

复制代码
import torch
from torch import nn
from d2l import torch as d2l

batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

2.实现具有单隐藏层的多层感知机,包含256个隐藏单元

复制代码
num_inputs, num_outputs, num_hiddens = 784, 10, 256

W1 = nn.Parameter(torch.randn(
    num_inputs, num_hiddens, requires_grad=True) * 0.01)
b1 = nn.Parameter(torch.zeros(num_hiddens, requires_grad=True))
W2 = nn.Parameter(torch.randn(
    num_hiddens, num_outputs, requires_grad=True) * 0.01)
b2 = nn.Parameter(torch.zeros(num_outputs, requires_grad=True))

params = [W1, b1, W2, b2]

3.实现ReLU激活函数

复制代码
def relu(X):
    a = torch.zeros_like(X)
    return torch.max(X, a)

4.使用reshape将每个二维图像转换为长度为num_inputs的向量

复制代码
def net(X):
    X = X.reshape((-1, num_inputs))
    H = relu(X@W1 + b1)
    return (H@W2 + b2)

loss = nn.CrossEntropyLoss(reduction='none')

5.隐藏层包含256个隐藏单元,并使用了ReLU激活函数

复制代码
net = nn.Sequential(nn.Flatten(),
                    nn.Linear(784, 256),
                    nn.ReLU(),
                    nn.Linear(256, 10))

def init_weights(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, std=0.01)

net.apply(init_weights);
相关推荐
m4Rk_1 小时前
【论文阅读】Agent 记忆机制(89):PersonaAgent——构建 Memory、Persona 与 Action 的持续反馈闭环
论文阅读·人工智能·学习·开源·github
坤坤子吖1 小时前
Python基础语法学习:条件、循环与程序控制
开发语言·笔记·python·学习
胡二拉二胡1 小时前
抗遗忘单词表 App:让单词记忆不再「背了就忘」
经验分享·笔记·学习
DevNo2 小时前
我的2026中医执业医师笔试资料使用小记
笔记·学习·考研
码上上班2 小时前
jaeger学习
学习
别动我齐刘海2 小时前
简历技术栈全面复习总结
c++·人工智能·深度学习·学习·tcp/ip·算法·rpc
UIU1142 小时前
-7 / 2 在 C 里是 -3,在 Python 里是 -4,谁算错了?
c++·学习·c#
其实防守也摸鱼3 小时前
渗透测试学习计划(全栈综合 · 零基础进阶)
android·数据库·学习·安全·oracle·自动化·学习方法
一隅论数智3 小时前
给AI Agent一颗“私域大脑“:本体增强的工程化之路
大数据·运维·数据仓库·人工智能·笔记·学习·政务
我是你的开心果7783 小时前
ai全栈软件开发学习day27
人工智能·学习·状态模式