{"record":{"id":"3c0425ba40bdb3b0","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"not-found-weights-file","errorCode":null,"errorMessage":"not found weights file: {}","messagePattern":"not found weights file: (.+?)","errorType":"exception","errorClass":"FileNotFoundError","httpStatus":null,"severity":"error","filePath":"pytorch_classification/Test10_regnet/train.py","lineNumber":76,"sourceCode":"                                             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 = create_regnet(model_name=args.model_name,\n                          num_classes=args.num_classes).to(device)\n    # print(model)\n\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 \"head\" not in name:\n                para.requires_grad_(False)\n            else:\n                print(\"train {}\".format(name))\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=5E-5)\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","sourceCodeStart":58,"sourceCodeEnd":94,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_classification/Test10_regnet/train.py#L58-L94","documentation":"train.py only attempts to load pretrained weights if os.path.exists(args.weights); when the file path is set but missing, it raises FileNotFoundError instead of silently training from scratch.","triggerScenarios":"Running train.py with --weights ./regnetx_400mf.pth where the .pth was never downloaded, renamed, or is in a different working directory.","commonSituations":"Forgot to run pretrain_weights.py first; typo in the path; weights downloaded under a different filename than the --weights argument.","solutions":["Download the weights first (run pretrain_weights.py) so the file exists at args.weights.","Verify/correct the --weights path (absolute path or correct relative path from the CWD).","Pass --weights '' or omit it if you intend to train from scratch (per the script's empty-string convention)."],"exampleFix":"// before\npython train.py --weights ./regnetx_400mf.pth   # file not downloaded\n// after\npython pretrain_weights.py && python train.py --weights ./regnetx_400mf.pth","handlingStrategy":"validation","validationCode":"import os\nweights = \"./regnetx_400mf.pth\"\nif weights and not os.path.exists(weights):\n    raise SystemExit(f\"weights missing: {weights}; run pretrain_weights.py first\")","typeGuard":"def weights_available(path) -> bool:\n    return not path or os.path.isfile(path)","tryCatchPattern":"try:\n    main()\nexcept FileNotFoundError as e:\n    print(f\"{e}; downloading weights...\")\n    os.system(\"python pretrain_weights.py\")\n    main()","preventionTips":["Run pretrain_weights.py before train.py","Verify --weights path exists (os.path.exists) at script start","Use absolute paths or paths relative to the script, not the shell CWD","Pass empty string for --weights to intentionally train from scratch"],"tags":["pytorch","file-not-found","pretrained-weights","cli-args"],"backgroundTag":"missing-weights-file","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}