VSCode提示Import "torch" could not be resolved但命令行可正常运行如何解决
故障解决方案
- 核对Python解释器路径
此类问题基本都是多环境路径不匹配导致的,先在Windows命令行执行where python,记下可以正常运行代码的Python环境完整路径。之后打开VSCode,按快捷键Ctrl+Shift+P调出命令面板,搜索Python: 选择解释器,在弹出的列表里选择和刚才记录的路径完全一致的解释器即可。
注:pip安装的第三方包只会生效在当前执行pip命令的环境下,VSCode默认调用的Python环境,大概率不是你实际安装了pytorch的那个环境 - 验证工作目录配置
如果确认解释器匹配后仍报错,打开VSCode设置页,搜索python.terminal.executeInFileDir,将该选项勾选为开启状态,避免运行代码时工作目录异常导致的模块加载失败。 - 清除工作区缓存
若以上操作均无效,可以关闭当前VSCode窗口,删除项目根目录下的.vscode文件夹,重新打开项目后再次选择对应解释器运行代码即可。
测试验证代码
import torch # Model model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True) # Images imgs = ['https://ultralytics.com/images/zidane.jpg'] # batch of images # Inference results = model(imgs) # Results results.print() results.save() # or .show() results.xyxy[0] # img1 predictions (tensor) results.pandas().xyxy[0] # img1 predictions (pandas) # xmin ymin xmax ymax confidence class name # 0 749.50 43.50 1148.0 704.5 0.874023 0 person # 1 433.50 433.50 517.5 714.5 0.687988 27 tie # 2 114.75 195.75 1095.0 708.0 0.624512 0 person # 3 986.00 304.00 1028.0 420.0 0.286865 27 tie
内容的提问来源于stack exchange,提问作者JohnWick
相关产品推荐
相关产品推荐

