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

not found weights file: {}

Error message

not found weights file: {}

What it means

The shufflenet training script raises FileNotFoundError in main() when args.weights is set to a path that does not exist on disk. It fails fast rather than silently training from scratch, since users who pass --weights expect pre-trained initialization.

Source

Thrown at pytorch_classification/Test7_shufflenet/train.py:73

                                               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 = shufflenet_v2_x1_0(num_classes=args.num_classes).to(device)
    if args.weights != "":
        if os.path.exists(args.weights):
            weights_dict = torch.load(args.weights, map_location=device)
            load_weights_dict = {k: v for k, v in weights_dict.items()
                                 if model.state_dict()[k].numel() == v.numel()}
            print(model.load_state_dict(load_weights_dict, strict=False))
        else:
            raise FileNotFoundError("not found weights file: {}".format(args.weights))

    # 是否冻结权重
    if args.freeze_layers:
        for name, para in model.named_parameters():
            # 除最后的全连接层外,其他权重全部冻结
            if "fc" 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=4E-5)
    # 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. Verify and correct the --weights path (ls the exact value, prefer absolute paths).
  2. Download the shufflenetv2 pre-trained weights and pass their absolute path.
  3. Pass --weights '' if you intend to train from random initialization, since the load branch only runs for a non-empty path.

Example fix

// before
python train.py --weights ./shufflenetv2.pth
// after
python train.py --weights /abs/path/shufflenetv2_x1-5666bf0f80.pth
Defensive patterns

Strategy: validation

Validate before calling

import os
if args.weights and not os.path.isfile(args.weights):
    sys.exit(f"weights file missing: {os.path.abspath(args.weights)}")

Try / catch

try:
    weights_dict = torch.load(args.weights, map_location=device)
except FileNotFoundError as e:
    print(f"WARNING: {e}; starting from random init")
    weights_dict = None

Prevention

When it happens

Trigger: Running `python train.py --weights some/path.pth` where the file is absent: wrong filename, weights never downloaded, or a relative path that doesn't resolve from the current working directory.

Common situations: Tutorial users missing the shufflenetv2 pre-trained checkpoint download; moving/renaming the .pth after download; launching the script from another directory (IDE run configs often change cwd).

Related errors


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