深度学习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)
相关推荐
Mark-Wang2 分钟前
每天介绍一家新质生产力公司4
人工智能
AI视觉网奇14 分钟前
智能办公 大模型总结
人工智能
AIGC大时代40 分钟前
有些内容AI写得再顺都不一定稳,这8个地方导师一问就露馅
人工智能·codex·ai工具·aiwritepaper·ai学术写作
CODER03041 小时前
Anaconda和Mamba创建环境管理包常用命令合集
python·深度学习·conda·虚拟环境·mamba·常用命令大全
skywalk81631 小时前
我现在手里有comate、dumate、 workbuddy和trae四个agent,你看这四个任务怎么分合适?
人工智能·deepseek
用户0617708544951 小时前
Agent 办事失败兜底技术实现方案:从失败模型到生产级容错体系
人工智能
是大乔家的1 小时前
网文分销商必备神器:用知漫剧快速将授权小说转化为连载视频引流
人工智能
ITmaster07311 小时前
面试官坏笑:“你用 AI 编程一年了,怎么保证 Claude Code 写出来的代码是对的?”我:“直接上 Claude Fable 5 啊!”
人工智能
英雄6271 小时前
给 DeepSeek Harness Web 写了一个美化插件
人工智能
dogstarhuang1 小时前
OpenAI GPT-5.6 降价后如何重算 API 账单?多模型路由与成本治理实战
服务器·网络·人工智能·大模型·api·ai应用开发·接口管理