{"record":{"id":"db4d03ded1f23746","repo":"d2l-ai/d2l-zh","slug":"train-acc-1-and-train-acc-0-7-db4d03","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/paddle.py","lineNumber":351,"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":333,"sourceCodeEnd":369,"githubUrl":"https://github.com/d2l-ai/d2l-zh/blob/e6b18ccea71451a55fcd861d7b96fddf2587b09a/d2l/paddle.py#L333-L369","documentation":"An AssertionError in d2l.paddle.train_ch3 requiring final training accuracy in (0.7, 1]. It is a post-training sanity check for the PaddlePaddle softmax-regression benchmark on Fashion-MNIST; accuracy <= 0.7 signals undertraining or divergence, while > 1 signals a broken metric computation.","triggerScenarios":"Undertrained model (1-2 epochs instead of 10); wrong gradient scaling in a custom updater producing near-chance accuracy; train_epoch_ch3 accuracy accumulator dividing by the wrong count (giving acc > 1); shuffled label pipeline making learning impossible.","commonSituations":"Cutting num_epochs short when iterating quickly; adapting train_epoch_ch3 to new metrics and breaking the Accumulator bookkeeping; Paddle dtype/device mismatches silently zeroing gradients.","solutions":["Train the full 10 epochs with lr=0.1, batch_size=256.","Audit train_epoch_ch3's metric.Accumulator(3): add correct-count and count per batch and divide metric[1] by metric[2] exactly once.","Verify optimizer.step() / linear.clear_gradients() (or paddle.optimizer SGD minimization) run every batch so weights actually update.","If acc hovers near 0.1, debug data loading (labels aligned with images) before touching hyperparameters."],"exampleFix":"# before\ntrain_ch3(net, train_iter, test_iter, loss, 1, updater)  # acc <= 0.7\n# after\ntrain_ch3(net, train_iter, test_iter, loss, 10, updater)","handlingStrategy":"validation","validationCode":"train_loss, train_acc = train_epoch_ch3(net, train_iter, loss, updater)\nif not (0.7 < train_acc <= 1.0):\n    raise ValueError(f'train_acc={train_acc:.3f} outside (0.7, 1]; '\n                     f'check optimizer.step()/clear_gradients and metric Accumulator')","typeGuard":null,"tryCatchPattern":"try:\n    train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)\nexcept AssertionError as e:\n    raise RuntimeError(f'Paddle train_ch3 accuracy check failed ({e}); '\n                       f'likely undertrained or metrics mis-accumulated') from e","preventionTips":["Ensure optimizer.step() and gradient clearing run every batch.","Keep the Accumulator pattern: add(correct_count, count) and divide once at the end.","Train the full 10 epochs; near-chance accuracy (~0.1) means updates are not applied."],"tags":["d2l","paddle","training","accuracy","assertion"],"backgroundTag":null,"analyzedSha":"e6b18ccea71451a55fcd861d7b96fddf2587b09a","analyzedAt":"2026-08-14T20:05:26.414Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}