深度学习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)
相关推荐
用户0183493016944 分钟前
用Zustand管理AI多会话状态
人工智能
武子康3 小时前
调查研究-198 Agent 到底该记住什么?读懂《What Must Generalist Agents Remember?》
人工智能·openai·agent
aqi004 小时前
15天学会AI应用开发(九)利用Chroma持久化向量数据
人工智能·python·大模型·ai编程·ai应用
武子康5 小时前
调查研究-197 FAISS vs Elasticsearch 全面对比:从向量检索、全文搜索到 RAG 选型指南
人工智能·elasticsearch·agent
青禾网络5 小时前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
用户252736278145 小时前
【技术实战】用 Spring Boot + Vue3 + LM Studio 在本地跑通 RAG 知识库
人工智能
用户5191495848455 小时前
VBScript随机数生成器内部机制:从时间种子到密码令牌破解
人工智能·aigc
米小虾6 小时前
Context Engineering —— 知识与记忆的窗口
人工智能·agent
IT_陈寒6 小时前
Python里这个赋值坑,连老司机都能翻车
前端·人工智能·后端