在 Google Colab 中导入并运行 scenred 仓库(ModuleNotFoundError)
数据小陈
不要只用 import scenario_reduction 导入。需要先把 Jonas-eng/scenred 克隆到 Colab 的 /content,再让 Python 能找到 scenario_reduction 模块。如果仓库根目录有 setup.py 或 pyproject.toml,优先用 editable install 安装;涉及 Cython 时,先装 Cython。克隆仓库并不等于完成安装。
原因
Colab 运行时的工作目录和 sys.path 不会自动包含刚克隆的 GitHub 仓库,因此会报 ModuleNotFoundError: No module named 'scenario_reduction'。scenario_reduction 可能是仓库根目录下的 .py 文件,也可能是需要构建 Cython 扩展才能生成的模块,具体取决于仓库结构。
操作步骤
- 克隆仓库:
!git clone https://github.com/Jonas-eng/scenred.git /content/scenred
- 查看仓库结构,确认
scenario_reduction.py、scenario_reduction*.so或安装文件的位置:
!ls -la /content/scenred
!find /content/scenred -maxdepth 3 -name "scenario_reduction.py" -o -name "scenario_reduction*.so"
- 如果仓库根目录下直接有
scenario_reduction.py,把仓库根目录加入sys.path,然后导入:
import sys
sys.path.insert(0, "/content/scenred")
import scenario_reduction as scen_red
如果文件在子目录里,把 sys.path.insert 的路径换成实际包含 scenario_reduction.py 的目录。
- 如果仓库根目录有
setup.py或pyproject.toml,在仓库目录内安装会更稳妥。由于该仓库涉及 Cython,建议先装构建依赖:
%cd /content/scenred
!python -m pip install --upgrade pip setuptools wheel
!pip install cython numpy
!pip install -e .
安装完成后再导入:
import scenario_reduction as scen_red
- 如果安装或导入后仍然报错,重启 Colab 运行时(Runtime -> Restart runtime),再从头执行“克隆/安装/导入”这几步,避免旧路径缓存造成影响。
运行原示例
确认导入成功后,再运行你的场景约简代码:
import numpy as np
import scenario_reduction as scen_red
scenarios = np.random.rand(10, 30)
probabilities = np.random.rand(30)
probabilities = probabilities / np.sum(probabilities)
S = scen_red.ScenarioReduction(
scenarios,
probabilities=probabilities,
cost_func='general',
r=2,
scen0=np.zeros(10)
)
S.fast_forward_sel(n_sc_red=5, num_threads=4)
scenarios_reduced = S.scenarios_reduced
probabilities_reduced = S.probabilities_reduced
注意事项
- 如果
pip install -e .提示找不到setup.py或pyproject.toml,说明这个仓库不是标准可安装包,只能用sys.path指向模块所在目录。 - 如果 Cython 扩展构建失败,先检查报错是不是缺少编译器或头文件。Colab 一般自带基础编译环境,必要时安装
build-essential。 %cd和sys.path的修改只在当前 Colab 运行时有效;运行时重置后需要重新执行。- 除非确认 PyPI 上的包与
Jonas-eng/scenred是同一个项目,否则不要用pip install scenred代替本仓库安装。
备注:内容仅供参考。
