yolov5 icon indicating copy to clipboard operation
yolov5 copied to clipboard

关于“TypeError: attempt_load() got an unexpected keyword argument 'map_location'”

Open zglihs opened this issue 3 years ago • 11 comments

Search before asking

  • [X] I have searched the YOLOv5 issues and discussions and found no similar questions.

Question

YOLOV5版本:V6.0

1、关于“TypeError: attempt_load() got an unexpected keyword argument 'map_location'”的提示,详细如下是执行和提示 (y5x11) D:\workspace\yolov5>python web_main.py [INFO] YOLOv5 Config: {'source': 'streams.txt', '@source': '为视频图像文件 地址', 'weights': 'runs/train/exp14/weights/best.pt', '@weights': '自己的 模型地址', 'device': '0', '@device': ' 使用的device类别,如是GPU,可填0', 'imgsz': 640, '@imgsz': '输入图像的大小', 'stride': 32, '@stride': ' 步长', 'conf_thres': 0.35, '@conf_thres': '置信值阈值', 'iou_thres': 0.45, '@iou_thres': ' iou阈值', 'augment': False, '@augment': '是否使用图像增强'}
fatal: Not a valid object name HEAD YOLOv5 2022-6-1 Python-3.8.13 torch-1.10.0+cu113 CUDA:0 (NVIDIA GeForce RTX 3060, 12288MiB)

Traceback (most recent call last): File "web_main.py", line 25, in

(y5x11) D:\workspace\yolov5>python web_main.py [INFO] YOLOv5 Config: {'source': 'streams.txt', '@source': '为视频图像文件 地址', 'weights': 'runs/train/exp14/weights/best.pt', '@weights': '自己的 模型地址', 'device': '0', '@device': ' 使用的device类别,如是GPU,可填0', 'imgsz': 640, '@imgsz': '输入图像的大小', 'stride': 32, '@stride': ' 步长', 'conf_thres': 0.35, '@conf_thres': '置信值阈值', 'iou_thres': 0.45, '@iou_thres': ' iou阈值', 'augment': False, '@augment': '是否使用图像增强'}
fatal: Not a valid object name HEAD YOLOv5 2022-6-1 Python-3.8.13 torch-1.10.0+cu113 CUDA:0 (NVIDIA GeForce RTX 3060, 12288MiB)

Traceback (most recent call last): File "web_main.py", line 25, in darknet = Darknet(opt) File "D:\workspace\yolov5\yolov5.py", line 20, in init self.model = attempt_load(self.opt["weights"], map_location=self.device) TypeError: attempt_load() got an unexpected keyword argument 'map_location' 2、代码如下: #web_main.py

import the necessary packages

from yolov5 import Darknet from camera import LoadStreams, LoadImages from utils.general import non_max_suppression, scale_coords, check_imshow from flask import Response from flask import Flask from flask import render_template import time import torch import json import cv2 import os

initialize a flask object

app = Flask(name)

initialize the video stream and allow the camera sensor to warmup

with open('yolov5_config.json', 'r', encoding='utf8') as fp: opt = json.load(fp) print('[INFO] YOLOv5 Config:', opt)

darknet = Darknet(opt) if darknet.webcam: # cudnn.benchmark = True # set True to speed up constant image size inference dataset = LoadStreams(darknet.source, img_size=opt["imgsz"], stride=darknet.stride) else: dataset = LoadImages(darknet.source, img_size=opt["imgsz"], stride=darknet.stride) time.sleep(2.0)

@app.route("/") def index(): # return the rendered template return render_template("index.html")

def detect_gen(dataset, feed_type): view_img = check_imshow() t0 = time.time() for path, img, img0s, vid_cap in dataset: img = darknet.preprocess(img)

    t1 = time.time()
    pred = darknet.model(img, augment=darknet.opt["augment"])[0]  # 0.22s
    pred = pred.float()
    pred = non_max_suppression(pred, darknet.opt["conf_thres"], darknet.opt["iou_thres"])
    t2 = time.time()

    pred_boxes = []
    for i, det in enumerate(pred):
        if darknet.webcam:  # batch_size >= 1
            feed_type_curr, p, s, im0, frame = "Camera_%s" % str(i), path[i], '%g: ' % i, img0s[i].copy(), dataset.count
        else:
            feed_type_curr, p, s, im0, frame = "Camera", path, '', img0s, getattr(dataset, 'frame', 0)

        s += '%gx%g ' % img.shape[2:]  # print string
        gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
        if det is not None and len(det):
            det[:, :4] = scale_coords(
                img.shape[2:], det[:, :4], im0.shape).round()

            # Print results
            for c in det[:, -1].unique():
                n = (det[:, -1] == c).sum()  # detections per class
                s += f"{n} {darknet.names[int(c)]}{'s' * (n > 1)}, "  # add to string

            for *xyxy, conf, cls_id in det:
                lbl = darknet.names[int(cls_id)]
                xyxy = torch.tensor(xyxy).view(1, 4).view(-1).tolist()
                score = round(conf.tolist(), 3)
                label = "{}: {}".format(lbl, score)
                x1, y1, x2, y2 = int(xyxy[0]), int(xyxy[1]), int(xyxy[2]), int(xyxy[3])
                pred_boxes.append((x1, y1, x2, y2, lbl, score))
                if view_img:
                    darknet.plot_one_box(xyxy, im0, color=(255, 0, 0), label=label)

        # Print time (inference + NMS)
        # print(pred_boxes)
        print(f'{s}Done. ({t2 - t1:.3f}s)')
        if feed_type_curr == feed_type:
            frame = cv2.imencode('.jpg', im0)[1].tobytes()
            yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video_feed/<feed_type>') def video_feed(feed_type): """Video streaming route. Put this in the src attribute of an img tag.""" if feed_type == 'Camera_0': return Response(detect_gen(dataset=dataset, feed_type=feed_type), mimetype='multipart/x-mixed-replace; boundary=frame')

