深度学习3.7 softmax回归的简洁实现

python 复制代码
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)

3.7.1 初始化模型参数

python 复制代码
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))

def init_weights(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, std=0.01)

net.apply(init_weights);

3.7.2 重新审视Softmax的实现

python 复制代码
loss = nn.CrossEntropyLoss(reduction='none')

3.7.3 优化算法

python 复制代码
# 在这里,我们(使用学习率为0.1的小批量随机梯度下降作为优化算法)
trainer = torch.optim.SGD(net.parameters(), lr=0.1)

3.7.4 训练

python 复制代码
num_epochs = 10
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)

3.7.5 预测

python 复制代码
batch_size = 256 #迭代器批量
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

def predict_ch3(net, test_iter, n=6):  
    """Predict labels (defined in Chapter 3)."""
    for X, y in test_iter:  # 获取第一批测试数据
        break
    trues = d2l.get_fashion_mnist_labels(y)  # 真实标签转文本
    preds = d2l.get_fashion_mnist_labels(d2l.argmax(net(X), axis=1))  # 预测标签转文本
    titles = [true +'\n' + pred for true, pred in zip(trues, preds)]  # 组合标签
    d2l.show_images(d2l.reshape(X[0:n], (n, 28, 28)), 1, n, titles=titles[0:n])  # 可视化

predict_ch3(net, test_iter)
相关推荐
桜吹雪2 小时前
手搓一个简易Agent
前端·人工智能·后端
数字时代全景窗2 小时前
从App时代到智能体时代,如何打破“三堵墙”
人工智能·软件工程
weixin_469163692 小时前
金融科技项目管理方式在AI加持下发展方向之,需求分析精准化减少业务与技术偏差
人工智能·科技·金融·项目管理·需求管理
老蒋新思维3 小时前
借陈修超之智,搭建 AI 与 IP 的创新增长桥梁|创客匠人
网络·人工智能·网络协议·tcp/ip·ip·知识付费·创客匠人
点PY3 小时前
TR3D: Towards Real-Time Indoor 3D Object Detection论文精读
人工智能·目标检测·3d
九年义务漏网鲨鱼3 小时前
【大模型面经】千问系列专题面经
人工智能·深度学习·算法·大模型·强化学习
北京耐用通信4 小时前
“耐达讯自动化Profibus总线光端机在化工变频泵控制系统中的应用与价值解析”
人工智能·科技·物联网·网络安全·自动化·信息与通信
2401_865854884 小时前
AI软件可以帮助我自动化哪些日常任务?
运维·人工智能·自动化
WWZZ20254 小时前
快速上手大模型:深度学习7(实践:卷积层)
人工智能·深度学习·算法·机器人·大模型·卷积神经网络·具身智能
简佐义的博客5 小时前
Genome Biol. IF 9.4 Q1 | ATAC-seq 数据分析实用指南,根据本文就可以构建ATAC生信分析流程了
人工智能