在Google Colab运行EfficientNet代码遇ModuleNotFoundError问题求助
解决Google Colab中EfficientNet代码的ModuleNotFoundError问题
方案一:使用PyTorch官方内置的EfficientNet实现(推荐)
这是最简单的方式,无需手动处理utils模块,直接调用torchvision提供的预实现:
# 确保安装最新版torch和torchvision !pip install --upgrade torch torchvision import torch from torch import nn from torch.nn import functional as F # 导入官方EfficientNet模型及预训练权重 from torchvision.models import efficientnet_b0, EfficientNet_B0_Weights # 初始化带预训练权重的模型 model = efficientnet_b0(weights=EfficientNet_B0_Weights.DEFAULT)
方案二:自定义utils模块导入(适合需要自定义代码的场景)
错误原因说明
- 原代码中的
from .utils import ...是相对导入语法,仅适用于Python包结构内的模块调用,而Colab笔记本属于顶级脚本环境,无法识别这种相对路径。 - 错误日志中的
from python.utils import ...是误写,不存在名为python的第三方包,导致模块找不到。
具体解决步骤
方式A:手动创建utils.py文件
- 在Colab左侧文件栏点击「+」→「新建文件」,命名为
utils.py。 - 将
round_filters、round_repeats等所有需要的函数复制到这个文件中。 - 修改导入语句为:
import torch from torch import nn from torch.nn import functional as F # 直接导入同目录下的utils模块 from utils import ( round_filters, round_repeats, drop_connect, get_same_padding_conv2d, get_model_params, efficientnet_params, load_pretrained_weights, Swish, MemoryEfficientSwish, calculate_output_image_size )
方式B:克隆开源EfficientNet仓库
如果这些utils函数来自lukemelas的EfficientNet-PyTorch仓库,直接克隆仓库并添加路径:
# 克隆仓库到Colab !git clone https://github.com/lukemelas/EfficientNet-PyTorch.git # 将仓库路径添加到Python环境变量 import sys sys.path.append('/content/EfficientNet-PyTorch') # 正确导入utils模块 import torch from torch import nn from torch.nn import functional as F from efficientnet_pytorch.utils import ( round_filters, round_repeats, drop_connect, get_same_padding_conv2d, get_model_params, efficientnet_params, load_pretrained_weights, Swish, MemoryEfficientSwish, calculate_output_image_size )
内容的提问来源于stack exchange,提问作者Mahdi Davari
相关产品推荐
相关产品推荐

