004_动手实现MLP(pytorch)

python 复制代码
import torch
from torch import nn
from torch.nn import init
import numpy as np
import sys
import d2lzh_pytorch as d2l
# 1.数据预处理
mnist_train = torchvision.datasets.FashionMNIST(
    root='/Users/w/PycharmProjects/DeepLearning_with_LiMu/datasets/FashionMnist', train=True, download=True,
    transform=transforms.ToTensor())
mnist_test = torchvision.datasets.FashionMNIST(
    root='/Users/w/PycharmProjects/DeepLearning_with_LiMu/datasets/FashionMnist', train=False, download=True,
    transform=transforms.ToTensor())
# 1.2 数据集的预处理
batch_size = 256
if sys.platform.startswith('win'):
    num_worker = 0
else:
    num_worker = 4
train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=num_worker)
test_iter  = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False, num_workers=num_worker)

# 封装自定义的结构转换函数
class FlattenLayer(nn.Module):
    def __init__(self):
        super(FlattenLayer, self).__init__()
    def forward(self, x): # x shape: (batch, *, *, ...)
        return x.view(x.shape[0], -1)
#定义网络结构
num_inputs, num_outputs, num_hiddens = 784, 10, 256
net = nn.Sequential(
    FlattenLayer(),
    nn.Linear(num_inputs,num_hiddens),
    nn.ReLU(),
    nn.Linear(num_hiddens,num_outputs)
)
for param in net.parameters():
    print(param.shape)
# 在 PyTorch 中,init.normal_ 是一个初始化方法,用于直接将张量中的元素初始化为来自正态分布(高斯分布)随机生成的值。它属于 torch.nn.init 模块,通常在神经网络的权重初始化中使用。
for params in net.parameters():
    init.normal_(params, mean=0, std=0.01)
# print 结果 torch.Size([256, 784])
#torch.Size([256])
#torch.Size([10, 256])
#torch.Size([10])

batch_size = 256
loss = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.5)
num_epochs = 5

def train(net, train_iter, test_iter, loss, num_epochs, batch_size,
              params=None, lr=None, optimizer=None):
    for epoch in range(num_epochs):
        train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
        for X, y in train_iter:
            y_hat = net(X)
            l = loss(y_hat, y).sum()

            # 梯度清零
            if optimizer is not None:
                optimizer.zero_grad()
            elif params is not None and params[0].grad is not None:
                for param in params:
                    param.grad.data.zero_()

            l.backward()
            if optimizer is None:
                sgd(params, lr, batch_size)
            else:
                optimizer.step()  # "softmax回归的简洁实现"一节将用到


            train_l_sum += l.item()
            train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
            n += y.shape[0]
        test_acc = evaluate_accuracy(test_iter, net)
        print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'
              % (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc))




train(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)
相关推荐
南山安14 小时前
手写 Cursor 核心原理:从 Node.js 进程到智能 Agent
人工智能·agent·设计
码路飞14 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
掘金安东尼14 小时前
如何为 AI 编码代理配置 Next.js 项目
人工智能
aircrushin14 小时前
轻量化大模型架构演进
人工智能·架构
文心快码BaiduComate15 小时前
百度云与光本位签署战略合作:用AI Agent 重构芯片研发流程
前端·人工智能·架构
风象南16 小时前
Claude Code这个隐藏技能,让我告别PPT焦虑
人工智能·后端
曲幽16 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
Mintopia17 小时前
OpenClaw 对软件行业产生的影响
人工智能
陈广亮17 小时前
构建具有长期记忆的 AI Agent:从设计模式到生产实践
人工智能
会写代码的柯基犬17 小时前
DeepSeek vs Kimi vs Qwen —— AI 生成俄罗斯方块代码效果横评
人工智能·llm