TypeError: attempt_load() got an unexpected keyword argument ‘map_location‘

文章讲述了在新版本中,尝试加载模型权重时出现错误的原因,是因为旧的调用方式已经不适用。新版本的函数定义要求使用device=而非map_location=。解决方法是按照新定义的函数结构更新代码,确保兼容性更新,以便正确加载和使用模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可能的原因:
错误代码

model = attempt_load(weights, map_location=device)


这在原来旧的版本里其实不算错,能正常运行,但是在当前新版本已经对这个进行了修改,再更以前一样使用就会报错,就像上面的那个一样,
当前新版本该函数定义如下:
def attempt_load(weights, device=None, inplace=True, fuse=True):

解决方法:
在yolov5/models/experimental.py可以看到

def attempt_load(weights, device=None, inplace=True, fuse=True):
from models.yolo import Detect, Model

# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
model = Ensemble()
for w in weights if isinstance(weights, list) else [weights]:
    ckpt = torch.load(attempt_download(w), map_location=device)
    ckpt = (ckpt.get('ema') or ckpt['model']).float()  # FP32 model
    model.append(ckpt.fuse().eval() if fuse else ckpt.eval())  # fused or un-fused model in eval mode

# Compatibility updates
for m in model.modules():
    t = type(m)
    if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
        m.inplace = inplace  # torch 1.7.0 compatibility
        if t is Detect and not isinstance(m.anchor_grid, list):
            delattr(m, 'anchor_grid')
            setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
    elif t is Conv:
        m._non_persistent_buffers_set = set()  # torch 1.6.0 compatibility
    elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):
        m.recompute_scale_factor = None  # torch 1.11.0 compatibility

if len(model) == 1:
    return model[-1]  # return model
print(f'Ensemble created with {weights}\n')
for k in 'names', 'nc', 'yaml':
    setattr(model, k, getattr(model[0], k))
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride  # max stride
assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
return model  # return ensemble

以此来确定自己的是不是当前新版本,并通过该定义可以知道,解决方法就是将 ‘map_location=’ 位置更改为 ‘device=’

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值