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)
相关推荐
云天AI实战派4 分钟前
AI 智能体全流程实战:从 0 搭一个门店运营助手,用 API + 工具搜索 + 编码代理做出可复现闭环
人工智能·ai·智能体
大连好光景4 分钟前
BCELoss + sigmoid 换成 BCEWithLogitsLoss
人工智能·深度学习·机器学习
OpenApi.cc27 分钟前
神经网络结构驱动+数据结构分析
数据结构·人工智能·神经网络
向量引擎27 分钟前
告别多源向量API适配噩梦:一套通用中转层的设计与实践
人工智能·gpt·aigc·agi·api调用
太阳上的雨天30 分钟前
任何格式的文件转Markdown
python·ai
my烂笔头39 分钟前
单阶段 双阶段 目标检测的区别
人工智能·ai
yaoxin52112342 分钟前
419. 现代 Java IO 最佳实践 - 写入文本文件
java·windows·python
程序员Aries1 小时前
LangChain 与大语言模型
人工智能·语言模型·langchain
向量引擎1 小时前
向量引擎API中转站深度测评:如何实现低成本、高并发的向量检索
人工智能·gpt·aigc·api·ai编程
morning_judger1 小时前
Agent系列(一) - Agent系统分层架构
人工智能·架构