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

导入torch.nn时出现ModuleNotFoundError: No module named 'torch._C'的问题求助

解决虚拟环境中导入torch.nn时出现的ModuleNotFoundError: No module named 'torch._C'问题

问题场景

在Windows 10系统、Python 3.10.6 64位的虚拟环境中,执行import torch.nn as nn时触发以下错误:

>>> import torch.nn as nn
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Mustapha\Envs\ml\lib\site-packages\torch\nn\__init__.py", line 1, in <module>
    from .modules import *  # noqa: F403
  File "C:\Users\Mustapha\Envs\ml\lib\site-packages\torch\nn\modules\__init__.py", line 1, in <module>
    from .module import Module
  File "C:\Users\Mustapha\Envs\ml\lib\site-packages\torch\nn\modules\module.py", line 7, in <module>
    from ..parameter import Parameter
  File "C:\Users\Mustapha\Envs\ml\lib\site-packages\torch\nn\parameter.py", line 2, in <module>
    from torch._C import _disabled_torch_function_impl
ModuleNotFoundError: No module named 'torch._C'

解决方案

该错误多由PyTorch安装不完整、环境版本不兼容或安装过程损坏导致,按以下步骤修复:

  • 确认虚拟环境激活状态
    确保当前终端已激活目标虚拟环境:

    • 若为venv环境:执行.\Envs\ml\Scripts\activate
    • 若为conda环境:执行conda activate ml
      激活后运行python --version,确认版本为3.10.6。
  • 完全卸载现有PyTorch
    根据安装方式执行卸载命令:

    • pip安装:pip uninstall -y torch torchvision torchaudio
    • conda安装:conda remove -y torch torchvision torchaudio
  • 重新安装适配版本的PyTorch
    在激活的虚拟环境中,根据硬件情况选择对应命令安装:

    • 带CUDA支持(NVIDIA显卡且兼容CUDA 11.8):
      pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
      
    • CPU版本:
      pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
      

    确保安装过程无网络中断,避免文件缺失。

  • 验证修复效果
    安装完成后,在终端中运行:

    import torch
    print(torch.__version__)
    import torch.nn as nn
    

    若能正常输出版本号且无报错,说明问题已解决。

注意事项

  • 必须在激活的虚拟环境内直接安装PyTorch,禁止从外部环境复制文件到虚拟环境。
  • 若使用conda创建环境,需指定Python版本:conda create -n ml python=3.10.6,避免版本不匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:18:35