{"record":{"id":"b6d9305f2148b1db","repo":"d2l-ai/d2l-zh","slug":"test-acc-1-and-test-acc-0-7-b6d930","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/paddle.py","lineNumber":352,"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":334,"sourceCodeEnd":370,"githubUrl":"https://github.com/d2l-ai/d2l-zh/blob/e6b18ccea71451a55fcd861d7b96fddf2587b09a/d2l/paddle.py#L334-L370","documentation":"An AssertionError in d2l.paddle.train_ch3 requiring final test accuracy in (0.7, 1]. It validates the evaluation path of the PaddlePaddle softmax-regression benchmark: the net must generalize past 70% on the Fashion-MNIST test set and the metric must stay within valid bounds.","triggerScenarios":"Evaluating an untrained or freshly re-initialized net; passing an empty/mis-built test_iter; test preprocessing differing from train preprocessing; divergence from bad hyperparameters pinning test accuracy near chance (~0.1).","commonSituations":"Notebook cell order re-creating the net between training and evaluation; using d2l.load_data_fashion_mnist with different resize/normalize for the two splits; Paddle version changes in loss or argmax semantics.","solutions":["Evaluate the same net object that went through train_ch3 — do not re-instantiate it afterwards.","Build both iterators from d2l.load_data_fashion_mnist(batch_size, resize=None) so preprocessing matches.","Fix divergence first (lr, updater) — test accuracy tracks the loss asserts above.","Sanity-check with evaluate_accuracy(net, test_iter) before train_ch3: it should print ~0.1 for a fresh net and ~0.83 after training."],"exampleFix":"# before\nnet = SoftmaxRegression()      # accidentally re-created\ntrain_ch3(net, ...)             # test_acc <= 0.7 -> AssertionError\n# after\nnet = SoftmaxRegression()\ntrain_ch3(net, train_iter, test_iter, loss, 10, updater)  # same object","handlingStrategy":"validation","validationCode":"test_acc = evaluate_accuracy(net, test_iter)\nif not (0.7 < test_acc <= 1.0):\n    raise ValueError(f'test_acc={test_acc:.3f} outside (0.7, 1]; verify the '\n                     f'trained net object and matching test preprocessing')","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 test-accuracy check failed ({e})') from e","preventionTips":["Never re-create the net between training and evaluation.","Build both splits via d2l.load_data_fashion_mnist with identical transforms.","Baseline fresh-net accuracy (~0.1 expected) to detect pipeline breakage early."],"tags":["d2l","paddle","training","evaluation","assertion"],"backgroundTag":null,"analyzedSha":"e6b18ccea71451a55fcd861d7b96fddf2587b09a","analyzedAt":"2026-08-14T20:05:26.414Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}