{"record":{"id":"53ba4edc3be185f3","repo":"d2l-ai/d2l-zh","slug":"train-acc-1-and-train-acc-0-7-53ba4e","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/tensorflow.py","lineNumber":320,"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\nclass Updater():\n    \"\"\"用小批量随机梯度下降法更新参数\n\n    Defined in :numref:`sec_softmax_scratch`\"\"\"\n    def __init__(self, params, lr):\n        self.params = params\n        self.lr = lr\n\n    def __call__(self, batch_size, grads):\n        d2l.sgd(self.params, grads, self.lr, batch_size)\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:","sourceCodeStart":302,"sourceCodeEnd":338,"githubUrl":"https://github.com/d2l-ai/d2l-zh/blob/e6b18ccea71451a55fcd861d7b96fddf2587b09a/d2l/tensorflow.py#L302-L338","documentation":"An AssertionError in d2l.tensorflow.train_ch3 requiring final training accuracy to lie in (0.7, 1]. It is a post-training sanity check that the softmax-regression model actually learned Fashion-MNIST to a reasonable degree. Values <= 0.7 mean the model undertrained or diverged; values > 1 mean the metric computation itself is broken.","triggerScenarios":"Same divergence/undertraining causes as the loss assert: too-high lr, wrong updater scaling, too few epochs, untrained net; additionally a custom train_epoch_ch3 whose accuracy accumulation divides by the wrong denominator can push train_acc above 1 and trip the upper bound.","commonSituations":"Notebook users changing num_epochs from 10 to 1-2; using a custom metric accumulator with a mismatched count; training on a heavily subsampled train_iter; TF2 gradient-tape code that forgets to apply updates.","solutions":["Restore the book's hyperparameters (lr=0.1, batch_size=256, num_epochs=10) and rerun.","Check train_epoch_ch3's accuracy accumulator: metric.add(y == argmax(y_hat), y.numel()) style bookkeeping must sum counts and divide by totals exactly once.","Confirm updater.apply_gradients is actually called each batch; a broken update loop yields ~0.1 accuracy (chance level).","Read the Animator curves: if accuracy is still climbing at the final epoch, increase num_epochs."],"exampleFix":"# before\ntrain_ch3(net, train_iter, test_iter, loss, 1, updater)  # undertrained -> acc <= 0.7\n# after\ntrain_ch3(net, train_iter, test_iter, loss, 10, updater)","handlingStrategy":"validation","validationCode":"final_loss, final_acc = train_epoch_ch3(net, train_iter, loss, updater)\nif not (0.7 < final_acc <= 1.0):\n    raise ValueError(f'train_acc out of expected (0.7, 1]: {final_acc:.3f}; '\n                     f'check metric accumulator and optimizer wiring')","typeGuard":null,"tryCatchPattern":"try:\n    train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)\nexcept AssertionError as e:\n    raise RuntimeError(f'train_ch3 accuracy check failed ({e}); '\n                       f'likely undertrained or broken updater') from e","preventionTips":["Train the full 10 epochs before judging accuracy.","Unit-check your metric Accumulator bookkeeping on one hand-made batch where the answer is known.","Confirm updater.apply_gradients (TF) actually runs each step; a no-op updater pins accuracy near 0.1.","Keep accuracy computation as correct_count / total_examples, computed once."],"tags":["d2l","tensorflow","training","accuracy","assertion"],"backgroundTag":null,"analyzedSha":"e6b18ccea71451a55fcd861d7b96fddf2587b09a","analyzedAt":"2026-08-14T20:05:26.414Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}