多层感知机从零开始实现

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);
相关推荐
集3046 小时前
C++多线程学习笔记
c++·笔记·学习
知南x6 小时前
【正点原子STM32MP157 可信任固件TF-A学习篇】(2) STM32MP1 中的 TF-A
stm32·嵌入式硬件·学习·stm32mp157
YJlio6 小时前
Active Directory 工具学习笔记(10.0):AdExplorer / AdInsight / AdRestore 导读与场景地图
网络·笔记·学习
子夜江寒7 小时前
Python 学习-Day8-执行其他应用程序
python·学习
●VON7 小时前
从单机应用到分布式调度:基于 HarmonyOS 构建车-空协同任务引擎
学习·华为·harmonyos·openharmony·开源鸿蒙
万变不离其宗_88 小时前
http学习笔记
笔记·学习
盐焗西兰花8 小时前
鸿蒙学习实战之路 - 避免冗余刷新最佳实践
学习·华为·harmonyos
Lynnxiaowen8 小时前
今天我们继续学习Kubernetes内容pod资源对象
运维·学习·容器·kubernetes·云计算
xier_ran8 小时前
关键词解释:对比学习(Contrastive Learning)
人工智能·深度学习·学习·机器学习·对比学习
andwhataboutit?8 小时前
GAN学习
深度学习·学习·生成对抗网络