WZMIAOMIAO/deep-learning-for-image-processing · error · FileNotFoundError
not found weights file: {}
Error message
not found weights file: {} What it means
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.
Source
Thrown at pytorch_classification/train_multi_GPU/train_single_gpu.py:80
collate_fn=train_data_set.collate_fn)
val_loader = torch.utils.data.DataLoader(val_data_set,
batch_size=batch_size,
shuffle=False,
pin_memory=True,
num_workers=nw,
collate_fn=val_data_set.collate_fn)
# 如果存在预训练权重则载入
model = resnet34(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=0.005)
# 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
- 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.
Example fix
# before
python train_single_gpu.py --weights ./checkpoints/model.pth
# FileNotFoundError if missing
# after
import os
cmd = ["python", "train_single_gpu.py", "--weights", "/abs/path/model.pth"]
assert os.path.exists("/abs/path/model.pth"), "checkpoint missing"
subprocess.run(cmd) Defensive patterns
Strategy: validation
Validate before calling
import os, sys
weights = args.weights
if weights and not os.path.isfile(weights):
sys.exit(f"weights not found: {os.path.abspath(weights)}") Try / catch
try:
weights_dict = torch.load(args.weights, map_location=device)
except FileNotFoundError as e:
logging.error("Checkpoint missing: %s — start training from scratch", e)
weights_dict = None Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Understand the failure class
Background: "File not found" and ENOENT errors: why libraries can't find a file that should exist — this error's family across 50 libraries.
Related errors
- not found weights file: {}
- not found weights file: {}
- not found weights file: {}
- not found weights file: {}
- not found weights file: {}
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/9012500de688d027.
Report an issue: GitHub.