WZMIAOMIAO/deep-learning-for-image-processing · error · FileNotFoundError

not found weights file: {}

Error message

not found weights file: {}

What it means

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.

Source

Thrown at pytorch_classification/Test8_densenet/train.py:70

                                               shuffle=True,
                                               pin_memory=True,
                                               num_workers=nw,
                                               collate_fn=train_dataset.collate_fn)

    val_loader = torch.utils.data.DataLoader(val_dataset,
                                             batch_size=batch_size,
                                             shuffle=False,
                                             pin_memory=True,
                                             num_workers=nw,
                                             collate_fn=val_dataset.collate_fn)

    # 如果存在预训练权重则载入
    model = densenet121(num_classes=args.num_classes).to(device)
    if args.weights != "":
        if os.path.exists(args.weights):
            load_state_dict(model, args.weights)
        else:
            raise FileNotFoundError("not found weights file: {}".format(args.weights))

    # 是否冻结权重
    if args.freeze_layers:
        for name, para in model.named_parameters():
            # 除最后的全连接层外,其他权重全部冻结
            if "classifier" not in name:
                para.requires_grad_(False)

    pg = [p for p in model.parameters() if p.requires_grad]
    optimizer = optim.SGD(pg, lr=args.lr, momentum=0.9, weight_decay=1E-4, nesterov=True)
    # Scheduler https://arxiv.org/pdf/1812.01187.pdf
    lf = lambda x: ((1 + math.cos(x * math.pi / args.epochs)) / 2) * (1 - args.lrf) + args.lrf  # cosine
    scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)

    for epoch in range(args.epochs):
        # train
        mean_loss = train_one_epoch(model=model,
                                    optimizer=optimizer,

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Download/checkpoint the expected .pth file and pass its correct full path via --weights
  2. Pass --weights "" (empty string) to skip weight loading and train from scratch
  3. Fix the relative path by running the script from the intended directory or using an absolute path

Example fix

// before
python train.py --weights ./weights/densnet121.pth  # typo: file missing
// after
python train.py --weights ./weights/densenet121.pth  # ensure file exists
Defensive patterns

Strategy: validation

Validate before calling

weights = args.weights
if weights and not os.path.exists(weights):
    raise SystemExit(f'weights file missing: {weights}')  # check before main() loads model

Try / catch

try:
    main()
except FileNotFoundError as e:
    print('Download pretrained weights or pass --weights "" to skip:', e)
    sys.exit(1)

Prevention

When it happens

Trigger: 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).

Common situations: 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.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/383b92396718aa7c. Report an issue: GitHub.