多层感知机从零开始实现

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);
相关推荐
好望角雾眠3 小时前
第一阶段C#基础-10:集合(Arraylist,list,Dictionary等)
笔记·学习·c#
艾伦~耶格尔3 小时前
【集合框架LinkedList底层添加元素机制】
java·开发语言·学习·面试
星仔编程3 小时前
python学习DAY46打卡
学习
大霞上仙4 小时前
实现自学习系统,输入excel文件,能学习后进行相应回答
python·学习·excel
Caven774 小时前
【pytorch】reshape的使用
pytorch·python
无规则ai4 小时前
动手学深度学习(pytorch版):第四章节—多层感知机(5)权重衰减
人工智能·pytorch·python·深度学习
yatingliu20195 小时前
HiveQL | 个人学习笔记
hive·笔记·sql·学习
武当豆豆5 小时前
C++编程学习(第25天)
开发语言·c++·学习
风和日丽 随波逐流5 小时前
java17学习笔记-Deprecate the Applet API for Removal
笔记·学习
淮北也生橘126 小时前
Linux的ALSA音频框架学习笔记
linux·笔记·学习