You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用fasterrcnn_resnet50_fpn遇WinError10054,手动加载权重无效求助

解决Faster R-CNN权重加载时的连接错误问题

问题原因

你使用的weights_path并不是fasterrcnn_resnet50_fpn()函数的合法参数,传入后会被忽略,函数仍默认尝试从官网下载权重,进而触发连接错误。

解决方法

以下两种方式均可实现加载本地预训练权重,避免自动下载:

方法1(适配PyTorch 1.13+/torchvision 0.14+新版本)

先创建不带预训练权重的模型,再手动加载本地权重文件:

import torch
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor

# 创建未加载预训练权重的模型
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=None)

# 加载本地权重文件
local_weights_path = './fasterrcnn_resnet50_fpn_coco-258fb6c6.pth'
state_dict = torch.load(local_weights_path)
model.load_state_dict(state_dict)

# 替换分类器(保留原有逻辑)
num_classes = 2  # 1类(目标) + 背景
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)

方法2(适配旧版本PyTorch/torchvision)

若你的torchvision版本低于0.14,使用pretrained=False禁用自动下载后加载本地权重:

import torch
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor

# 创建未加载预训练权重的模型
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False)

# 加载本地权重文件
local_weights_path = './fasterrcnn_resnet50_fpn_coco-258fb6c6.pth'
state_dict = torch.load(local_weights_path)
model.load_state_dict(state_dict)

# 替换分类器(保留原有逻辑)
num_classes = 2  # 1类(目标) + 背景
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)

注意事项

  • 确保本地权重文件路径正确,建议使用绝对路径避免路径解析错误
  • 确认下载的本地权重文件与模型结构匹配,Faster R-CNN的COCO预训练权重文件名应为fasterrcnn_resnet50_fpn_coco-258fb6c6.pth
  • 可通过print(torchvision.__version__)查看当前torchvision版本,选择对应方法

内容的提问来源于stack exchange,提问作者Qamil Mirza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 23:55:04