多层感知机从零开始实现

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);
相关推荐
sp_fyf_202413 分钟前
【大语言模型】从失败中学习:在微调大型语言模型作为智能体时整合负例
人工智能·深度学习·学习·机器学习·语言模型·自然语言处理
秋雨梧桐叶落莳30 分钟前
【iOS】 AutoLayout初步学习
学习·macos·ios·objective-c·cocoa·xcode
独隅31 分钟前
PyTorch 文本生成完整代码模板与深度解析
人工智能·pytorch·python
for_ever_love__40 分钟前
Objective-C学习UI 的初步了解(2)
学习·ui·objective-c
m0_716765231 小时前
数据结构--顺序表的插入、删除、查找详解
c语言·开发语言·数据结构·c++·学习·算法·visual studio
独隅1 小时前
PyTorch 图像分类完整代码模板与深度解析
人工智能·pytorch·分类
我要成为嵌入式大佬1 小时前
学习linux的部分疑惑与解答(非专业)
学习
Дерек的学习记录1 小时前
Unreal Eangie 5:蓝图编程
开发语言·学习·ue5
AI科技星1 小时前
基于v≡c第一性原理:密度的本质与时空动力学
人工智能·学习·算法·机器学习·数据挖掘
Orange_sparkle1 小时前
learn claude code学习记录-S01
学习·claude code