【Bug已解决】Despite installing the torch vision pytorch library, I am getting an error saying that…

发布时间:2026/8/29 13:45:19
【Bug已解决】Despite installing the torch vision pytorch library, I am getting an error saying that… 【Bug已解决】Despite installing the torch vision pytorch library, I am getting an error saying that there is no module named torch vision 解决方案问题描述在安装 PyTorch 后许多开发者尝试导入torchvision时遇到ModuleNotFoundError: No module named torchvision错误。尽管torch可以正常导入但torchvision却找不到这是因为torchvision是一个独立的包需要单独安装而不是随torch自动安装的。具体错误信息ModuleNotFoundError: No module named torchvision或ImportError: cannot import name transforms from torchvision (unknown location)torchvision是 PyTorch 的计算机视觉工具库提供了常用数据集如 CIFAR、ImageNet、模型架构如 ResNet、VGG和图像变换工具如 transforms。它与 PyTorch 配合使用但作为独立包分发需要单独安装。常见的触发场景包括只安装了torch没有安装torchvision安装了不兼容的torchvision版本在错误的 Conda/venv 环境中安装使用 pip 安装了 torch 但用 conda 安装 torchvision或反之导致版本冲突torchvision 安装成功但导入时缺少依赖库如 PIL/Pillow。错误复现场景一只安装了 torchpip install torchimport torch # 成功 print(torch.__version__) # 2.0.1 import torchvision # 失败ModuleNotFoundError: No module named torchvision场景二版本不兼容pip install torch2.0.1 pip install torchvision0.14.0 # 与 torch 2.0.1 不兼容import torchvisionImportError: torchvision requires PyTorch 1.11.0 or later, but found 2.0.1 # 或其他版本不匹配错误场景三在错误的环境中安装# 在 base 环境中安装 conda activate base pip install torchvision # 切换到其他环境 conda activate myproject python -c import torchvisionModuleNotFoundError: No module named torchvision场景四缺少 Pillow 依赖pip install torchvisionfrom torchvision import transformsImportError: cannot import name transforms from torchvision (unknown location)这是因为 torchvision 安装时缺少 Pillow 依赖导致部分模块无法加载。场景五conda 和 pip 混用conda install pytorch2.0.1 pip install torchvision # pip 安装的版本可能与 conda 的 torch 不兼容import torchvisionRuntimeError: torchvision is not compatible with the installed PyTorch version.根因分析1. torchvision 是独立包torchvision不随torch自动安装。它们是两个独立的 PyPI/Conda 包需要分别安装。许多教程只提到安装torch忽略了torchvision。2. 版本兼容性要求torchvision与torch有严格的版本对应关系。安装不匹配的版本会导致导入错误或运行时错误torch 版本torchvision 版本torchaudio 版本2.0.x0.15.x2.0.x2.1.x0.16.x2.1.x2.2.x0.17.x2.2.x2.3.x0.18.x2.3.x1.13.x0.14.x0.13.x1.12.x0.13.x0.12.x1.11.x0.12.x0.11.x3. 安装环境不一致在 Conda 环境中如果先conda activate envA安装了 torchvision然后在envB中导入自然找不到。这是 Python 虚拟环境隔离的正常行为但容易被忽略。4. conda 和 pip 混用Conda 和 pip 使用不同的依赖解析机制。在同一个环境中混用 conda 和 pip 安装 torch 和 torchvision可能导致版本不匹配或 DLL 冲突尤其在 Windows 上。5. 缺少系统依赖torchvision 的某些功能依赖系统级库Pillow (PIL)图像读写libjpeg / libpngJPEG/PNG 图像编解码libavcodec / ffmpeg视频处理torchvision.io如果这些依赖缺失torchvision 可能安装成功但导入时部分模块不可用。6. 安装源问题使用非官方源安装 torchvision 可能获取到不兼容的版本。例如使用国内镜像源安装的 torchvision 可能是 CPU 版本与 GPU 版本的 torch 不兼容。解决方案方案一使用官方命令同时安装推荐最简单的方法是使用 PyTorch 官方推荐的安装命令同时安装 torch、torchvision 和 torchaudio# CUDA 11.8 版本 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 # CUDA 12.1 版本 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 # CPU 版本 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu # Conda 方式CUDA 11.8 conda install pytorch torchvision torchaudio pytorch-cuda11.8 -c pytorch -c nvidia -y方案二单独安装 torchvision如果 torch 已安装只需安装匹配版本的 torchvision# 查看当前 torch 版本 python -c import torch; print(torch.__version__) # 根据版本安装对应的 torchvision # torch 2.0.1 - torchvision 0.15.2 pip install torchvision0.15.2 --index-url https://download.pytorch.org/whl/cu118 # torch 2.1.0 - torchvision 0.16.0 pip install torchvision0.16.0 --index-url https://download.pytorch.org/whl/cu121方案三修复 conda/pip 混用问题# 卸载所有相关包 pip uninstall torch torchvision torchaudio -y conda uninstall pytorch torchvision torchaudio -y # 使用统一方式重新安装 # 方式 A: 全部用 conda conda install pytorch torchvision torchaudio pytorch-cuda11.8 -c pytorch -c nvidia -y # 方式 B: 全部用 pip pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118方案四安装缺失的依赖# 安装 Pillow pip install Pillow # 安装其他依赖 pip install numpy scipy # 在 Linux 上安装系统依赖 sudo apt-get install -y libjpeg-dev libpng-dev libavcodec-dev libavformat-dev libswscale-dev # 验证 python -c from torchvision import transforms; print(transforms 导入成功) python -c from torchvision import datasets; print(datasets 导入成功) python -c from torchvision import models; print(models 导入成功)方案五从源码安装解决特殊兼容性问题# 克隆 torchvision 仓库 git clone https://github.com/pytorch/vision.git cd vision # 切换到匹配的分支 git checkout v0.15.2 # 对应 torch 2.0.1 # 安装 pip install -e . # 或 python setup.py install完整修复代码以下是一个完整的诊断和修复脚本 torchvision 安装诊断与修复脚本 import sys import subprocess import importlib ![配图](https://i-blog.csdnimg.cn/img_convert/02f718d179e1ec0d10c7821ec39dab37.png) import platform def get_torch_info(): 获取已安装的 torch 信息 try: import torch return { installed: True, version: torch.__version__, cuda_version: torch.version.cuda, is_available: torch.cuda.is_available(), path: torch.__file__ } except ImportError: return {installed: False} def get_torchvision_info(): 获取已安装的 torchvision 信息 try: import torchvision return { installed: True, version: torchvision.__version__, path: torchvision.__file__ } except ImportError: return {installed: False} except Exception as e: return {installed: False, error: str(e)} def get_compatible_torchvision_version(torch_version): 根据 torch 版本获取兼容的 torchvision 版本 compatibility_map { 2.3.: 0.18., 2.2.: 0.17., 2.1.: 0.16., 2.0.: 0.15., 1.13.: 0.14., 1.12.: 0.13., 1.11.: 0.12., 1.10.: 0.11., } for torch_prefix, tv_prefix in compatibility_map.items(): if torch_version.startswith(torch_prefix): return tv_prefix return None def check_dependencies(): 检查 torchvision 的依赖 deps { PIL (Pillow): PIL, numpy: numpy, scipy: scipy, requests: requests, } results {} for name, module_name in deps.items(): try: mod importlib.import_module(module_name) version getattr(mod, __version__, unknown) results[name] {installed: True, version: version} except ImportError: results[name] {installed: False} return results def diagnose(): 运行完整诊断 print( * 60) print( torchvision 安装诊断) print( * 60) print() # 系统信息 print(fPython: {sys.version}) print(f平台: {platform.system()} {platform.machine()}) print(fPython 路径: {sys.executable}) print() # torch 信息 print(--- torch 信息 ---) torch_info get_torch_info() if torch_info[installed]: print(f 版本: {torch_info[version]}) print(f CUDA 版本: {torch_info[cuda_version]}) print(f CUDA 可用: {torch_info[is_available]}) print(f 路径: {torch_info[path]}) else: print( [FAIL] torch 未安装!) print( 请先安装 torch:) print( pip install torch --index-url https://download.pytorch.org/whl/cu118) return print() # torchvision 信息 print(--- torchvision 信息 ---) tv_info get_torchvision_info() if tv_info[installed]: print(f 版本: {tv_info[version]}) print(f 路径: {tv_info[path]}) # 检查版本兼容性 compatible_prefix get_compatible_torchvision_version(torch_info[version]) if compatible_prefix: if tv_info[version].startswith(compatible_prefix): print(f [OK] 版本兼容 (torch {torch_info[version]} torchvision {tv_info[version]})) else: print(f [WARN] 版本可能不兼容!) print(f torch {torch_info[version]} 需要 torchvision {compatible_prefix}x) print(f 当前安装的是 torchvision {tv_info[version]}) else: print( [FAIL] torchvision 未安装!) if error in tv_info: print(f 错误信息: {tv_info[error]}) compatible_prefix get_compatible_torchvision_version(torch_info[version]) if compatible_prefix: print(f\n 推荐安装命令:) cuda_ver torch_info.get(cuda_version, ) if cuda_ver: index_url fhttps://download.pytorch.org/whl/cu{cuda_ver.replace(., )} else: index_url https://download.pytorch.org/whl/cpu print(f pip install torchvision --index-url {index_url}) print(f 或指定版本: pip install torchvision{compatible_prefix}0 --index-url {index_url}) print() # 依赖检查 print(--- 依赖检查 ---) deps check_dependencies() for name, info in deps.items(): if info[installed]: print(f [OK] {name}: {info[version]}) else: print(f [MISSING] {name}) print() # torchvision 子模块测试 if tv_info[installed]: print(--- torchvision 子模块测试 ---) submodules [transforms, datasets, models, utils, io] for sm in submodules: try: mod importlib.import_module(ftorchvision.{sm}) print(f [OK] torchvision.{sm}) except ImportError as e: print(f [FAIL] torchvision.{sm}: {e}) except Exception as e: print(f [ERROR] torchvision.{sm}: {e}) print() # 修复建议 print( * 60) print( 修复建议) print( * 60) if not tv_info[installed]: print( 1. 安装 torchvision:) cuda_ver torch_info.get(cuda_version, ) if cuda_ver: url fhttps://download.pytorch.org/whl/cu{cuda_ver.replace(., )} else: url https://download.pytorch.org/whl/cpu print(f pip install torchvision --index-url {url}) print() print( 2. 或同时安装所有 PyTorch 包:) print(f pip install torch torchvision torchaudio --index-url {url}) elif error in tv_info: print(f torchvision 导入错误: {tv_info[error]}) print( 尝试重新安装:) print( pip uninstall torchvision -y) print( pip install torchvision --index-url https://download.pytorch.org/whl/cu118) missing_deps [name for name, info in deps.items() if not info[installed]] if missing_deps: print(f\n 缺少依赖: {, .join(missing_deps)}) for dep in missing_deps: pkg dep.split( )[0].lower() if pkg pil: pkg Pillow print(f pip install {pkg}) print() def fix_installation(): 自动修复安装 torch_info get_torch_info() if not torch_info[installed]: print(torch 未安装无法自动修复) return cuda_ver torch_info.get(cuda_version, ) if cuda_ver: index_url fhttps://download.pytorch.org/whl/cu{cuda_ver.replace(., )} else: index_url https://download.pytorch.org/whl/cpu print(f将使用索引: {index_url}) print() # 卸载现有版本 print(卸载现有 torchvision...) subprocess.run([sys.executable, -m, pip, uninstall, torchvision, -y]) # 安装 print(安装 torchvision...) result subprocess.run([ sys.executable, -m, pip, install, torchvision, --index-url, index_url ]) if result.returncode 0: print(\n安装成功! 验证...) tv_info get_torchvision_info() if tv_info[installed]: print(f torchvision 版本: {tv_info[version]}) print( [OK] 修复成功!) else: print( [FAIL] 安装成功但导入失败) if error in tv_info: print(f 错误: {tv_info[error]}) else: print(\n安装失败!) if __name__ __main__: diagnose() print(是否自动修复? (y/n): , end) try: choice input().strip().lower() if choice y: fix_installation() except EOFError: pass常见陷阱与注意事项1. torch 和 torchvision 版本必须匹配不匹配的版本会导致各种奇怪的错误。安装前务必检查版本对应关系# 检查版本兼容性 import torch print(ftorch: {torch.__version__}) # torchvision 版本对应表 # torch 2.0.x - torchvision 0.15.x # torch 2.1.x - torchvision 0.16.x # torch 2.2.x - torchvision 0.17.x2. 不要混用 conda 和 pip在同一个环境中选择一种包管理器安装所有 PyTorch 相关包# 全部用 conda conda install pytorch torchvision torchaudio pytorch-cuda11.8 -c pytorch -c nvidia -y # 或全部用 pip pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu1183. 注意安装源使用 pip 安装 GPU 版本时必须指定--index-url# 正确 - GPU 版本 pip install torchvision --index-url https://download.pytorch.org/whl/cu118 # 错误 - 可能安装 CPU 版本 pip install torchvision4. Pillow 版本兼容性torchvision 对 Pillow 版本有要求。如果 Pillow 版本过新或过旧可能导致兼容性问题# 安装兼容的 Pillow 版本 pip install Pillow5.3.0,!8.3.0,8.2.05. 验证所有子模块torchvision 包含多个子模块安装后应逐一验证# 验证所有子模块 from torchvision import transforms # 图像变换 from torchvision import datasets # 数据集 from torchvision import models # 预训练模型 from torchvision import utils # 工具函数 from torchvision import io # I/O 操作视频/图像 # 测试基本功能 transform transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) # 测试模型加载 model models.resnet18(pretrainedFalse) print(fResNet18 参数数量: {sum(p.numel() for p in model.parameters()):,})6. Docker 中安装 torchvision在 Dockerfile 中安装 torchvision 时确保与 torch 使用相同的 CUDA 版本FROM nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu22.04 RUN apt-get update apt-get install -y python3-pip RUN pip install torch torchvision torchaudio \ --index-url https://download.pytorch.org/whl/cu1187. 国内网络环境在国内pip 安装可能很慢。可以使用以下方式加速# 方法 1: 使用 PyTorch 官方索引GPU 版本必须用这个 pip install torchvision -i https://pypi.tuna.tsinghua.edu.cn/simple # 注意国内镜像可能只有 CPU 版本 # 方法 2: 下载 wheel 文件手动安装 # 访问 https://download.pytorch.org/whl/cu118/torchvision/ # 下载对应的 .whl 文件 pip install torchvision-0.15.2cu118-cp310-cp310-linux_x86_64.whl总结ModuleNotFoundError: No module named torchvision是 PyTorch 生态中常见的安装问题根本原因是 torchvision 作为独立包需要单独安装。核心要点总结torchvision 是独立包不随 torch 自动安装需要使用pip install torchvision或conda install torchvision单独安装。版本必须匹配torch 和 torchvision 有严格的版本对应关系。安装前检查版本兼容性使用官方安装命令同时安装所有包。使用官方安装命令pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cuXXX是最可靠的安装方式确保版本匹配和 CUDA 支持。不要混用 conda 和 pip在同一个环境中选择一种包管理器避免版本冲突和 DLL 问题。注意安装源pip 安装 GPU 版本时必须指定--index-url否则可能安装到 CPU 版本。检查依赖torchvision 依赖 Pillow、numpy 等库确保这些依赖已正确安装。验证所有子模块安装后验证 transforms、datasets、models、utils、io 等子模块是否都能正常导入。使用诊断脚本本文提供的诊断脚本可以自动检查 torch 版本、torchvision 安装状态、版本兼容性和依赖完整性快速定位问题。通过遵循本文的指南你应该能够顺利安装和导入 torchvision为计算机视觉开发提供完整的工具链支持。