{"record":{"id":"9012500de688d027","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"not-found-weights-file-901250","errorCode":null,"errorMessage":"not found weights file: {}","messagePattern":"not found weights file: (.+?)","errorType":"exception","errorClass":"FileNotFoundError","httpStatus":null,"severity":"error","filePath":"pytorch_classification/train_multi_GPU/train_single_gpu.py","lineNumber":80,"sourceCode":"                                               collate_fn=train_data_set.collate_fn)\n\n    val_loader = torch.utils.data.DataLoader(val_data_set,\n                                             batch_size=batch_size,\n                                             shuffle=False,\n                                             pin_memory=True,\n                                             num_workers=nw,\n                                             collate_fn=val_data_set.collate_fn)\n\n    # 如果存在预训练权重则载入\n    model = resnet34(num_classes=args.num_classes).to(device)\n    if args.weights != \"\":\n        if os.path.exists(args.weights):\n            weights_dict = torch.load(args.weights, map_location=device)\n            load_weights_dict = {k: v for k, v in weights_dict.items()\n                                 if model.state_dict()[k].numel() == v.numel()}\n            print(model.load_state_dict(load_weights_dict, strict=False))\n        else:\n            raise FileNotFoundError(\"not found weights file: {}\".format(args.weights))\n\n    # 是否冻结权重\n    if args.freeze_layers:\n        for name, para in model.named_parameters():\n            # 除最后的全连接层外，其他权重全部冻结\n            if \"fc\" not in name:\n                para.requires_grad_(False)\n\n    pg = [p for p in model.parameters() if p.requires_grad]\n    optimizer = optim.SGD(pg, lr=args.lr, momentum=0.9, weight_decay=0.005)\n    # Scheduler https://arxiv.org/pdf/1812.01187.pdf\n    lf = lambda x: ((1 + math.cos(x * math.pi / args.epochs)) / 2) * (1 - args.lrf) + args.lrf  # cosine\n    scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)\n\n    for epoch in range(args.epochs):\n        # train\n        mean_loss = train_one_epoch(model=model,\n                                    optimizer=optimizer,","sourceCodeStart":62,"sourceCodeEnd":98,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_classification/train_multi_GPU/train_single_gpu.py#L62-L98","documentation":"This FileNotFoundError is raised when the --weights path supplied for resuming/fine-tuning does not exist on disk. The code checks os.path.exists(args.weights) and, if the file is missing, fails with the path in the message instead of letting torch.load throw a vaguer error.","triggerScenarios":"Invoking train_single_gpu.py with --weights pointing to a nonexistent file: typo in path, weights never trained/downloaded, relative path resolved from a different working directory, or the checkpoint was deleted/moved before the run.","commonSituations":"Copying a training command from docs without first running the training that produces weights; running from a different cwd so relative paths break; wrong filename (weights.pth vs best.pth); checkpoint stored in cloud storage not yet downloaded.","solutions":["Print/verify the exact path: ls -l <args.weights> from the same working directory the script runs in.","Pass an absolute path to --weights to avoid cwd ambiguity.","Download or train the checkpoint first (run the training script without --weights, or fetch the released model file).","If you intend to train from scratch, omit --weights so the branch is skipped entirely.","Add a caller-side os.path.exists() precheck before launching the script."],"exampleFix":"# before\npython train_single_gpu.py --weights ./checkpoints/model.pth\n# FileNotFoundError if missing\n# after\nimport os\ncmd = [\"python\", \"train_single_gpu.py\", \"--weights\", \"/abs/path/model.pth\"]\nassert os.path.exists(\"/abs/path/model.pth\"), \"checkpoint missing\"\nsubprocess.run(cmd)","handlingStrategy":"validation","validationCode":"import os, sys\nweights = args.weights\nif weights and not os.path.isfile(weights):\n    sys.exit(f\"weights not found: {os.path.abspath(weights)}\")","typeGuard":null,"tryCatchPattern":"try:\n    weights_dict = torch.load(args.weights, map_location=device)\nexcept FileNotFoundError as e:\n    logging.error(\"Checkpoint missing: %s — start training from scratch\", e)\n    weights_dict = None","preventionTips":["Use absolute paths for checkpoints in launch scripts.","Download pretrained weights as a setup step before training.","Resolve paths relative to the script file, not cwd."],"tags":["pytorch","file-not-found","checkpoint","paths"],"backgroundTag":"file-not-found","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}