{"record":{"id":"383b92396718aa7c","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"not-found-weights-file-383b92","errorCode":null,"errorMessage":"not found weights file: {}","messagePattern":"not found weights file: (.+?)","errorType":"exception","errorClass":"FileNotFoundError","httpStatus":null,"severity":"error","filePath":"pytorch_classification/Test8_densenet/train.py","lineNumber":70,"sourceCode":"                                               shuffle=True,\n                                               pin_memory=True,\n                                               num_workers=nw,\n                                               collate_fn=train_dataset.collate_fn)\n\n    val_loader = torch.utils.data.DataLoader(val_dataset,\n                                             batch_size=batch_size,\n                                             shuffle=False,\n                                             pin_memory=True,\n                                             num_workers=nw,\n                                             collate_fn=val_dataset.collate_fn)\n\n    # 如果存在预训练权重则载入\n    model = densenet121(num_classes=args.num_classes).to(device)\n    if args.weights != \"\":\n        if os.path.exists(args.weights):\n            load_state_dict(model, args.weights)\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 \"classifier\" 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=1E-4, nesterov=True)\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":52,"sourceCodeEnd":88,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_classification/Test8_densenet/train.py#L52-L88","documentation":"train.py loads pretrained DenseNet weights from args.weights only if the path exists; otherwise it deliberately raises FileNotFoundError instead of training from scratch silently. It signals that the user asked for pretrained weights but supplied a path that does not exist on disk.","triggerScenarios":"Running train.py with --weights pointing to a missing or misspelled file (e.g. densenet121.pth not yet downloaded, wrong relative path from the working directory).","commonSituations":"Forgetting to download the official densenet121 weights from the download link before training; passing a Windows-style path on Linux; running the script from a different cwd so relative paths break.","solutions":["Download/checkpoint the expected .pth file and pass its correct full path via --weights","Pass --weights \"\" (empty string) to skip weight loading and train from scratch","Fix the relative path by running the script from the intended directory or using an absolute path"],"exampleFix":"// before\npython train.py --weights ./weights/densnet121.pth  # typo: file missing\n// after\npython train.py --weights ./weights/densenet121.pth  # ensure file exists","handlingStrategy":"validation","validationCode":"weights = args.weights\nif weights and not os.path.exists(weights):\n    raise SystemExit(f'weights file missing: {weights}')  # check before main() loads model","typeGuard":null,"tryCatchPattern":"try:\n    main()\nexcept FileNotFoundError as e:\n    print('Download pretrained weights or pass --weights \"\" to skip:', e)\n    sys.exit(1)","preventionTips":["Download the pretrained .pth into the expected directory before training","Use absolute paths or paths anchored to __file__ instead of cwd","Pass --weights \"\" explicitly when training from scratch"],"tags":["pytorch","file-not-found","pretrained-weights","argparse"],"backgroundTag":"missing-weights-file","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}