深度学习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)
相关推荐
kevin 12 分钟前
财务审核场景全覆盖,AI智能审核,自然语言配置规则
人工智能
jieshenai4 分钟前
BERT_Experiment_Template 多种模型与数据集加载,训练、参数保存与评估,适合论文实验的代码模板项目
人工智能·深度学习·bert
蝎蟹居16 分钟前
GBT 4706.1-2024逐句解读系列(25) 第7.5条款:不同电压功率需清晰明确
人工智能·单片机·嵌入式硬件·物联网·安全
Mintopia17 分钟前
😎 HTTP/2 中的 HPACK 压缩原理全揭秘
前端·人工智能·aigc
阿里云大数据AI技术23 分钟前
EMR AI 助手再升级:支持 Serverless StarRocks
人工智能
bing.shao24 分钟前
golang 做AI任务链的优势和场景
开发语言·人工智能·golang
知乎的哥廷根数学学派25 分钟前
基于多物理约束融合与故障特征频率建模的滚动轴承智能退化趋势分析(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习
deephub40 分钟前
Agentic Memory 实践:用 agents.md 实现 LLM 持续学习
人工智能·大语言模型·agent
chen_jared1 小时前
反对称矩阵的性质和几何意义
人工智能·算法·机器学习
NocoBase1 小时前
NocoBase 本周更新汇总:支持 Gemini-3 模型
人工智能·开源·零代码·无代码·版本更新