{"record":{"id":"dc1d37bb5dc7c245","repo":"d2l-ai/d2l-zh","slug":"train-acc-1-and-train-acc-0-7-dc1d37","errorCode":null,"errorMessage":"train_acc <= 1 and train_acc > 0.7","messagePattern":"train_acc <= 1 and train_acc > 0\\.7","errorType":"validation","errorClass":"AssertionError","httpStatus":null,"severity":"error","filePath":"d2l/torch.py","lineNumber":340,"sourceCode":"        for x, y, fmt in zip(self.X, self.Y, self.fmts):\n            self.axes[0].plot(x, y, fmt)\n        self.config_axes()\n        display.display(self.fig)\n        display.clear_output(wait=True)\n\ndef train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):\n    \"\"\"训练模型（定义见第3章）\n\n    Defined in :numref:`sec_softmax_scratch`\"\"\"\n    animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],\n                        legend=['train loss', 'train acc', 'test acc'])\n    for epoch in range(num_epochs):\n        train_metrics = train_epoch_ch3(net, train_iter, loss, updater)\n        test_acc = evaluate_accuracy(net, test_iter)\n        animator.add(epoch + 1, train_metrics + (test_acc,))\n    train_loss, train_acc = train_metrics\n    assert train_loss < 0.5, train_loss\n    assert train_acc <= 1 and train_acc > 0.7, train_acc\n    assert test_acc <= 1 and test_acc > 0.7, test_acc\n\ndef predict_ch3(net, test_iter, n=6):\n    \"\"\"预测标签（定义见第3章）\n\n    Defined in :numref:`sec_softmax_scratch`\"\"\"\n    for X, y in test_iter:\n        break\n    trues = d2l.get_fashion_mnist_labels(y)\n    preds = d2l.get_fashion_mnist_labels(d2l.argmax(net(X), axis=1))\n    titles = [true +'\\n' + pred for true, pred in zip(trues, preds)]\n    d2l.show_images(\n        d2l.reshape(X[0:n], (n, 28, 28)), 1, n, titles=titles[0:n])\n\ndef evaluate_loss(net, data_iter, loss):\n    \"\"\"评估给定数据集上模型的损失\n\n    Defined in :numref:`sec_model_selection`\"\"\"","sourceCodeStart":322,"sourceCodeEnd":358,"githubUrl":"https://github.com/d2l-ai/d2l-zh/blob/e6b18ccea71451a55fcd861d7b96fddf2587b09a/d2l/torch.py#L322-L358","documentation":"Python AssertionError from d2l.torch.train_ch3's post-training sanity check: after the final epoch, training accuracy must lie in (0.7, 1]. It guards the book's promise that softmax regression on Fashion-MNIST reaches ~0.8+ train accuracy; a value outside that band means the model underfit, diverged, or the metric computation is off.","triggerScenarios":"train_acc stuck near 0.1 because the updater never updates weights (missing optimizer.step(), empty param group); accuracy computed against one-hot labels with == instead of argmax comparison; labels are float and (y_hat.argmax(axis=1) == y) broadcasting produces wrong-shaped boolean sums; lr so high the net diverges to NaN.","commonSituations":"Custom updater closures that only call zero_grad(); using MSELoss on class indices instead of CrossEntropyLoss; y left as float dtype from a numpy conversion so comparisons miscount; converting the d2l accuracy accumulator with cmp.type as in the book but on torch>=2.0 where .type semantics changed subtly.","solutions":["Use torch.optim.SGD(net.parameters(), lr=0.1) and pass trainer.step as updater","Ensure loss = nn.CrossEntropyLoss() (mean reduction) and y is a LongTensor of class indices","Smoke-test accuracy: accuracy(torch.tensor([[0.9,0.1]]), torch.tensor([0])) should be 1.0","If train_acc is NaN, lower the lr and re-initialize the net (net.apply(weight_reset) or rebuild)"],"exampleFix":"# before\nupdater = lambda batch_size: None  # forgot to step\ntrain_ch3(net, train_iter, test_iter, loss, 10, updater)  # train_acc ~0.1 -> AssertionError\n# after\ntrainer = torch.optim.SGD(net.parameters(), lr=0.1)\ntrain_ch3(net, train_iter, test_iter, loss, 10, trainer.step)  # train_acc ~0.85","handlingStrategy":"validation","validationCode":"# sanity-check the accuracy pipeline on a known case\ny_hat = torch.tensor([[0.9, 0.1], [0.2, 0.8]])\ny = torch.tensor([0, 1])\nassert d2l.accuracy(y_hat, y) == 2\nassert isinstance(y, torch.LongTensor) or y.dtype in (torch.int64, torch.long), 'labels must be long indices'","typeGuard":"def labels_valid(y: torch.Tensor, n_classes=10) -> bool:\n    return y.dtype in (torch.int64, torch.long) and y.max() < n_classes","tryCatchPattern":"try:\n    train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)\nexcept AssertionError as e:\n    v = e.args[0]\n    print('underfit (<=0.7)' if v <= 0.7 else f'implausible acc {v}')\n    raise","preventionTips":["Smoke-test d2l.accuracy with a hand-built tensor before training","Cast labels: y = y.type(torch.long) when loading custom data","Rebuild (not reuse) the net between experiments to avoid stale weights","Watch the Animator: 0.1 flat accuracy = no-op updater"],"tags":["d2l","pytorch","assertion","training","accuracy","convergence"],"backgroundTag":null,"analyzedSha":"e6b18ccea71451a55fcd861d7b96fddf2587b09a","analyzedAt":"2026-08-14T20:05:26.414Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}