深度学习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)
相关推荐
一车小面包6 小时前
基于bert-base-chinese的外卖评论情绪分类项目
人工智能·机器学习
wu_jing_sheng06 小时前
ai 作物分类
人工智能·分类·数据挖掘
董建光d6 小时前
PyTorch 实现多种 CNN 模型并采用集成方法提升 CIFAR-10 分类性能
人工智能·pytorch·cnn
摘星编程6 小时前
从0到1:打造专业级AI教学助手的完整开发实录
人工智能
文真同学6 小时前
《动手学深度学习》5.3~5.5
人工智能·深度学习
科研服务器mike_leeso7 小时前
41 年 7 次转型!戴尔从 PC 到 AI 工厂的技术跃迁与组织重构
大数据·人工智能·机器学习
lisw057 小时前
如何改善基于深度学习的场重构
深度学习·重构·软件工程
大千AI助手7 小时前
机器学习模型评估指标AUC详解:从理论到实践
人工智能·机器学习·模型评估·roc·precision·recall·auc
2501_913981787 小时前
2025年智能家居无线数传设备品牌方案精选
大数据·人工智能·智能家居
不老刘7 小时前
GitHub Spec-Kit:AI 时代的规范驱动开发工具
人工智能·github·spec-kit