elif feed_type == 'Camera_1':
    return Response(detect_gen(dataset=dataset, feed_type=feed_type),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if name == 'main': app.run(host='0.0.0.0', port="5000", threaded=True)

Additional

No response

zglihs avatar Jun 12 '22 03:06 zglihs

👋 Hello @zglihs, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide screenshots and minimum viable code to reproduce your issue, otherwise we can not help you.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online W&B logging if available.

For business inquiries or professional support requests please visit https://ultralytics.com or email [email protected].

Requirements

Python>=3.7.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

CI CPU testing

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training (train.py), validation (val.py), inference (detect.py) and export (export.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit.

github-actions[bot] avatar Jun 12 '22 03:06 github-actions[bot]

There are no brothers with such a problem?

zglihs avatar Jun 12 '22 03:06 zglihs

Correction: yolov5 version used is V6.1

zglihs avatar Jun 12 '22 03:06 zglihs

I am facing the same issue how to remove this issue?

noreenanwar avatar Jun 25 '22 19:06 noreenanwar

@zglihs @noreenanwar 👋 hi, thanks for letting us know about this possible problem with YOLOv5 🚀. We've created a few short guidelines below to help users provide what we need in order to start investigating a possible problem.

How to create a Minimal, Reproducible Example

When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. This is referred to by community members as creating a minimum reproducible example. Your code that reproduces the problem should be:

  • Minimal – Use as little code as possible to produce the problem
  • Complete – Provide all parts someone else needs to reproduce the problem
  • Reproducible – Test the code you're about to provide to make sure it reproduces the problem

For Ultralytics to provide assistance your code should also be:

  • Current – Verify that your code is up-to-date with GitHub master, and if necessary git pull or git clone a new copy to ensure your problem has not already been solved in master.
  • Unmodified – Your problem must be reproducible using official YOLOv5 code without changes. Ultralytics does not provide support for custom code ⚠️.

If you believe your problem meets all the above criteria, please close this issue and raise a new one using the 🐛 Bug Report template with a minimum reproducible example to help us better understand and diagnose your problem.

Thank you! 😃

glenn-jocher avatar Jun 26 '22 12:06 glenn-jocher

I am facing the same issue how to remove this issue?

me too, I got the same error

yuerlong avatar Jul 05 '22 07:07 yuerlong

@yuerlong 👋 hi, thanks for letting us know about this possible problem with YOLOv5 🚀. We've created a few short guidelines below to help users provide what we need in order to start investigating a possible problem.

How to create a Minimal, Reproducible Example

When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. This is referred to by community members as creating a minimum reproducible example. Your code that reproduces the problem should be:

  • Minimal – Use as little code as possible to produce the problem
  • Complete – Provide all parts someone else needs to reproduce the problem
  • Reproducible – Test the code you're about to provide to make sure it reproduces the problem

For Ultralytics to provide assistance your code should also be:

  • Current – Verify that your code is up-to-date with GitHub master, and if necessary git pull or git clone a new copy to ensure your problem has not already been solved in master.
  • Unmodified – Your problem must be reproducible using official YOLOv5 code without changes. Ultralytics does not provide support for custom code ⚠️.

If you believe your problem meets all the above criteria, please close this issue and raise a new one using the 🐛 Bug Report template with a minimum reproducible example to help us better understand and diagnose your problem.

Thank you! 😃

glenn-jocher avatar Jul 05 '22 09:07 glenn-jocher

I am facing the same issue how to remove this issue?

I reverted back old commit and this error is gone. It seems that the latest has this issue.

yuerlong avatar Jul 05 '22 22:07 yuerlong

This function is defined as follows: def attempt_load(weights, device=None, inplace=True, fuse=True):

So we need to change the ’map_location=‘ location to ’device=‘

jxzddup avatar Jul 06 '22 02:07 jxzddup

@jxzddup yes that's correct. attempt_load() map_location argument has been renamed to device: https://github.com/ultralytics/yolov5/blob/1ab23fc67f52d44d5f8ce67a895e73c7cbd7aec5/models/experimental.py#L74-L75

glenn-jocher avatar Jul 07 '22 10:07 glenn-jocher

👋 Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs.

Access additional YOLOv5 🚀 resources:

  • Wiki – https://github.com/ultralytics/yolov5/wiki
  • Tutorials – https://docs.ultralytics.com/yolov5
  • Docs – https://docs.ultralytics.com

Access additional Ultralytics ⚡ resources:

  • Ultralytics HUB – https://ultralytics.com/hub
  • Vision API – https://ultralytics.com/yolov5
  • About Us – https://ultralytics.com/about
  • Join Our Team – https://ultralytics.com/work
  • Contact Us – https://ultralytics.com/contact

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLOv5 🚀 and Vision AI ⭐!

github-actions[bot] avatar Aug 07 '22 00:08 github-actions[bot]

bumped into same issue. map_location -> device WAS model = attempt_load(modelpath, map_location=device) NOW model = attempt_load(modelpath, device=device)

apiszcz avatar Sep 02 '22 10:09 apiszcz

how?

fahad-2747 avatar Nov 29 '22 14:11 fahad-2747

@fahad-2747 the map_location parameter was renamed to device in the attempt_load function. So, to resolve the issue, simply replace map_location=device with device=device in the function call.

Here is an example: Before:

model = attempt_load(modelpath, map_location=device)

After:

model = attempt_load(modelpath, device=device)

By making this change, you can resolve the TypeError: attempt_load() got an unexpected keyword argument 'map_location' issue.

glenn-jocher avatar Nov 15 '23 14:11 glenn-jocher