多层感知机从零开始实现

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);
相关推荐
好好研究6 分钟前
Java基础学习(十三):IO流基础
java·开发语言·学习·io流
知识分享小能手13 分钟前
R语言入门学习教程,从入门到精通,R语言传统绘图系统 - 完整知识点与案例代码(2)
开发语言·学习·r语言
嵌入式×边缘AI:打怪升级日志30 分钟前
从零开始学习 Linux SPI 驱动开发(基于 IMX6ULL + TLC5615 DAC)
linux·驱动开发·学习
eqwaak031 分钟前
PyTorch入门:10分钟搭建首个神经网络
开发语言·人工智能·pytorch·python
时空自由民.39 分钟前
嵌入式学习-构建系统(图形化IDE/Kconfig/手动makefile Cmake)
数据库·ide·单片机·学习
2301_7809438444 分钟前
第二阶段:Gem5基础学习
学习
我想我不够好。1 小时前
坚持到习惯为止
学习·学习方法
IRevers1 小时前
【Agent】基于Langchain的Agent数据库查询助手
数据库·人工智能·pytorch·sql·深度学习·langchain·agent
三品吉他手会点灯1 小时前
STM32F103 学习笔记-21-串口通信(第4节)—串口发送和接收代码讲解(下)
笔记·stm32·单片机·嵌入式硬件·学习
隔壁大炮1 小时前
Day02-13.张量的拼接操作
人工智能·pytorch·深度学习·神经网络·numpy