{"record":{"id":"fe78a917d06d2588","repo":"d2l-ai/d2l-zh","slug":"test-acc-1-and-test-acc-0-7-fe78a9","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/torch.py","lineNumber":341,"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\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`\"\"\"\n    metric = d2l.Accumulator(2)  # 损失的总和,样本数量","sourceCodeStart":323,"sourceCodeEnd":359,"githubUrl":"https://github.com/d2l-ai/d2l-zh/blob/e6b18ccea71451a55fcd861d7b96fddf2587b09a/d2l/torch.py#L323-L359","documentation":"Python AssertionError from d2l.torch.train_ch3's final sanity check: test accuracy must be in (0.7, 1] after training on Fashion-MNIST. It verifies the trained model generalizes as the book claims (~0.83 test acc); failure means underfitting, divergence, or an evaluation-path bug rather than a library defect.","triggerScenarios":"evaluate_accuracy(net, test_iter) returning <= 0.7: model undertrained (num_epochs=1-3), diverged lr, net reused from a previous overfit state, or test_iter normalized differently from train_iter (e.g. ToTensor only on the test transform path by mistake); also evaluating with net still in train() mode so dropout/batchnorm skew results if a custom net uses them.","commonSituations":"CPU-only environments where users trim num_epochs; reusing a net variable across notebook cells without re-instantiation; transforms applied inconsistently between the two DataLoaders; running on torch>=2.6 where default DataLoader/factory settings changed and iterators need explicit handling.","solutions":["Rerun with the book's configuration: fresh net, num_epochs=10, lr=0.1, batch_size=256","Build train_iter and test_iter with identical transforms (only shuffle=True vs False differs)","Confirm net.eval() semantics if your custom model has dropout/batchnorm (d2l's evaluate_accuracy handles the standard softmax net)","If train acc is high but test acc ~0.1, check label order/argmax axis and that the same net object is passed to evaluation"],"exampleFix":"# before\ntrain_iter = load_data_fashion_mnist(batch_size, resize=None)[0]  # normalized\n_, test_iter = load_data_fashion_mnist(batch_size)              # different path\ntrain_ch3(net, train_iter, test_iter, loss, 2, updater)  # test_acc 0.5 -> AssertionError\n# after\ntrain_iter, test_iter = load_data_fashion_mnist(256)\nnet = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))\ntrainer = torch.optim.SGD(net.parameters(), lr=0.1)\ntrain_ch3(net, train_iter, test_iter, loss, 10, trainer.step)  # test_acc ~0.83","handlingStrategy":"validation","validationCode":"train_iter, test_iter = d2l.load_data_fashion_mnist(256)  # same transforms\nnet = build_fresh_net()  # rebuild, never reuse stale weights\nassert next(iter(test_iter)) is not None","typeGuard":"def eval_pipeline_ready(net, test_iter) -> bool:\n    X, y = next(iter(test_iter))\n    return net(X).shape[1] == 10 and X.shape[0] == y.shape[0]","tryCatchPattern":"try:\n    train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)\nexcept AssertionError as e:\n    print(f'test_acc={e.args[0]} outside (0.7, 1]; check epochs, transforms, net freshness')\n    raise","preventionTips":["Create both DataLoaders from load_data_fashion_mnist so transforms match","Instantiate a fresh net per experiment","Keep num_epochs=10; do not trim for speed in assert-bearing code","Verify transforms (ToTensor/normalize) applied to both splits"],"tags":["d2l","pytorch","assertion","evaluation","generalization","fashion-mnist"],"backgroundTag":null,"analyzedSha":"e6b18ccea71451a55fcd861d7b96fddf2587b09a","analyzedAt":"2026-08-14T20:05:26.414Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}