{"record":{"id":"98853a7fe8050007","repo":"d2l-ai/d2l-zh","slug":"test-acc-1-and-test-acc-0-7-98853a","errorCode":null,"errorMessage":"test_acc <= 1 and test_acc > 0.7","messagePattern":"test_acc <= 1 and test_acc > 0\\.7","errorType":"validation","errorClass":"AssertionError","httpStatus":null,"severity":"error","filePath":"d2l/tensorflow.py","lineNumber":321,"sourceCode":"            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:\n        break","sourceCodeStart":303,"sourceCodeEnd":339,"githubUrl":"https://github.com/d2l-ai/d2l-zh/blob/e6b18ccea71451a55fcd861d7b96fddf2587b09a/d2l/tensorflow.py#L303-L339","documentation":"An AssertionError in d2l.tensorflow.train_ch3 that final test accuracy must be in (0.7, 1] for the Fashion-MNIST softmax-regression benchmark. It guards the evaluation half of the pipeline: evaluate_accuracy must run against the real test_iter, and the net must generalize past 70%. A value > 1 indicates the metric denominator is wrong; <= 0.7 indicates undertraining, divergence, or evaluating an untrained/different model.","triggerScenarios":"Passing an empty or wrong test_iter (accuracy 0/0 or NaN); evaluating a freshly re-initialized net instead of the trained one; label/shape mismatch making every prediction wrong; divergence from too-high lr dropping test accuracy to chance level (~0.1).","commonSituations":"Notebook cell reordering that re-creates net after training; using a test_iter built with a different preprocessing than train_iter; TF version differences in SparseCategoricalCrossentropy from_logits handling producing near-zero accuracy.","solutions":["Make sure evaluate_accuracy(net, test_iter) is called on the same net object that was trained, after the training loop.","Confirm loss matches output form: use from_logits=True only if the net returns logits (no softmax layer).","Rebuild train_iter/test_iter with identical preprocessing (resize to 28x28, scale to [0,1]) via d2l.load_data_fashion_mnist.","If accuracy is near 0.1 (chance), apply the fixes for the loss assert first (lr, updater scaling) — accuracy follows the loss."],"exampleFix":"# before: net re-created before eval\nnet = tf.keras.Model(...)  # wipes trained weights\ntrain_ch3(net, ...)  # test_acc <= 0.7 -> AssertionError\n# after: train once, evaluate the same net\ntrain_ch3(net, train_iter, test_iter, loss, 10, updater)","handlingStrategy":"validation","validationCode":"test_acc = evaluate_accuracy(net, test_iter)\nif not (0.7 < test_acc <= 1.0):\n    raise ValueError(f'test_acc out of expected (0.7, 1]: {test_acc:.3f}; '\n                     f'verify same net is evaluated and preprocessing matches train')","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 test-accuracy check failed ({e}); '\n                       f'check test_iter construction and from_logits setting') from e","preventionTips":["Evaluate the exact net object that was trained; never re-instantiate between train and eval.","Build both iterators with d2l.load_data_fashion_mnist so preprocessing is identical.","Match from_logits to your model's output (no softmax layer => from_logits=True).","Baseline a fresh net with evaluate_accuracy — expect ~0.1 before training."],"tags":["d2l","tensorflow","training","evaluation","assertion"],"backgroundTag":null,"analyzedSha":"e6b18ccea71451a55fcd861d7b96fddf2587b09a","analyzedAt":"2026-08-14T20:05:26.414Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}