动手学深度学习softmax简洁实现,调用d2l的train_ch3时显示无这个属性,经查阅要降低d2l的版本到0.17.5

但安装低版本时出现报错:jupyterlab-server 2.27.3 requires requests>=2.31, but you have requests 2.25.1 which is incompatible.

升级requests版本:pip install --upgrade requests

又出现报错:d2l 0.17.5 requires requests==2.25.1, but you have requests 2.32.3 which is incompatible.

简单的推断,首先d2l版本不能动,其次requests版本也只能是2.25.1,所以只能降低jupyterlab-server的版本了?

天杀的!包全弄乱了,最后是在torch最下面一行加了几块代码解决了。

d2l的版本还是1.0.3

jupyterlab-server 版本2.14.1

numpy 1.23.5

matplotlib 3.7.2

def train_epoch_ch3(net, train_iter, loss, updater):  #@save
    """训练模型一个迭代周期(定义见第3章)"""
    # 将模型设置为训练模式
    if isinstance(net, torch.nn.Module): # isinstance()用来判断一个对象是否是一个已知的类型
        net.train()
    # 训练损失总和、训练准确度总和、样本数
    metric = Accumulator(3)
    for X, y in train_iter:
        # 计算梯度并更新参数
        y_hat = net(X)
        l = loss(y_hat, y)
        if isinstance(updater, torch.optim.Optimizer):
            # 使用PyTorch内置的优化器和损失函数
            updater.zero_grad()
            l.mean().backward()
            updater.step()
        else:
            # 使用定制的优化器和损失函数
            l.sum().backward()
            updater(X.shape[0])
        metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())
    # 返回训练损失和训练精度
    return metric[0] / metric[2], metric[1] / metric[2]

def evaluate_accuracy(net, data_iter):  #@save
    """计算在指定数据集上模型的精度"""
    if isinstance(net, torch.nn.Module):
        net.eval()  # 将模型设置为评估模式
    metric = Accumulator(2)  # 正确预测数、预测总数
    with torch.no_grad():
        for X, y in data_iter:
            metric.add(accuracy(net(X), y), y.numel())
    return metric[0] / metric[1]

def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):  #@save
    #该训练函数将会运行多个迭代周期(由num_epochs指定)。 在每个迭代周期结束时,利用test_iter访问到的测试数据集对模型进行评估。
    #我们将利用Animator类来可视化训练进度。
    """训练模型(定义见第3章)"""
    animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],
                        legend=['train loss', 'train acc', 'test acc'])
    for epoch in range(num_epochs):
        train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
        test_acc = evaluate_accuracy(net, test_iter)
        animator.add(epoch + 1, train_metrics + (test_acc,))
    train_loss, train_acc = train_metrics
    assert train_loss < 0.5, train_loss
    assert train_acc <= 1 and train_acc > 0.7, train_acc
    assert test_acc <= 1 and test_acc > 0.7, test_acc

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