{"record":{"id":"98f02b66384a0ebf","repo":"d2l-ai/d2l-zh","slug":"train-loss-0-5-98f02b","errorCode":null,"errorMessage":"train_loss < 0.5","messagePattern":"train_loss < 0\\.5","errorType":"validation","errorClass":"AssertionError","httpStatus":null,"severity":"error","filePath":"d2l/paddle.py","lineNumber":350,"sourceCode":"        self.axes[0].cla()\n        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","sourceCodeStart":332,"sourceCodeEnd":368,"githubUrl":"https://github.com/d2l-ai/d2l-zh/blob/e6b18ccea71451a55fcd861d7b96fddf2587b09a/d2l/paddle.py#L332-L368","documentation":"An AssertionError raised at the end of d2l.paddle.train_ch3, the PaddlePaddle edition of the chapter-3 softmax-regression training loop. After the final epoch it requires train_loss < 0.5 on Fashion-MNIST; a value >= 0.5 means the model diverged or undertrained, and the assert turns that into an immediate failure.","triggerScenarios":"Running train_ch3 with too-large lr (loss oscillates or explodes), too-small lr, or too few epochs; a custom updater that fails to average gradients per batch; loss reduction differences across Paddle versions scaling the reported loss upward.","commonSituations":"Modifying the sec_softmax_scratch notebook's lr/batch_size; writing a Paddle updater that skips param gradient application (clear_gradients/set_state_dict mistakes); training on a small slice of the dataset where convergence stalls above 0.5.","solutions":["Restore the book's hyperparameters: lr=0.1 (from-scratch SGD), batch_size=256, num_epochs=10.","Ensure the updater averages gradients over the batch (divide summed gradients by batch_size) exactly like d2l.Updater/paddle.sgd.","Use the default loss (paddle regularized cross-entropy with mean reduction) so the 0.5 threshold is comparable.","Watch the Animator: if loss is still falling at the last epoch, raise num_epochs; if it spikes, lower lr."],"exampleFix":"# before\nupdater = Updater([W, b], lr=5.0)  # divergence -> AssertionError\n# after\nupdater = Updater([W, b], lr=0.1)\ntrain_ch3(net, train_iter, test_iter, loss, 10, updater)","handlingStrategy":"validation","validationCode":"final = train_epoch_ch3(net, train_iter, loss, updater)\nif final[0] >= 0.5:\n    raise ValueError(f'loss={final[0]:.3f} >= 0.5; check lr (try 0.1), '\n                     f'batch-averaged gradients, and num_epochs=10')","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 loss check failed ({e}); '\n                       f'verify lr=0.1 and mean-reduced loss') from e","preventionTips":["Default to lr=0.1, batch_size=256, num_epochs=10 for Fashion-MNIST softmax regression.","In custom Paddle updaters, divide accumulated gradients by batch_size.","Confirm paddle's loss uses mean reduction so the 0.5 threshold applies.","Inspect the Animator per epoch rather than waiting for the final assert."],"tags":["d2l","paddle","training","softmax-regression","assertion","hyperparameters"],"backgroundTag":null,"analyzedSha":"e6b18ccea71451a55fcd861d7b96fddf2587b09a","analyzedAt":"2026-08-14T20:05:26.414Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}