多层感知机从零开始实现

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);
相关推荐
~光~~1 小时前
【嵌入式linux学习】Cache 策略:Write-Through / Write-Back + Allocation
linux·学习·spring
星恒随风2 小时前
Linux基础IO万字详解:从文件描述符fd到重定向、FILE缓冲机制及MiniShell升级
linux·运维·笔记·学习·状态模式
小雪崩3 小时前
嵌入式学习 day65:Linux驱动进阶——pinctrl 子系统和 platform 驱动框架
linux·学习·驱动
shixiexunnie3 小时前
Raw NAND 驱动库学习
驱动开发·学习
喜欢打篮球的普通人3 小时前
MiniMind 学习笔记(二十二):数学 Cookbook——把概率空间、期望、似然一次讲明白
人工智能·笔记·学习
程序猿阿森3 小时前
混合精度详解:FP16 vs BF16,Loss Scaling 与 PyTorch 实战
人工智能·pytorch·python
JWASX4 小时前
【agent 开发】agent 开发学习 - LangChain(3)
学习·langchain
dadaobusi4 小时前
一个有趣的物理假设
学习
JWASX5 小时前
【agent 开发】agent 开发学习 - LangChain(2)
python·学习·langchain
li星野5 小时前
【学习记录】立创EDA专业版核心概念全解析:数据整理、设计验证与器件四层模型
学习