深度学习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)
相关推荐
oort1239 分钟前
吃上了自家的细糠,还挺丝滑,用起来手感还行,OortCloud发布新版AI编程平台,下载 OortCodex,Token多,免费薅
大数据·开发语言·人工智能·ai编程
AI小码15 分钟前
把动作「画」给视频世界模型,跨本体双向推演,李飞飞参与
大数据·人工智能·算法·ai·大模型·音视频·编程
AI多Agent协作实战派26 分钟前
AI多Agent协作系统实战(二十三):Agent读HEARTBEAT.md不读AGENTS.md——openclaw的文件加载之谜
前端·数据库·人工智能·uni-app
爱研究的小梁41 分钟前
乾元通聚合路由及管理平台支持全面适配信创
网络·人工智能·信息与通信
水如烟1 小时前
孤能子视角:智能系统的持续学习——从关系场存续到模块化生长
人工智能
做一个码农都是奢望1 小时前
0722 LLM及其科研进展
人工智能
饼饼学习空间智能1 小时前
2026数字孪生国产化进入“交付验证期”:五类头部企业能力与项目选型分析
人工智能
海兰1 小时前
【高速缓存】RedisVL为文本生成嵌入向量实践指南
人工智能·python·机器学习
user-猴子2 小时前
让网页“活”过来 —— 用AI打造会自主学习的动态知识图谱
人工智能·学习·知识图谱
苦瓜小生2 小时前
AI名词大扫盲!最全的面试ai名词集合
人工智能·面试