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)
相关推荐
cxr8282 分钟前
deepseek harness能否指挥Claude code和codex来协同开发
人工智能·智能体
数据智研3 分钟前
【数据分享】中国农产品价格调查年鉴(2004-2025)
大数据·人工智能·数据分析·可视化·数据可视化
阿图灵4 分钟前
OpenCV 图像操作六件套:读取、裁剪、缩放、旋转、通道分割与保存
图像处理·人工智能·python·深度学习·opencv·计算机视觉
小小帅呀6 分钟前
学习 VLA 第 1 天:VLA 概述与学习路线
人工智能
TechEdu2026068 分钟前
[人工智能]Claude(Anthropic):模型能力、智能体与安全工程实践
人工智能·ai
pjj198549 分钟前
opencv-图像透视转换
人工智能·opencv·计算机视觉
aneasystone本尊9 分钟前
学习大模型推理的分词:从文本到 Token
人工智能
浪兎兎10 分钟前
【深度学习】(四)案例:基于PyTorch的全连接神经网络实现手机价格区间预测
pytorch·深度学习·神经网络
桐桐桐13 分钟前
Python 实战:批量生成带来源参数的 WhatsApp 短链 + 二维码
服务器·数据库·python·前端框架·ip·跨境电商·独立站
牧羊人.33313 分钟前
计算机视觉基础 第 11 章| 特征检测与特征匹配
图像处理·人工智能·opencv·计算机视觉